'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  FileCode2, Code2, Clock, AlertTriangle, Target, GitBranch,
  Shield, Database, Play, Settings, Users, Calendar,
  Activity, CheckCircle2, Loader2, Save, LayoutDashboard,
  ArrowRight, Zap, Tag, Building2, Globe, Lock, Server,
  ChevronRight, Circle, TrendingUp, BarChart3, Cpu
} from 'lucide-react';
import type { Project } from '../data/projectsData';
import { api } from '../lib/api';

interface Props {
  projectId: string;
  onNavigate: (section: string, projectId?: string) => void;
  maxReachedStep?: number;
  project?: Project | null;
}

const statusConfig: Record<string, { label: string; color: string; bg: string; dot: string; icon: typeof CheckCircle2; spin?: boolean }> = {
  completed:  { label: 'Completed',  color: 'text-green-400',   bg: 'bg-green-500/10',   dot: 'bg-green-400',   icon: CheckCircle2 },
  converting: { label: 'Converting', color: 'text-accent-light', bg: 'bg-accent/10',      dot: 'bg-accent',     icon: Loader2, spin: true },
  validating: { label: 'Validating', color: 'text-amber-400',   bg: 'bg-amber-500/10',  dot: 'bg-amber-400',  icon: Loader2, spin: true },
  analyzing:  { label: 'Analyzing',  color: 'text-sky-400',     bg: 'bg-sky-500/10',    dot: 'bg-sky-400',    icon: Loader2, spin: true },
  draft:      { label: 'Draft',      color: 'text-muted',       bg: 'bg-surface',        dot: 'bg-muted',      icon: Circle },
  failed:     { label: 'Failed',     color: 'text-red-400',     bg: 'bg-red-500/10',    dot: 'bg-red-400',    icon: AlertTriangle },
};

const PIPELINE_STAGES = [
  { id: 'conversion-dashboard', label: 'Setup',       step: 0 },
  { id: 'repository',        label: 'Repository',  step: 1 },
  { id: 'pre-analysis',      label: 'Analysis',    step: 2 },
  { id: 'migration-flow',    label: 'Conversion',  step: 3 },
  { id: 'comparison',        label: 'Code Review', step: 4 },
  { id: 'verification',      label: 'Validation',  step: 5 },
  { id: 'security',          label: 'Security',    step: 6 },
  { id: 'artifacts',         label: 'Artifacts',   step: 7 },
  { id: 'export',            label: 'Export',      step: 8 },
];

/** Past last stage index so `progress > step` marks the final step done (matches sectionStepMap / navigation). */
const PIPELINE_COMPLETE_PROGRESS = PIPELINE_STAGES[PIPELINE_STAGES.length - 1].step + 1;

function langLabel(id: string) {
  const map: Record<string, string> = {
    // Legacy mainframe
    cobol: 'COBOL', pli: 'PL/I', rpg: 'RPG/400', natural: 'Natural/ADABAS',
    jcl: 'JCL', rexx: 'REXX/NetREXX', clist: 'CLIST/ISPF',
    assembly: 'Assembly', ada: 'Ada', fortran: 'Fortran', mumps: 'MUMPS/M',
    // Legacy business / ERP
    sap: 'SAP ABAP', oracle: 'Oracle PL/SQL', tsql: 'T-SQL/SQL Server',
    db2: 'DB2 SQL', pascal: 'Pascal/Delphi', vb6: 'Visual Basic 6',
    powerbuilder: 'PowerBuilder', progress: 'Progress 4GL', coldfusion: 'ColdFusion',
    clipper: 'Clipper/xBase', visualfoxpro: 'Visual FoxPro', lotusscript: 'LotusScript',
    informix: 'Informix 4GL', sas: 'SAS', pick: 'PICK/MultiValue',
    uniface: 'UNIFACE', apl: 'APL/Dyalog/J/K', smalltalk: 'Smalltalk',
    // Legacy PC / desktop
    objective_c: 'Objective-C', actionscript: 'ActionScript/Flash',
    basic: 'BASIC/QuickBASIC', tcl: 'Tcl/Tk',
    // Modern systems
    c: 'C', cpp: 'C++', java: 'Java', csharp: 'C#', python: 'Python',
    javascript: 'JavaScript', typescript: 'TypeScript', php: 'PHP',
    ruby: 'Ruby', go: 'Go', rust: 'Rust', swift: 'Swift',
    kotlin: 'Kotlin', scala: 'Scala', elixir: 'Elixir', clojure: 'Clojure',
    fsharp: 'F#', haskell: 'Haskell', dart: 'Dart', lua: 'Lua',
    perl: 'Perl', r: 'R', julia: 'Julia', crystal: 'Crystal',
    nim: 'Nim', zig: 'Zig', vlang: 'V', odin: 'Odin',
    wasm: 'WebAssembly/WASI', sql: 'SQL', graphql: 'GraphQL', matlab: 'MATLAB',
    powershell: 'PowerShell', bash: 'Bash/Shell', groovy: 'Groovy',
    scheme: 'Scheme', lisp: 'Common Lisp', erlang: 'Erlang/OTP',
    ocaml: 'OCaml', elm: 'Elm', purescript: 'PureScript',
    verilog: 'Verilog/SystemVerilog', vhdl: 'VHDL', solidity: 'Solidity',
    move: 'Move', coffeescript: 'CoffeeScript', haxe: 'Haxe',
    gdscript: 'GDScript', glsl: 'GLSL/HLSL', gleam: 'Gleam',
    // Logic / formal / scientific
    prolog: 'Prolog/Datalog', forth: 'Forth/Factor', coq: 'Coq/Rocq',
    lean4: 'Lean 4', idris2: 'Idris 2', wolfram: 'Wolfram/Mathematica',
    // Platform / enterprise CRM
    apex: 'Salesforce Apex', ballerina: 'Ballerina', hack: 'Hack/HHVM',
    reason: 'ReScript/Reason', mojo: 'Mojo', d: 'D Language', nix: 'Nix/NixOS',
    // Industrial / scientific / simulation
    labview: 'LabVIEW/G', simulink: 'Simulink/Stateflow', plc: 'IEC 61131-3/PLC',
    xslt: 'XSLT/XQuery', spss: 'SPSS/Stata',
    // Target-specific
    node: 'Node.js', rpg_free: 'RPG Free (**FREE)', java_legacy: 'Java Legacy',
    dotnet_legacy: '.NET Framework', vbnet: 'VB.NET', classic_asp: 'Classic ASP',
    php_legacy: 'PHP Legacy', perl_legacy: 'Perl Legacy',
    pl1: 'PL/I', abap: 'ABAP',
  };
  return map[id] ?? id;
}

export default function ProjectDashboard({ projectId, onNavigate, maxReachedStep = 0, project: propProject }: Props) {
  const [activeTab, setActiveTab] = useState<'overview' | 'settings'>('overview');
  const [cfg, setCfg] = useState<Record<string, any>>({});
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    if (propProject?.config) setCfg(propProject.config as Record<string, any>);
  }, [propProject]);

  const cfgSet = (key: string, val: any) => setCfg(prev => ({ ...prev, [key]: val }));

  const saveSettings = async () => {
    setSaving(true);
    try {
      await api.updateProject(projectId, { config: cfg });
      setSaved(true);
      setTimeout(() => setSaved(false), 2500);
    } catch { /* non-blocking */ }
    setSaving(false);
  };

  if (!propProject) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-accent" />
      </div>
    );
  }

  const project = propProject;
  const sc = statusConfig[project.status] ?? statusConfig.draft;
  const StatusIcon = sc.icon;
  const isDraft = project.status === 'draft';
  const isCompleted = project.status === 'completed';
  const isActive = ['analyzing', 'converting', 'validating'].includes(project.status);

  // Bottom stepper must align with top pipeline: `status: completed` implies all stages done even if DB `maxReachedStep` never advanced past migration.
  const effectiveReached = isCompleted
    ? Math.max(maxReachedStep, PIPELINE_COMPLETE_PROGRESS)
    : maxReachedStep;

  // Derive primary CTA
  const cta = isCompleted
    ? { label: 'View Results', icon: CheckCircle2, section: 'export', style: 'bg-green-500 hover:bg-green-400' }
    : isDraft
    ? { label: 'Start Conversion', icon: Zap, section: 'migration-flow', style: 'gradient-accent glow-accent' }
    : { label: 'Resume', icon: Play, section: maxReachedStep >= 3 ? 'migration-flow' : maxReachedStep >= 2 ? 'pre-analysis' : 'repository', style: 'gradient-accent' };

  const handleCTA = async () => {
    if (isDraft) {
      try { await api.updateProject(projectId, { status: 'analyzing' }); } catch {}
    }
    onNavigate(cta.section, projectId);
  };

  const configHighlights = [
    cfg.selectedPriority && { icon: Target,    label: 'Priority',     value: cfg.selectedPriority },
    cfg.riskLevel        && { icon: Shield,    label: 'Risk Level',    value: cfg.riskLevel },
    cfg.intent && { icon: Zap,   label: 'Intent',      value: cfg.intent },
    cfg.architecturePattern && { icon: Server, label: 'Architecture',  value: cfg.architecturePattern },
    cfg.deadline         && { icon: Calendar,  label: 'Deadline',      value: new Date(cfg.deadline).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', year: 'numeric' }) },
    cfg.selectedCompliance?.length > 0 && { icon: Lock, label: 'Compliance', value: (cfg.selectedCompliance as string[]).join(', ').toUpperCase() },
  ].filter(Boolean) as { icon: any; label: string; value: string }[];

  return (
    <div className="space-y-5">

      {/* ── Header ── */}
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}
        className="glass rounded-xl p-6">
        <div className="flex items-start justify-between gap-4">
          <div className="min-w-0">
            <div className="flex items-center gap-3 mb-1.5 flex-wrap">
              <h2 className="text-xl font-bold text-foreground truncate">{project.name}</h2>
              <span className={`flex items-center gap-1.5 text-[11px] px-2.5 py-1 rounded-full font-semibold ${sc.color} ${sc.bg} border border-current/20 shrink-0`}>
                <StatusIcon className={`w-3 h-3 ${sc.spin ? 'animate-spin' : ''}`} />
                {sc.label}
              </span>
              {(project.tags ?? []).map((tag: string) => (
                <span key={tag} className="text-[10px] px-2 py-0.5 rounded-full bg-accent/10 text-accent-light border border-accent/20 font-medium shrink-0">{tag}</span>
              ))}
            </div>
            <p className="text-sm text-muted mb-4 leading-relaxed">{project.description}</p>
            <div className="flex flex-wrap items-center gap-x-5 gap-y-1.5 text-xs text-muted">
              {project.repoUrl && (
                <span className="flex items-center gap-1.5">
                  <GitBranch className="w-3.5 h-3.5 text-accent-light" />
                  <span className="font-mono">{project.repoUrl.replace(/^https?:\/\/[^/]+\//, '')}</span>
                </span>
              )}
              <span className="flex items-center gap-1.5">
                <FileCode2 className="w-3.5 h-3.5 text-purple-400" />
                {langLabel(project.sourceLanguage)} → {langLabel(project.targetLanguage)}
              </span>
              {project.team?.length > 0 && (
                <span className="flex items-center gap-1.5">
                  <Users className="w-3.5 h-3.5" />
                  {project.team.length} team member{project.team.length !== 1 ? 's' : ''}
                </span>
              )}
              <span className="flex items-center gap-1.5">
                <Calendar className="w-3.5 h-3.5" />
                Created {new Date(project.createdAt).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', year: 'numeric' })}
              </span>
            </div>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <button onClick={handleCTA}
              className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-white text-sm font-semibold transition-all cursor-pointer ${cta.style}`}>
              <cta.icon className="w-4 h-4" />{cta.label}
            </button>
          </div>
        </div>
      </motion.div>

      {/* ── Pipeline Stage Tracker ── */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.05 }}
        className="glass rounded-xl p-4">
        <div className="flex items-center justify-between">
          {PIPELINE_STAGES.map((stage, i) => {
            const done   = effectiveReached > stage.step;
            const active = !isCompleted && effectiveReached === stage.step;
            const locked = !isCompleted && effectiveReached < stage.step;
            return (
              <div key={stage.id} className="flex items-center flex-1 last:flex-none">
                <button
                  onClick={() => done || active ? onNavigate(stage.id, projectId) : undefined}
                  disabled={locked}
                  className={`flex flex-col items-center gap-1 group transition-all ${
                    locked ? 'cursor-not-allowed opacity-40' : 'cursor-pointer'
                  }`}
                >
                  <div className={`w-7 h-7 rounded-full flex items-center justify-center text-[10px] font-bold border-2 transition-all ${
                    done   ? 'bg-green-500/20 border-green-500 text-green-400 group-hover:bg-green-500/30' :
                    active ? 'bg-accent/20 border-accent text-accent-light' :
                    'bg-surface border-border text-muted'
                  }`}>
                    {done ? <CheckCircle2 className="w-3.5 h-3.5" /> : <span>{stage.step + 1}</span>}
                  </div>
                  <span className={`text-[9px] font-medium tracking-wide whitespace-nowrap ${
                    done ? 'text-green-400' : active ? 'text-accent-light' : 'text-muted'
                  }`}>{stage.label}</span>
                </button>
                {i < PIPELINE_STAGES.length - 1 && (
                  <div className={`flex-1 h-px mx-1.5 mb-3.5 transition-colors ${
                    done ? 'bg-green-500/50' : active ? 'bg-accent/30' : 'bg-border'
                  }`} />
                )}
              </div>
            );
          })}
        </div>
      </motion.div>

      {/* ── Tab Bar ── */}
      <div className="flex gap-0 border-b border-border">
        {([['overview', LayoutDashboard, 'Overview'], ['settings', Settings, 'Settings']] as const).map(([id, Icon, label]) => (
          <button key={id} onClick={() => setActiveTab(id)}
            className={`flex items-center gap-1.5 px-5 py-2.5 text-xs font-medium border-b-2 transition-colors ${
              activeTab === id ? 'border-accent text-accent-light' : 'border-transparent text-muted hover:text-foreground'
            }`}>
            <Icon className="w-3.5 h-3.5" />{label}
          </button>
        ))}
      </div>

      {activeTab === 'overview' ? (
        <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.1 }} className="space-y-5">

          {/* ── Key info cards ── */}
          <div className="grid grid-cols-4 gap-3">
            {[
              { icon: FileCode2, label: 'Source',      value: `${langLabel(project.sourceLanguage)}${cfg.sourceVersion ? ` ${cfg.sourceVersion}` : ''}`, color: 'text-orange-400' },
              { icon: Code2,     label: 'Target',      value: `${langLabel(project.targetLanguage)}${cfg.targetVersion ? ` ${cfg.targetVersion}` : ''}`, color: 'text-sky-400' },
              { icon: Database,  label: 'Repository',  value: project.repoUrl ? project.repoUrl.replace(/^https?:\/\/[^/]+\//, '') : '—', color: 'text-purple-400', mono: true },
              { icon: Building2, label: 'Domain',      value: (project.tags ?? [])[0] ?? '—', color: 'text-amber-400' },
            ].map((c) => (
              <motion.div key={c.label} initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }}
                className="glass rounded-xl p-4">
                <div className="flex items-center gap-2 mb-2">
                  <c.icon className={`w-4 h-4 ${c.color}`} />
                  <span className="text-[10px] text-muted uppercase tracking-wider font-medium">{c.label}</span>
                </div>
                <p className={`text-sm font-semibold text-foreground truncate ${c.mono ? 'font-mono' : ''}`}>{c.value}</p>
              </motion.div>
            ))}
          </div>

          {/* ── Token counter ── */}
          {(() => {
            const stored = (project as any).tokensUsed ?? 0;
            const estimated = stored > 0 ? stored : Math.round(Math.max((project.totalLines ?? 0) * 6, 0));
            return estimated > 0 ? (
              <motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.12 }}
                className="glass rounded-xl p-4 flex items-center gap-6">
                <div className="flex items-center gap-2 shrink-0">
                  <Cpu className="w-4 h-4 text-accent-light" />
                  <span className="text-xs font-semibold text-foreground">Token Usage</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <span className="text-lg font-bold text-foreground tabular-nums">{estimated.toLocaleString()}</span>
                  <span className="text-[11px] text-muted">tokens {stored > 0 ? 'consumed' : 'estimated'}</span>
                </div>
                {stored === 0 && <span className="ml-auto text-[10px] text-muted/60 italic">estimated from {(project.totalLines ?? 0).toLocaleString()} lines</span>}
              </motion.div>
            ) : null;
          })()}

          {/* ── Main content ── */}
          <div className="grid grid-cols-5 gap-4">

            {/* Activity feed */}
            <motion.div initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.15 }}
              className="col-span-3 glass rounded-xl p-5">
              <h3 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
                <Activity className="w-4 h-4 text-accent-light" /> Activity
              </h3>
              <div className="space-y-4 max-h-[340px] overflow-y-auto pr-1 scrollbar-thin">
                {project.activity?.length > 0 ? project.activity.map((a: any, idx: number) => (
                  <div key={a.id ?? idx} className="flex gap-3 relative">
                    {idx < project.activity.length - 1 && (
                      <div className="absolute left-[5px] top-5 bottom-0 w-px bg-border" />
                    )}
                    <div className="w-2.5 h-2.5 rounded-full bg-accent mt-1 flex-shrink-0 relative z-10" />
                    <div className="min-w-0 pb-1">
                      <p className="text-xs text-foreground leading-snug">{a.action}</p>
                      {a.detail && <p className="text-[10px] text-muted mt-0.5">{a.detail}</p>}
                      <p className="text-[10px] text-muted mt-0.5">
                        {a.user} · {new Date(a.timestamp).toLocaleDateString('it-IT', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}
                      </p>
                    </div>
                  </div>
                )) : (
                  <p className="text-xs text-muted italic">No activity yet.</p>
                )}
              </div>
            </motion.div>

            {/* Right column: Team + Config highlights */}
            <div className="col-span-2 space-y-4">

              {/* Team */}
              <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.2 }}
                className="glass rounded-xl p-5">
                <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                  <Users className="w-4 h-4 text-accent-light" /> Team
                </h3>
                {project.team?.length > 0 ? (
                  <div className="space-y-2">
                    {project.team.map((m: any) => (
                      <div key={m.name} className="flex items-center gap-2.5">
                        <div className="w-7 h-7 rounded-full gradient-accent flex items-center justify-center text-[10px] font-bold text-white shrink-0">
                          {(m.avatar || m.name?.slice(0, 2) || '??').toUpperCase()}
                        </div>
                        <div className="min-w-0">
                          <p className="text-xs font-medium text-foreground truncate">{m.name}</p>
                          <p className="text-[10px] text-muted">{m.role}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-xs text-muted italic">No team members.</p>
                )}
              </motion.div>

              {/* Config highlights */}
              {configHighlights.length > 0 && (
                <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.25 }}
                  className="glass rounded-xl p-5">
                  <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                    <BarChart3 className="w-4 h-4 text-accent-light" /> Configuration
                    <button onClick={() => setActiveTab('settings')}
                      className="ml-auto text-[10px] text-accent-light hover:underline cursor-pointer flex items-center gap-0.5">
                      Edit <ArrowRight className="w-3 h-3" />
                    </button>
                  </h3>
                  <div className="space-y-2">
                    {configHighlights.map((h) => (
                      <div key={h.label} className="flex items-center justify-between">
                        <span className="flex items-center gap-1.5 text-[10px] text-muted">
                          <h.icon className="w-3.5 h-3.5" /> {h.label}
                        </span>
                        <span className="text-[11px] font-medium text-foreground capitalize">{h.value}</span>
                      </div>
                    ))}
                  </div>
                </motion.div>
              )}

              {/* Quick actions */}
              <motion.div initial={{ opacity: 0, x: 10 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.3 }}
                className="glass rounded-xl p-5">
                <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                  <Zap className="w-4 h-4 text-accent-light" /> Quick Actions
                </h3>
                <div className="space-y-2">
                  {([
                    { label: 'Repository',  section: 'repository',    icon: GitBranch, step: 1 },
                    { label: 'Analysis',    section: 'pre-analysis',  icon: TrendingUp, step: 2 },
                    { label: 'Migration',   section: 'migration-flow', icon: Zap, step: 3 },
                    { label: 'Code View',   section: 'comparison',    icon: FileCode2, step: 4 },
                    { label: 'Security',    section: 'security',      icon: Cpu, step: 6 },
                    { label: 'Artifacts',   section: 'artifacts',     icon: Cpu, step: 7 },
                    { label: 'Export',      section: 'export',        icon: CheckCircle2, step: 8 },
                  ] as const).map((a) => {
                    const reachable = effectiveReached >= a.step;
                    return (
                      <button key={a.label} onClick={() => reachable ? onNavigate(a.section, projectId) : undefined}
                        disabled={!reachable}
                        className={`w-full flex items-center justify-between px-3 py-2 rounded-lg text-xs transition-all ${
                          reachable
                            ? 'bg-surface hover:bg-accent/10 text-foreground hover:text-accent-light cursor-pointer'
                            : 'bg-surface/40 text-muted cursor-not-allowed opacity-50'
                        }`}>
                        <span className="flex items-center gap-2">
                          <a.icon className="w-3.5 h-3.5" />{a.label}
                        </span>
                        <ChevronRight className="w-3.5 h-3.5" />
                      </button>
                    );
                  })}
                </div>
              </motion.div>

            </div>
          </div>
        </motion.div>

      ) : activeTab === 'settings' ? (
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-5">
          {/* Sticky save bar */}
          <div className="flex items-center justify-between sticky top-0 z-10 bg-background/80 backdrop-blur-sm py-2 -mx-1 px-1">
            <p className="text-xs text-muted">Edit the configuration saved during project setup. Changes apply to the next conversion run.</p>
            <button onClick={saveSettings} disabled={saving}
              className="flex items-center gap-1.5 px-4 py-2 rounded-lg gradient-accent text-white text-xs font-semibold hover:opacity-90 transition-opacity disabled:opacity-60 cursor-pointer">
              <Save className="w-3.5 h-3.5" />
              {saving ? 'Saving…' : saved ? 'Saved ✓' : 'Save Changes'}
            </button>
          </div>

          {/* ── Conversion Info ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Conversion Info</h4>
            <div className="grid grid-cols-3 gap-3">
              {([['projectOwner','Conversion Owner'],['businessUnit','Business Unit'],['projectCode','Conversion Code'],
                ['legacySystem','Legacy System'],['targetSystem','Target System'],['estimatedLOC','Estimated LOC'],
                ['technicalContact','Technical Contact'],['businessContact','Business Contact']] as [string,string][]).map(([k,label]) => (
                <div key={k}>
                  <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">{label}</label>
                  <input value={cfg[k] ?? ''} onChange={e => cfgSet(k, e.target.value)}
                    className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
                </div>
              ))}
              <div className="col-span-3">
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Stakeholders</label>
                <input value={cfg.stakeholders ?? ''} onChange={e => cfgSet('stakeholders', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Priority</label>
                <select value={cfg.selectedPriority ?? 'medium'} onChange={e => cfgSet('selectedPriority', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30">
                  {['low','medium','high','critical'].map(v => <option key={v} value={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Risk Level</label>
                <select value={cfg.riskLevel ?? 'medium'} onChange={e => cfgSet('riskLevel', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30">
                  {['low','medium','high'].map(v => <option key={v} value={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Deadline</label>
                <input type="date" value={cfg.deadline ?? ''} onChange={e => cfgSet('deadline', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
              </div>
            </div>
          </div>

          {/* ── Repository ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Repository</h4>
            <div className="grid grid-cols-3 gap-3">
              {([['branch','Branch'],['branchStrategy','Branch Strategy'],['encoding','Source Encoding'],
                ['authMethod','Auth Method'],['includePatterns','Include Patterns'],['excludePatterns','Exclude Patterns']] as [string,string][]).map(([k,label]) => (
                <div key={k}>
                  <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">{label}</label>
                  <input value={cfg[k] ?? ''} onChange={e => cfgSet(k, e.target.value)}
                    className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground font-mono outline-none border border-transparent focus:border-accent/30" />
                </div>
              ))}
            </div>
          </div>

          {/* ── Language ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Language Versions</h4>
            <div className="grid grid-cols-3 gap-3">
              {([['sourceVersion','Source Version'],['sourceDialect','Source Dialect'],
                ['targetVersion','Target Version'],['targetBuild','Target Framework']] as [string,string][]).map(([k,label]) => (
                <div key={k}>
                  <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">{label}</label>
                  <input value={cfg[k] ?? ''} onChange={e => cfgSet(k, e.target.value)}
                    className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
                </div>
              ))}
            </div>
          </div>

          {/* ── Target Config ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Target Configuration</h4>
            <div className="grid grid-cols-3 gap-3">
              {([['namingConvention','Naming Convention'],['intent','Translation Intent'],
                ['architecturePattern','Architecture Pattern'],['packageManager','Package Manager'],
                ['testingFramework','Testing Framework'],['apiFramework','API Framework']] as [string,string][]).map(([k,label]) => (
                <div key={k}>
                  <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">{label}</label>
                  <input value={cfg[k] ?? ''} onChange={e => cfgSet(k, e.target.value)}
                    className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
                </div>
              ))}
            </div>
            <div className="grid grid-cols-4 gap-2 pt-1">
              {([['addTests','Tests'],['addDocs','Docs'],['addLinter','Linter'],['addFormatter','Formatter'],
                ['addTypeScript','TypeScript'],['addDocker','Docker'],['addKubernetes','Kubernetes'],['addCI','CI/CD']] as [string,string][]).map(([k,label]) => (
                <label key={k} className="flex items-center gap-2 cursor-pointer select-none">
                  <div onClick={() => cfgSet(k, !cfg[k])}
                    className={`w-8 h-4 rounded-full flex items-center transition-colors cursor-pointer ${cfg[k] ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                    <div className="w-3 h-3 rounded-full bg-white mx-0.5 shadow-sm" />
                  </div>
                  <span className="text-[10px] text-foreground">{label}</span>
                </label>
              ))}
            </div>
          </div>

          {/* ── Translation ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Translation Settings</h4>
            <div className="grid grid-cols-3 gap-3">
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Translation Intent</label>
                <select value={cfg.intent ?? ''} onChange={e => cfgSet('intent', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30">
                  {['','compat-strict','parity','modernize'].map(v => <option key={v} value={v}>{v || 'auto'}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Error Handling</label>
                <select value={cfg.errorHandling ?? 'preserve'} onChange={e => cfgSet('errorHandling', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30">
                  {['preserve','exceptions','result-type','error-codes'].map(v => <option key={v} value={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Quality gate</label>
                <select value={cfg.qualityLevel ?? 0} onChange={e => cfgSet('qualityLevel', Number(e.target.value))}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30">
                  {([[0,'Off'],[1,'Compile (Q1)'],[2,'Idiomatic (Q2)'],[3,'Production (Q3)']] as [number,string][]).map(([v,l]) => <option key={v} value={v}>{l}</option>)}
                </select>
              </div>
              <div className="col-span-2">
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Custom Rules</label>
                <input value={cfg.customRules ?? ''} onChange={e => cfgSet('customRules', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground font-mono outline-none border border-transparent focus:border-accent/30" />
              </div>
            </div>
            <div className="grid grid-cols-4 gap-2 pt-1">
              {([['preserveComments','Comments'],['preserveApiSignatures','API Signatures']] as [string,string][]).map(([k,label]) => (
                <label key={k} className="flex items-center gap-2 cursor-pointer select-none">
                  <div onClick={() => cfgSet(k, !cfg[k])}
                    className={`w-8 h-4 rounded-full flex items-center transition-colors cursor-pointer ${cfg[k] ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                    <div className="w-3 h-3 rounded-full bg-white mx-0.5 shadow-sm" />
                  </div>
                  <span className="text-[10px] text-foreground">{label}</span>
                </label>
              ))}
            </div>
          </div>

          {/* ── Database ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <div className="flex items-center justify-between">
              <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Database Configuration</h4>
              <div onClick={() => cfgSet('enableDatabaseConfig', !cfg.enableDatabaseConfig)}
                className={`w-9 h-5 rounded-full flex items-center transition-colors cursor-pointer ${cfg.enableDatabaseConfig ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
              </div>
            </div>
            {cfg.enableDatabaseConfig && (
              <div className="space-y-3">
                <div className="grid grid-cols-3 gap-3">
                  {([['sourceDatabase','Source DB'],['sourceDbVersion','Source Version'],['schemaFileName','Schema File'],
                    ['selectedDatabase','Target DB'],['dbVersion','Target Version'],['dbInstanceSize','Instance Size'],
                    ['dbStorage','Storage (GB)'],['migrationStrategy','Migration Strategy']] as [string,string][]).map(([k,label]) => (
                    <div key={k}>
                      <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">{label}</label>
                      <input value={cfg[k] ?? ''} onChange={e => cfgSet(k, e.target.value)}
                        className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
                    </div>
                  ))}
                </div>
                <div className="grid grid-cols-4 gap-2">
                  {([['enableReadReplica','Read Replica'],['enableBackup','Backup'],['enableEncryption','Encryption'],
                    ['enableConnectionPool','Connection Pool'],['preserveData','Preserve Data'],['preserveIndexes','Preserve Indexes']] as [string,string][]).map(([k,label]) => (
                    <label key={k} className="flex items-center gap-2 cursor-pointer select-none">
                      <div onClick={() => cfgSet(k, !cfg[k])}
                        className={`w-8 h-4 rounded-full flex items-center transition-colors cursor-pointer ${cfg[k] ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                        <div className="w-3 h-3 rounded-full bg-white mx-0.5 shadow-sm" />
                      </div>
                      <span className="text-[10px] text-foreground">{label}</span>
                    </label>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* ── API Layer ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <div className="flex items-center justify-between">
              <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">API Layer</h4>
              <div onClick={() => cfgSet('enableApiGateway', !cfg.enableApiGateway)}
                className={`w-9 h-5 rounded-full flex items-center transition-colors cursor-pointer ${cfg.enableApiGateway ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
              </div>
            </div>
            {cfg.enableApiGateway && (
              <div className="space-y-3">
                <div className="grid grid-cols-3 gap-3">
                  {([['apiGatewayType','Protocol'],['apiGatewayAuth','Authentication'],['apiFramework','API Framework']] as [string,string][]).map(([k,label]) => (
                    <div key={k}>
                      <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">{label}</label>
                      <input value={cfg[k] ?? ''} onChange={e => cfgSet(k, e.target.value)}
                        className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
                    </div>
                  ))}
                </div>
                <div className="flex gap-4">
                  {([['enableGraphQL','GraphQL Schema'],['enableOpenAPISpec','OpenAPI Spec'],['enableServiceMesh','Service Mesh']] as [string,string][]).map(([k,label]) => (
                    <label key={k} className="flex items-center gap-2 cursor-pointer select-none">
                      <div onClick={() => cfgSet(k, !cfg[k])}
                        className={`w-8 h-4 rounded-full flex items-center transition-colors cursor-pointer ${cfg[k] ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                        <div className="w-3 h-3 rounded-full bg-white mx-0.5 shadow-sm" />
                      </div>
                      <span className="text-[10px] text-foreground">{label}</span>
                    </label>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* ── Monitoring ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Monitoring & Observability</h4>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Alert Threshold (%)</label>
                <input type="number" min={0} max={100} value={cfg.alertThreshold ?? 90} onChange={e => cfgSet('alertThreshold', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
              </div>
            </div>
            <div className="grid grid-cols-4 gap-2">
              {([['enablePrometheus','Prometheus'],['enableGrafana','Grafana'],['enableJaeger','Jaeger Tracing'],['enableELK','ELK Logging']] as [string,string][]).map(([k,label]) => (
                <label key={k} className="flex items-center gap-2 cursor-pointer select-none">
                  <div onClick={() => cfgSet(k, !cfg[k])}
                    className={`w-8 h-4 rounded-full flex items-center transition-colors cursor-pointer ${cfg[k] ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                    <div className="w-3 h-3 rounded-full bg-white mx-0.5 shadow-sm" />
                  </div>
                  <span className="text-[10px] text-foreground">{label}</span>
                </label>
              ))}
            </div>
          </div>

          {/* ── Backup ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Backup & Recovery</h4>
            <div className="grid grid-cols-3 gap-3">
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Frequency</label>
                <select value={cfg.backupFrequency ?? 'daily'} onChange={e => cfgSet('backupFrequency', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30">
                  {['hourly','daily','weekly'].map(v => <option key={v} value={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Retention (days)</label>
                <input type="number" min={1} value={cfg.backupRetention ?? 30} onChange={e => cfgSet('backupRetention', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">DR Region</label>
                <input value={cfg.drRegion ?? ''} onChange={e => cfgSet('drRegion', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground font-mono outline-none border border-transparent focus:border-accent/30" />
              </div>
            </div>
            <label className="flex items-center gap-2 cursor-pointer select-none">
              <div onClick={() => cfgSet('enableDisasterRecovery', !cfg.enableDisasterRecovery)}
                className={`w-8 h-4 rounded-full flex items-center transition-colors cursor-pointer ${cfg.enableDisasterRecovery ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                <div className="w-3 h-3 rounded-full bg-white mx-0.5 shadow-sm" />
              </div>
              <span className="text-[10px] text-foreground">Disaster Recovery</span>
            </label>
          </div>

          {/* ── Deployment ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <div className="flex items-center justify-between">
              <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Deployment Configuration</h4>
              <div onClick={() => cfgSet('enableDeploymentConfig', !cfg.enableDeploymentConfig)}
                className={`w-9 h-5 rounded-full flex items-center transition-colors cursor-pointer ${cfg.enableDeploymentConfig ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                <div className="w-3.5 h-3.5 rounded-full bg-white mx-0.5 shadow-sm" />
              </div>
            </div>
            {cfg.enableDeploymentConfig && (
              <div className="space-y-3">
                <div className="grid grid-cols-3 gap-3">
                  {([['selectedCI','CI/CD Platform'],['infrastructure','Deployment Target'],['deployEnvironment','First Environment'],
                    ['buildTool','Build Tool'],['cacheStrategy','Cache Strategy']] as [string,string][]).map(([k,label]) => (
                    <div key={k}>
                      <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">{label}</label>
                      <input value={cfg[k] ?? ''} onChange={e => cfgSet(k, e.target.value)}
                        className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
                    </div>
                  ))}
                </div>
                <div className="grid grid-cols-4 gap-2">
                  {([['enableAutoDeploy','Auto Deploy'],['enableRollback','Rollback'],['enableHealthChecks','Health Checks'],
                    ['enableBuildTests','Tests in CI'],['enableLinting','Linting'],['enableMinification','Minification']] as [string,string][]).map(([k,label]) => (
                    <label key={k} className="flex items-center gap-2 cursor-pointer select-none">
                      <div onClick={() => cfgSet(k, !cfg[k])}
                        className={`w-8 h-4 rounded-full flex items-center transition-colors cursor-pointer ${cfg[k] ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                        <div className="w-3 h-3 rounded-full bg-white mx-0.5 shadow-sm" />
                      </div>
                      <span className="text-[10px] text-foreground">{label}</span>
                    </label>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* ── Security & Compliance ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Compliance & Security</h4>
            <div className="grid grid-cols-3 gap-2">
              {(['gdpr','sox','pci','hipaa','iso27001','none'] as string[]).map(s => {
                const selected: string[] = Array.isArray(cfg.selectedCompliance) ? cfg.selectedCompliance : [];
                const isNoneActive = selected.includes('none');
                const isSelected = selected.includes(s);
                const isDisabled = isNoneActive && s !== 'none';
                return (
                  <button key={s} disabled={isDisabled} onClick={() => {
                    if (s === 'none') { cfgSet('selectedCompliance', isNoneActive ? [] : ['none']); return; }
                    const without = selected.filter((x: string) => x !== 'none');
                    cfgSet('selectedCompliance', without.includes(s) ? without.filter((x: string) => x !== s) : [...without, s]);
                  }}
                  className={`px-3 py-2 rounded-md border text-[11px] font-medium transition-all ${
                    isDisabled ? 'opacity-35 border-border bg-surface cursor-not-allowed' :
                    isSelected ? 'border-accent/50 bg-accent/10 text-foreground cursor-pointer' :
                    'border-border bg-surface text-foreground hover:border-accent/30 cursor-pointer'
                  }`}>{s.toUpperCase()}</button>
                );
              })}
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Encryption Type</label>
                <select value={cfg.encryptionType ?? 'aes256'} onChange={e => cfgSet('encryptionType', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30">
                  {['aes256','aes128','rsa'].map(v => <option key={v} value={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Secrets Provider</label>
                <select value={cfg.secretsProvider ?? 'aws'} onChange={e => cfgSet('secretsProvider', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30">
                  {['aws','azure','vault','gcp'].map(v => <option key={v} value={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">IAM Policy</label>
                <select value={cfg.iamPolicy ?? 'least-privilege'} onChange={e => cfgSet('iamPolicy', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30">
                  {['least-privilege','role-based','attribute-based'].map(v => <option key={v} value={v}>{v}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[10px] text-muted uppercase tracking-wider block mb-1">Data Retention (days)</label>
                <input type="number" min={1} value={cfg.dataRetention ?? 90} onChange={e => cfgSet('dataRetention', e.target.value)}
                  className="w-full bg-surface rounded-md px-3 py-2 text-xs text-foreground outline-none border border-transparent focus:border-accent/30" />
              </div>
            </div>
            <div className="grid grid-cols-4 gap-2">
              {([['enableSecurityScan','Security Scan'],['enableVulnerabilityScan','Vuln. Scan'],['enableDependencyScan','Dep. Scan'],
                ['enableSAST','SAST'],['enableDAST','DAST'],['enableContainerScan','Container Scan'],
                ['enableSecretsManager','Secrets Mgr'],['enableIAM','IAM']] as [string,string][]).map(([k,label]) => (
                <label key={k} className="flex items-center gap-2 cursor-pointer select-none">
                  <div onClick={() => cfgSet(k, !cfg[k])}
                    className={`w-8 h-4 rounded-full flex items-center transition-colors cursor-pointer ${cfg[k] ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                    <div className="w-3 h-3 rounded-full bg-white mx-0.5 shadow-sm" />
                  </div>
                  <span className="text-[10px] text-foreground">{label}</span>
                </label>
              ))}
            </div>
          </div>

          {/* ── Notifications ── */}
          <div className="glass-light rounded-lg p-4 space-y-3">
            <h4 className="text-xs font-semibold text-foreground uppercase tracking-wider">Notifications</h4>
            <div className="grid grid-cols-3 gap-2">
              {([['notifyOnComplete','On Completion'],['notifyOnWarning','On Warning'],['notifyOnFailure','On Failure']] as [string,string][]).map(([k,label]) => (
                <label key={k} className="flex items-center gap-2 cursor-pointer select-none">
                  <div onClick={() => cfgSet(k, !cfg[k])}
                    className={`w-8 h-4 rounded-full flex items-center transition-colors cursor-pointer ${cfg[k] ? 'bg-accent justify-end' : 'bg-border justify-start'}`}>
                    <div className="w-3 h-3 rounded-full bg-white mx-0.5 shadow-sm" />
                  </div>
                  <span className="text-[10px] text-foreground">{label}</span>
                </label>
              ))}
            </div>
          </div>

          <div className="flex justify-end pb-4">
            <button onClick={saveSettings} disabled={saving}
              className="flex items-center gap-1.5 px-6 py-2.5 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity disabled:opacity-60 cursor-pointer glow-accent">
              <Save className="w-4 h-4" />
              {saving ? 'Saving…' : saved ? 'Saved ✓' : 'Save Changes'}
            </button>
          </div>
        </motion.div>
      ) : null}
    </div>
  );
}
