'use client';

import { useCallback, useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Search, Grid3X3, List, Plus,
  CheckCircle2, Loader2, Activity, AlertTriangle, FileText,
  ArrowRight, Star, Trash2, X, AlertOctagon,
  ShoppingCart, Euro, Sparkles,
} from 'lucide-react';
import type { Project } from '../data/projectsData';
import { useSession } from '../lib/session-context';
import { getPlanCapabilities, normalizeTier } from '../lib/plan-access';

const statusConfig: Record<string, { label: string; color: string; bg: string; icon: typeof CheckCircle2 }> = {
  completed: { label: 'Completed', color: 'text-success', bg: 'bg-success/15', icon: CheckCircle2 },
  converting: { label: 'Converting', color: 'text-accent-light', bg: 'bg-accent/15', icon: Loader2 },
  validating: { label: 'Validating', color: 'text-amber-400', bg: 'bg-amber-500/15', icon: Activity },
  analyzing: { label: 'Analyzing', color: 'text-purple-400', bg: 'bg-purple-500/15', icon: Loader2 },
  draft: { label: 'Draft', color: 'text-muted', bg: 'bg-surface-light', icon: FileText },
  failed: { label: 'Failed', color: 'text-danger', bg: 'bg-red-500/15', icon: AlertTriangle },
};

interface Props {
  onNavigate: (section: string, projectId?: string) => void;
  projects?: Project[];
  onRefresh?: () => void;
  isOwner?: boolean;
  isAdmin?: boolean;
  companyId?: string | null;
}

export default function ProjectsHub({ onNavigate, projects: propProjects, onRefresh, isOwner, isAdmin, companyId }: Props) {
  const projectsData = propProjects ?? [];
  const { user: sessionUser } = useSession();
  const capabilities = getPlanCapabilities(normalizeTier(sessionUser?.tier));
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [starred, setStarred] = useState<Set<string>>(new Set());
  const [showBuySlotModal, setShowBuySlotModal] = useState(false);
  const [buySlotProcessing, setBuySlotProcessing] = useState(false);
  const [buySlotSuccess, setBuySlotSuccess] = useState(false);
  
  // Delete confirmation modal state
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [projectToDelete, setProjectToDelete] = useState<Project | null>(null);
  const [deleteConfirmText, setDeleteConfirmText] = useState('');
  const [isDeleting, setIsDeleting] = useState(false);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [maxProjects, setMaxProjects] = useState<number | null>(null);
  const [companyProjectCount, setCompanyProjectCount] = useState<number | null>(null);

  // Delete all modal state
  const [showDeleteAllModal, setShowDeleteAllModal] = useState(false);
  const [deleteAllConfirmText, setDeleteAllConfirmText] = useState('');
  const [deleteAllError, setDeleteAllError] = useState<string | null>(null);
  const [isDeletingAll, setIsDeletingAll] = useState(false);

  const filtered = projectsData.filter(p => {
    const matchSearch = p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      p.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      p.tags.some(t => t.includes(searchQuery.toLowerCase()));
    const matchStatus = statusFilter === 'all' || p.status === statusFilter;
    return matchSearch && matchStatus;
  });

  const fetchSlotData = useCallback(() => {
    if (!companyId) return;
    fetch(`/api/companies/${companyId}`, { credentials: 'include' })
      .then((res) => (res.ok ? res.json() : null))
      .then((data) => {
        const cap = data?.company?.maxConversions;
        if (typeof cap === 'number') setMaxProjects(cap);
        const used = data?.company?.conversionCount;
        if (typeof used === 'number') setCompanyProjectCount(used);
      })
      .catch(() => {});
  }, [companyId]);

  useEffect(() => {
    fetchSlotData();
  }, [fetchSlotData]);

  const effectiveProjectCount = typeof companyProjectCount === 'number' ? companyProjectCount : projectsData.length;
  const isAtProjectLimit = typeof maxProjects === 'number' && effectiveProjectCount >= maxProjects;

  const toggleStar = (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setStarred(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const openDeleteModal = (project: Project, e: React.MouseEvent) => {
    e.stopPropagation();
    setProjectToDelete(project);
    setDeleteConfirmText('');
    setDeleteError(null);
    setShowDeleteModal(true);
  };

  const closeDeleteModal = () => {
    setShowDeleteModal(false);
    setProjectToDelete(null);
    setDeleteConfirmText('');
    setDeleteError(null);
  };

  const handleDeleteProject = async () => {
    if (!projectToDelete) return;

    if (deleteConfirmText !== 'I agree, delete everything') {
      setDeleteError('Please type the confirmation text exactly as shown');
      return;
    }

    if (!isAdmin && !companyId) {
      setDeleteError('You must belong to a company to delete projects. Please contact support.');
      return;
    }

    setIsDeleting(true);
    setDeleteError(null);

    try {
      const url = isAdmin
        ? `/api/admin/conversions/${projectToDelete.id}`
        : `/api/companies/${companyId}/conversions/${projectToDelete.id}`;
      const res = await fetch(url, {
        method: 'DELETE',
        credentials: 'include',
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Failed to delete project');
      }

      closeDeleteModal();
      onRefresh?.();
    } catch (err) {
      setDeleteError(err instanceof Error ? err.message : 'Failed to delete project');
    } finally {
      setIsDeleting(false);
    }
  };

  const handleDeleteAllProjects = async () => {
    if (deleteAllConfirmText !== 'delete all conversions') {
      setDeleteAllError('Please type the confirmation text exactly as shown.');
      return;
    }
    setIsDeletingAll(true);
    setDeleteAllError(null);
    try {
      const res = await fetch('/api/admin/conversions', { method: 'DELETE', credentials: 'include' });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Failed to delete projects');
      }
      setShowDeleteAllModal(false);
      setDeleteAllConfirmText('');
      onRefresh?.();
    } catch (err) {
      setDeleteAllError(err instanceof Error ? err.message : 'Failed to delete projects');
    } finally {
      setIsDeletingAll(false);
    }
  };

  const renderCard = (p: Project, i: number) => {
    const sc = statusConfig[p.status];
    const Icon = sc.icon;
    const progress = p.totalFiles > 0 ? Math.round((p.convertedFiles / p.totalFiles) * 100) : 0;

    return (
      <motion.div
        key={p.id}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: i * 0.05 }}
        onClick={() => onNavigate('conversion-dashboard', p.id)}
        className="glass rounded-xl p-5 hover:border-accent/30 transition-all cursor-pointer group relative"
      >
        <div className="flex items-start justify-between mb-3">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <h3 className="text-sm font-semibold text-foreground truncate">{p.name}</h3>
              <button onClick={(e) => toggleStar(p.id, e)} className="cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity">
                <Star className={`w-3.5 h-3.5 ${starred.has(p.id) ? 'text-amber-400 fill-amber-400' : 'text-muted'}`} />
              </button>
            </div>
            <p className="text-[11px] text-muted mt-0.5 line-clamp-2">{p.description}</p>
          </div>
          <span className={`flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full font-medium ${sc.color} ${sc.bg} flex-shrink-0 ml-3`}>
            <Icon className={`w-3 h-3 ${p.status === 'converting' || p.status === 'analyzing' ? 'animate-spin' : ''}`} />
            {sc.label}
          </span>
        </div>

        <div className="flex items-center gap-2 text-[11px] text-muted mb-3">
          <span className="font-mono">{p.sourceLanguage}</span>
          <ArrowRight className="w-3 h-3 text-accent-light" />
          <span className="font-mono">{p.targetLanguage}</span>
        </div>

        {p.totalFiles > 0 && (
          <div className="mb-3">
            <div className="flex items-center justify-between text-[10px] mb-1">
              <span className="text-muted">Progress</span>
              <span className="text-foreground font-medium">{progress}%</span>
            </div>
            <div className="h-1.5 bg-surface-light rounded-full overflow-hidden">
              <motion.div
                initial={{ width: 0 }}
                animate={{ width: `${progress}%` }}
                transition={{ duration: 1, delay: i * 0.1 }}
                className="h-full rounded-full bg-accent"
              />
            </div>
          </div>
        )}

        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <div className="flex -space-x-1.5">
              {p.team.slice(0, 3).map((m) => (
                <div key={m.name} className="w-6 h-6 rounded-full bg-surface-light border-2 border-surface flex items-center justify-center text-[9px] font-bold text-muted" title={m.name}>
                  {m.avatar}
                </div>
              ))}
              {p.team.length > 3 && (
                <div className="w-6 h-6 rounded-full bg-surface-light border-2 border-surface flex items-center justify-center text-[9px] text-muted">
                  +{p.team.length - 3}
                </div>
              )}
            </div>
          </div>
          <div className="flex items-center gap-3 text-[10px] text-muted">
            {p.accuracy > 0 && <span className="font-mono">{p.accuracy}% acc</span>}
            <span>{new Date(p.updatedAt).toLocaleDateString('it-IT', { day: '2-digit', month: 'short' })}</span>
            {(isOwner || isAdmin) && (
              <button
                onClick={(e) => openDeleteModal(p, e)}
                className="p-1.5 rounded hover:bg-red-500/10 cursor-pointer text-muted hover:text-red-400 transition-colors"
                title="Delete project permanently"
              >
                <Trash2 className="w-3.5 h-3.5" />
              </button>
            )}
          </div>
        </div>

        {p.tags.length > 0 && (
          <div className="flex flex-wrap gap-1 mt-3">
            {p.tags.slice(0, 3).map(t => (
              <span key={t} className="text-[9px] px-1.5 py-0.5 rounded-full bg-surface-light text-muted">{t}</span>
            ))}
            {p.tags.length > 3 && <span className="text-[9px] text-muted">+{p.tags.length - 3}</span>}
          </div>
        )}
      </motion.div>
    );
  };

  const renderListItem = (p: Project, i: number) => {
    const sc = statusConfig[p.status];
    const Icon = sc.icon;
    const progress = p.totalFiles > 0 ? Math.round((p.convertedFiles / p.totalFiles) * 100) : 0;

    return (
      <motion.div
        key={p.id}
        initial={{ opacity: 0, x: -10 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ delay: i * 0.03 }}
        onClick={() => onNavigate('conversion-dashboard', p.id)}
        className="glass rounded-lg p-4 flex items-center gap-4 hover:border-accent/30 transition-all cursor-pointer group"
      >
        <button onClick={(e) => toggleStar(p.id, e)} className="cursor-pointer">
          <Star className={`w-3.5 h-3.5 ${starred.has(p.id) ? 'text-amber-400 fill-amber-400' : 'text-muted opacity-0 group-hover:opacity-100 transition-opacity'}`} />
        </button>

        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-foreground truncate">{p.name}</p>
          <p className="text-[11px] text-muted truncate">{p.description}</p>
        </div>

        <div className="flex items-center gap-2 text-[11px] text-muted w-36">
          <span className="font-mono">{p.sourceLanguage}</span>
          <ArrowRight className="w-3 h-3 text-accent-light" />
          <span className="font-mono truncate">{p.targetLanguage}</span>
        </div>

        {p.totalFiles > 0 ? (
          <div className="w-24">
            <div className="h-1.5 bg-surface-light rounded-full overflow-hidden">
              <div className="h-full rounded-full bg-accent" style={{ width: `${progress}%` }} />
            </div>
            <p className="text-[10px] text-muted mt-0.5 text-right">{progress}%</p>
          </div>
        ) : (
          <div className="w-24 text-[10px] text-muted text-right">—</div>
        )}

        <div className="flex -space-x-1.5 w-20 justify-center">
          {p.team.slice(0, 3).map((m) => (
            <div key={m.name} className="w-6 h-6 rounded-full bg-surface-light border-2 border-surface flex items-center justify-center text-[9px] font-bold text-muted" title={m.name}>
              {m.avatar}
            </div>
          ))}
        </div>

        <span className={`flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full font-medium w-24 justify-center ${sc.color} ${sc.bg}`}>
          <Icon className={`w-3 h-3 ${p.status === 'converting' || p.status === 'analyzing' ? 'animate-spin' : ''}`} />
          {sc.label}
        </span>

        <span className="text-[10px] text-muted w-16 text-right">
          {new Date(p.updatedAt).toLocaleDateString('it-IT', { day: '2-digit', month: 'short' })}
        </span>

        {isOwner && (
          <button
            onClick={(e) => openDeleteModal(p, e)}
            className="p-1.5 rounded hover:bg-red-500/10 cursor-pointer text-muted hover:text-red-400 transition-colors"
            title="Delete project permanently"
          >
            <Trash2 className="w-3.5 h-3.5" />
          </button>
        )}
      </motion.div>
    );
  };

  return (
    <div className="space-y-6">
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-foreground">Conversions</h2>
          <p className="text-sm text-muted mt-1">{projectsData.length} migration conversion{projectsData.length !== 1 ? 's' : ''}</p>
          {typeof maxProjects === 'number' && (
            <p className={`text-xs mt-1 ${isAtProjectLimit ? 'text-amber-400' : 'text-muted'}`}>
              Conversion slots: <span className="font-semibold text-foreground">{effectiveProjectCount}/{maxProjects}</span>
              {isAtProjectLimit ? ' · Limit reached — purchase an extra slot to continue.' : ''}
              {!isAtProjectLimit && ' · Delete a conversion to free one slot.'}
            </p>
          )}
        </div>
        <div className="flex items-center gap-2">
          {isAdmin && projectsData.length > 0 && (
            <button
              onClick={() => { setDeleteAllConfirmText(''); setDeleteAllError(null); setShowDeleteAllModal(true); }}
              className="px-4 py-2.5 rounded-lg bg-red-500/10 text-red-400 text-sm font-semibold border border-red-500/20 hover:bg-red-500/20 transition flex items-center gap-2 cursor-pointer"
            >
              <Trash2 className="w-4 h-4" /> Delete All
            </button>
          )}
          {isAtProjectLimit && (isOwner || isAdmin) && (
            <button
              onClick={() => { setBuySlotSuccess(false); setShowBuySlotModal(true); }}
              className="px-4 py-2.5 rounded-lg bg-amber-500/15 text-amber-400 text-sm font-semibold border border-amber-500/25 hover:bg-amber-500/25 transition flex items-center gap-2 cursor-pointer"
            >
              <ShoppingCart className="w-4 h-4" /> Buy Extra Slot
            </button>
          )}
          <button
            onClick={() => onNavigate('new-conversion')}
            disabled={isAtProjectLimit}
            className="px-5 py-2.5 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity flex items-center gap-2 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Plus className="w-4 h-4" /> New Conversion
          </button>
        </div>
      </motion.div>

      <div className="flex items-center gap-3">
        <div className="flex items-center gap-2 glass rounded-lg px-3 py-2 flex-1 max-w-md">
          <Search className="w-4 h-4 text-muted" />
          <input
            type="text"
            placeholder="Search conversions..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="bg-transparent text-sm text-foreground outline-none placeholder-muted flex-1"
          />
        </div>

        <div className="flex items-center gap-1 glass rounded-lg p-1">
          {['all', 'analyzing', 'converting', 'validating', 'completed', 'draft'].map(s => (
            <button
              key={s}
              onClick={() => setStatusFilter(s)}
              className={`px-3 py-1.5 rounded-md text-xs font-medium transition-all cursor-pointer ${
                statusFilter === s ? 'bg-accent/15 text-accent-light' : 'text-muted hover:text-foreground'
              }`}
            >
              {s === 'all' ? 'All' : s.charAt(0).toUpperCase() + s.slice(1)}
            </button>
          ))}
        </div>

        <div className="flex items-center gap-0.5 glass rounded-lg p-1">
          <button
            onClick={() => setViewMode('grid')}
            className={`p-1.5 rounded-md cursor-pointer transition-all ${viewMode === 'grid' ? 'bg-accent/15 text-accent-light' : 'text-muted hover:text-foreground'}`}
          >
            <Grid3X3 className="w-4 h-4" />
          </button>
          <button
            onClick={() => setViewMode('list')}
            className={`p-1.5 rounded-md cursor-pointer transition-all ${viewMode === 'list' ? 'bg-accent/15 text-accent-light' : 'text-muted hover:text-foreground'}`}
          >
            <List className="w-4 h-4" />
          </button>
        </div>
      </div>

      <AnimatePresence mode="wait">
        {viewMode === 'grid' ? (
          <motion.div key="grid" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="grid grid-cols-3 gap-4">
            {filtered.map((p, i) => renderCard(p, i))}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: filtered.length * 0.05 }}
              onClick={() => onNavigate('new-conversion')}
              className="glass rounded-xl p-5 border-dashed border-2 border-border hover:border-accent/40 transition-all cursor-pointer flex flex-col items-center justify-center gap-3 min-h-[200px]"
            >
              <div className="w-12 h-12 rounded-full bg-surface-light flex items-center justify-center">
                <Plus className="w-5 h-5 text-muted" />
              </div>
              <p className="text-sm text-muted font-medium">Create New Conversion</p>
            </motion.div>
          </motion.div>
        ) : (
          <motion.div key="list" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="space-y-2">
            {filtered.map((p, i) => renderListItem(p, i))}
          </motion.div>
        )}
      </AnimatePresence>

      {/* Delete Confirmation Modal */}
      <AnimatePresence>
        {showDeleteModal && projectToDelete && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
          >
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 12 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="w-full max-w-lg glass rounded-2xl p-6 border border-red-500/30"
            >
              {/* Header */}
              <div className="flex items-center justify-between mb-5">
                <div className="flex items-center gap-2">
                  <AlertOctagon className="w-5 h-5 text-red-400" />
                  <h3 className="text-base font-bold text-foreground">Delete Conversion Permanently</h3>
                </div>
                <button
                  onClick={closeDeleteModal}
                  className="p-1.5 rounded hover:bg-surface-light cursor-pointer"
                >
                  <X className="w-4 h-4 text-muted" />
                </button>
              </div>

              {/* Warning Message */}
              <div className="mb-5 p-4 rounded-lg bg-red-500/10 border border-red-500/20">
                <p className="text-sm text-red-400 font-medium mb-2">
                  Warning: This action cannot be undone
                </p>
                <p className="text-xs text-muted">
                  All the data related to the conversion <strong className="text-foreground">{projectToDelete.name}</strong> will be deleted completely with no possibility to ever retrieve it. This includes all migration data, code, analysis results, and activity logs.
                </p>
              </div>

              {/* Error Message */}
              {deleteError && (
                <div className="mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs text-red-400">
                  {deleteError}
                </div>
              )}

              {/* Confirmation Input */}
              <div className="mb-5">
                <label className="block text-xs font-medium text-muted mb-2">
                  To confirm, type <span className="text-red-400 font-semibold">I agree, delete everything</span> below:
                </label>
                <input
                  type="text"
                  value={deleteConfirmText}
                  onChange={(e) => setDeleteConfirmText(e.target.value)}
                  placeholder="I agree, delete everything"
                  className="w-full bg-surface border border-border rounded-lg px-3 py-2 text-sm text-foreground outline-none focus:border-red-400/60 transition"
                />
              </div>

              {/* Action Buttons */}
              <div className="flex gap-3">
                <button
                  type="button"
                  onClick={closeDeleteModal}
                  className="flex-1 py-2.5 rounded-lg glass-light text-sm text-muted hover:text-foreground transition cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  onClick={handleDeleteProject}
                  disabled={isDeleting || deleteConfirmText !== 'I agree, delete everything'}
                  className="flex-1 py-2.5 rounded-lg bg-red-500/20 hover:bg-red-500/30 text-red-400 text-sm font-semibold transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                >
                  {isDeleting ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" /> Deleting…
                    </>
                  ) : (
                    <>
                      <Trash2 className="w-4 h-4" /> I agree, delete everything
                    </>
                  )}
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Delete All Projects modal */}
      <AnimatePresence>
        {showDeleteAllModal && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
            <motion.div initial={{ opacity: 0, scale: 0.95, y: 12 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }}
              className="w-full max-w-md glass rounded-2xl p-6 border border-red-500/30">
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-red-500/15 flex items-center justify-center">
                    <AlertTriangle className="w-5 h-5 text-red-400" />
                  </div>
                  <div>
                    <h3 className="text-base font-bold text-foreground">Delete All Conversions</h3>
                    <p className="text-xs text-red-400 mt-0.5">This cannot be undone</p>
                  </div>
                </div>
                <button onClick={() => setShowDeleteAllModal(false)} className="p-1.5 rounded hover:bg-surface-light cursor-pointer">
                  <X className="w-4 h-4 text-muted" />
                </button>
              </div>

              <p className="text-sm text-muted mb-5 leading-relaxed">
                All <span className="font-semibold text-foreground">{projectsData.length}</span> conversion{projectsData.length !== 1 ? 's' : ''} will be permanently deleted — including all migration data, code, analysis results, and activity logs. There is no recovery.
              </p>

              {deleteAllError && (
                <div className="mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs text-red-400">
                  {deleteAllError}
                </div>
              )}

              <p className="text-xs text-muted mb-2">
                To confirm, type <span className="text-red-400 font-semibold">delete all conversions</span> below:
              </p>
              <input
                type="text"
                value={deleteAllConfirmText}
                onChange={e => setDeleteAllConfirmText(e.target.value)}
                placeholder="delete all conversions"
                className="w-full bg-surface border border-border rounded-lg px-3 py-2.5 text-sm text-foreground outline-none focus:border-red-500/50 transition mb-5"
              />

              <div className="flex gap-3">
                <button type="button" onClick={() => setShowDeleteAllModal(false)}
                  className="flex-1 py-2.5 rounded-lg glass-light text-sm text-muted hover:text-foreground transition cursor-pointer">
                  Cancel
                </button>
                <button
                  onClick={() => void handleDeleteAllProjects()}
                  disabled={isDeletingAll || deleteAllConfirmText !== 'delete all conversions'}
                  className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg bg-red-500/15 text-red-400 text-sm font-semibold border border-red-500/30 hover:bg-red-500/25 transition cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed">
                  {isDeletingAll
                    ? <><div className="w-4 h-4 border border-current border-t-transparent rounded-full animate-spin" /> Deleting…</>
                    : <><Trash2 className="w-4 h-4" /> Delete all conversions</>}
                </button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Buy Extra Conversion Slot Modal */}
      <AnimatePresence>
        {showBuySlotModal && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4">
            <motion.div initial={{ opacity: 0, scale: 0.95, y: 12 }} animate={{ opacity: 1, scale: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }}
              className="w-full max-w-md glass rounded-2xl p-6 border border-amber-500/20">
              <div className="flex items-center justify-between mb-5">
                <div className="flex items-center gap-2">
                  <div className="w-9 h-9 rounded-full bg-amber-500/15 flex items-center justify-center">
                    <ShoppingCart className="w-4 h-4 text-amber-400" />
                  </div>
                  <h3 className="text-base font-bold text-foreground">Buy Extra Conversion Slot</h3>
                </div>
                <button onClick={() => setShowBuySlotModal(false)} className="p-1.5 rounded hover:bg-surface-light cursor-pointer">
                  <X className="w-4 h-4 text-muted" />
                </button>
              </div>

              {buySlotSuccess ? (
                <div className="text-center py-6 space-y-3">
                  <div className="w-14 h-14 rounded-full bg-green-500/15 flex items-center justify-center mx-auto">
                    <CheckCircle2 className="w-7 h-7 text-green-400" />
                  </div>
                  <p className="text-sm font-semibold text-foreground">Slot purchased successfully!</p>
                  <p className="text-xs text-muted">Your conversion limit has been increased by one. You can now create a new conversion.</p>
                  <button onClick={() => { setShowBuySlotModal(false); onRefresh?.(); }}
                    className="px-6 py-2.5 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition cursor-pointer mt-2">
                    Close
                  </button>
                </div>
              ) : (
                <>
                  <div className="glass-light rounded-xl p-4 mb-5 space-y-3">
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-muted">Your plan</span>
                      <span className="font-semibold text-foreground capitalize">{capabilities.tier}</span>
                    </div>
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-muted">Extra slot price</span>
                      <span className="font-bold text-foreground flex items-center gap-1">
                        <Euro className="w-3.5 h-3.5 text-accent-light" />
                        {capabilities.extraConversionPriceEur.toLocaleString('de-DE')},00
                      </span>
                    </div>
                    <div className="h-px bg-border" />
                    <div className="flex items-center gap-1.5 text-[11px] text-muted">
                      <Sparkles className="w-3.5 h-3.5 text-accent-light shrink-0" />
                      Higher-tier plans get better pricing: Starter €5,000 · Professional €4,000 · Enterprise €2,500 per extra slot.
                    </div>
                  </div>

                  <div className="flex gap-3">
                    <button type="button" onClick={() => setShowBuySlotModal(false)}
                      className="flex-1 py-2.5 rounded-lg glass-light text-sm text-muted hover:text-foreground transition cursor-pointer">
                      Cancel
                    </button>
                    <button
                      onClick={async () => {
                        if (!companyId) return;
                        setBuySlotProcessing(true);
                        try {
                          const res = await fetch(`/api/companies/${companyId}/slots`, {
                            method: 'POST',
                            credentials: 'include',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ quantity: 1 }),
                          });
                          if (!res.ok) throw new Error('Purchase failed');
                          setBuySlotSuccess(true);
                          fetchSlotData();
                          onRefresh?.();
                        } catch {
                          // keep modal open so user can retry
                        } finally {
                          setBuySlotProcessing(false);
                        }
                      }}
                      disabled={buySlotProcessing}
                      className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition cursor-pointer disabled:opacity-60 disabled:cursor-not-allowed"
                    >
                      {buySlotProcessing
                        ? <><Loader2 className="w-4 h-4 animate-spin" /> Processing…</>
                        : <><ShoppingCart className="w-4 h-4" /> Purchase</>}
                    </button>
                  </div>
                </>
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
