import { useEffect, useState } from 'react';
import { Outlet, NavLink, useLocation, useNavigate } from 'react-router-dom';
import {
  LayoutDashboard, Plus, Library, PenTool, Box, ShieldCheck, Activity, Settings,
  LogOut, Wand2, Image as ImageIcon, History, Menu, PanelLeftClose, PanelLeftOpen, Sparkles
} from 'lucide-react';
import { base44 } from '@/api/base44Client';
import WorkflowStrip from '@/components/app/WorkflowStrip';
import StatusBar from '@/components/app/StatusBar';
import ExperienceModeProvider, { useExperienceMode } from '@/lib/ExperienceMode';
import Onboarding from '@/components/onboarding/Onboarding';
import Help from '@/components/app/Help';

const navGroups = [
  { label: 'Design', items: [['/', LayoutDashboard, 'Dashboard'], ['/create-design', Plus, 'Create Design'], ['/design-canvas', Sparkles, 'Design Canvas'], ['/designs', LayoutDashboard, 'Universal Designs'], ['/cover-variants', History, 'Cover Variants']] },
  { label: 'Covers', items: [['/covers', Library, 'Covers']] },
  { label: 'Workspace', items: [['/studio', Box, '3D Studio'], ['/image-apply', ImageIcon, 'Image Processing'], ['/sketch-3d', PenTool, 'Sketch to 3D']] },
  { label: 'PromptForge', items: [['/promptforge', Wand2, 'PromptForge']] },
  { label: 'Validation', items: [['/validation', ShieldCheck, 'Validation']] },
  { label: 'Processing', items: [['/jobs', Activity, 'Jobs']] },
  { label: 'Archive', items: [['/history', History, 'Project History']] },
  { label: 'Systems', items: [['/settings', Settings, 'Systems']] },
];

const guidedNav = [
  { label: 'Design', items: [['/', LayoutDashboard, 'Home'], ['/create-design', Plus, 'Create Design'], ['/design-canvas', Sparkles, 'Design Canvas'], ['/designs', LayoutDashboard, 'Universal Designs'], ['/cover-variants', History, 'Cover Variants']] },
  { label: 'Covers', items: [['/covers', Library, 'Covers']] },
  { label: 'Help & Account', items: [['/settings', Settings, 'Settings']] },
];

function ShireMark({ size = 32 }) {
  return (
    <span className="relative grid place-items-center rounded-lg border border-cyan-400/40 bg-[#0a0f14]" style={{ width: size, height: size }}>
      <svg viewBox="0 0 24 24" className="text-cyan-300" fill="none" stroke="currentColor" strokeWidth="1.6" style={{ width: size * 0.55, height: size * 0.55 }}>
        <path d="M12 2 4 6.5v11L12 22l8-4.5v-11L12 2Z" /><path d="M12 7v10M7.5 9.5l9 5M16.5 9.5l-9 5" opacity=".55" />
      </svg>
    </span>
  );
}

function Dot({ tone }) {
  const map = { ok: 'bg-emerald-400 shadow-[0_0_8px_rgba(16,185,129,0.6)]', warn: 'bg-amber-400', bad: 'bg-red-500', sim: 'bg-violet-400', idle: 'bg-slate-600' };
  return <span className={`h-1.5 w-1.5 rounded-full ${map[tone] || map.idle}`} />;
}

function StatusPill({ dot, label, value, valueClass }) {
  return (
    <span className="hidden items-center gap-1.5 rounded-md border border-white/[0.07] bg-white/[0.02] px-2 py-1 text-[10px] text-slate-400 md:inline-flex">
      <Dot tone={dot} /><span>{label}</span><b className={valueClass || 'text-slate-200'}>{value}</b>
    </span>
  );
}

export default function AppShell() {
  const location = useLocation();
  const navigate = useNavigate();
  const projectId = new URLSearchParams(location.search).get('project');
  const [collapsed, setCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [settings, setSettings] = useState(null);
  const [project, setProject] = useState(null);
  const [cover, setCover] = useState(null);
  const [projects, setProjects] = useState([]);
  const [user, setUser] = useState(null);

  useEffect(() => {
    base44.entities.SystemSettings.list(null, 1).then(x => setSettings(Array.isArray(x) ? x[0] : null)).catch(() => setSettings(null));
    base44.entities.CoverCanvasProject.list('-updated_date', 30).then(x => setProjects(Array.isArray(x) ? x : [])).catch(() => setProjects([]));
    base44.auth.me().then(setUser).catch(() => setUser(null));
  }, []);
  useEffect(() => {
    if (!projectId) { setProject(null); setCover(null); return; }
    let alive = true;
    base44.entities.CoverCanvasProject.get(projectId).then(async p => {
      if (!alive) return;
      setProject(p);
      if (p?.coverModelId) { try { setCover(await base44.entities.CoverModel.get(p.coverModelId)); } catch { setCover(null); } }
    }).catch(() => { setProject(null); setCover(null); });
    return () => { alive = false; };
  }, [projectId]);
  useEffect(() => { setMobileOpen(false); }, [location]);
  useEffect(() => {
    if (!mobileOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setMobileOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [mobileOpen]);

  const refreshUser = () => base44.auth.me().then(setUser).catch(() => setUser(null));

  useEffect(() => {
    const root = document.documentElement;
    root.classList.toggle('reduced-motion', !!user?.reducedMotion);
    root.classList.toggle('high-contrast', !!user?.highContrast);
  }, [user?.reducedMotion, user?.highContrast]);

  const geoTone = settings?.geometryServiceStatus === 'connected' ? 'ok' : settings?.geometryServiceStatus === 'simulation_only' ? 'sim' : 'idle';
  const geoVal = settings?.geometryServiceStatus === 'connected' ? 'Online' : settings?.geometryServiceStatus === 'simulation_only' ? 'Simulation' : 'Offline';
  const geoCls = geoTone === 'ok' ? 'text-emerald-300' : geoTone === 'sim' ? 'text-violet-300' : 'text-slate-400';
  const vaultTone = settings?.shireVaultStatus === 'connected' && settings?.shireVaultWritable ? 'ok' : 'warn';
  const vaultVal = settings?.shireVaultStatus === 'connected' ? (settings?.shireVaultWritable ? 'Synced' : 'Read-only') : 'Not mounted';
  const vaultCls = vaultTone === 'ok' ? 'text-emerald-300' : 'text-amber-300';

  const railW = collapsed ? 'lg:w-[68px]' : 'lg:w-[232px]';
  const mainL = collapsed ? 'lg:ml-[68px]' : 'lg:ml-[232px]';

  return (
    <ExperienceModeProvider user={user}>
    <div className="min-h-screen text-slate-100">
      <a href="#main-content" className="sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-2 focus:z-[60] focus:rounded focus:bg-cyan-400 focus:px-3 focus:py-1 focus:text-sm focus:font-semibold focus:text-slate-950">Skip to content</a>
      {/* Command bar */}
      <header className="fixed inset-x-0 top-0 z-40 h-12 border-b border-white/[0.06] bg-[#0a0d12]/90 backdrop-blur-xl">
        <div className="flex h-12 items-center gap-3 px-3 lg:px-4">
          <button onClick={() => setMobileOpen(true)} className="icon-button lg:hidden" aria-label="Open navigation"><Menu size={17} /></button>
          <ShireMark size={30} />
          <div className="leading-tight">
            <p className="text-[9px] font-semibold uppercase tracking-[0.3em] text-cyan-400/80">SHiRE</p>
            <p className="font-heading text-[13px] font-semibold text-white">LimbForge <span className="text-slate-600">·</span> CoverCanvas</p>
          </div>
          <div className="mx-2 hidden h-6 w-px bg-white/10 sm:block" />
          {/* Project selector */}
          <select
            aria-label="Active project"
            value={projectId || ''}
            onChange={e => navigate(e.target.value ? `/studio?project=${e.target.value}` : '/')}
            className="hidden max-w-[200px] rounded-md border border-white/10 bg-[#0a0e13] px-2 py-1 text-xs text-slate-200 focus:border-cyan-400 focus:outline-none md:block"
          >
            <option value="">— no active project —</option>
            {(Array.isArray(projects) ? projects : []).map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          {cover && <span className="hidden items-center gap-1.5 rounded-md border border-white/10 bg-white/[0.03] px-2 py-1 text-[11px] text-slate-300 lg:inline-flex"><Box size={12} className="text-cyan-300" />{cover.name}</span>}
          <div className="ml-auto flex items-center gap-2">
            <StatusPill dot={geoTone} label="Geometry Engine" value={geoVal} valueClass={geoCls} />
            <StatusPill dot={vaultTone} label="SHiREVault" value={vaultVal} valueClass={vaultCls} />
            <div className="mx-1 hidden h-6 w-px bg-white/10 sm:block" />
            <div className="hidden items-center gap-2 sm:flex">
              <span className="grid h-8 w-8 place-items-center rounded-full border border-white/10 bg-white/[0.03] text-[11px] font-semibold text-cyan-200">{(user?.full_name || 'OP').slice(0, 1).toUpperCase()}</span>
              <span className="hidden text-[11px] leading-tight md:block">
                <b className="block text-slate-200">{user?.full_name || 'SHiRE Operator'}</b>
                <span className="text-slate-500">{user?.role === 'admin' ? 'Lead Designer' : 'Operator'}</span>
              </span>
            </div>
            <Help />
            <button onClick={() => base44.auth.logout('/login')} className="icon-button" title="Sign out" aria-label="Sign out"><LogOut size={16} /></button>
          </div>
        </div>
      </header>

      {/* Workflow strip */}
      <div className={`fixed top-12 z-30 h-10 border-b border-white/[0.06] bg-[#0b0f14]/90 backdrop-blur-md ${mainL} right-0`}>
        <WorkflowStrip project={project} />
      </div>

      {/* Desktop nav rail */}
      <aside className={`fixed bottom-8 top-12 left-0 z-30 hidden border-r border-white/[0.06] bg-[#070a0e] transition-all duration-300 lg:block ${railW}`}>
        <NavRail collapsed={collapsed} onToggle={() => setCollapsed(c => !c)} />
      </aside>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setMobileOpen(false)} />
          <aside className="absolute bottom-8 top-12 left-0 w-[232px] border-r border-white/10 bg-[#070a0e]"><NavRail collapsed={false} onToggle={() => {}} /></aside>
        </div>
      )}

      <main id="main-content" className={`min-w-0 pt-[88px] pb-8 transition-all duration-300 ${mainL}`}>
        <div className="p-4 md:p-5 lg:p-6"><Outlet /></div>
      </main>

      <Onboarding user={user} onComplete={refreshUser} />

      {/* Status bar */}
      <div className={`fixed bottom-0 z-30 h-8 right-0 left-0 ${collapsed ? 'lg:left-[68px]' : 'lg:left-[232px]'}`}>
        <StatusBar project={project} settings={settings} />
      </div>
    </div>
    </ExperienceModeProvider>
  );
}

function NavRail({ collapsed, onToggle }) {
  const { mode } = useExperienceMode();
  const groups = mode === 'guided' ? guidedNav : navGroups;
  return (
    <div className="flex h-full flex-col">
      <nav className="flex-1 space-y-4 overflow-y-auto px-2 py-4">
        {groups.map(group => (
          <div key={group.label}>
            {!collapsed && <p className="mb-1.5 px-2 text-[9px] font-semibold uppercase tracking-[0.22em] text-slate-600">{group.label}</p>}
            <div className="space-y-0.5">
              {group.items.map(([to, Icon, label]) => (
                <NavLink key={to} to={to} end={to === '/'} className={({ isActive }) =>
                  `group relative flex items-center gap-2.5 rounded-md px-2.5 py-2 text-[13px] transition ${isActive ? 'bg-cyan-400/[0.10] text-cyan-100' : 'text-slate-400 hover:bg-white/[0.03] hover:text-white'} ${collapsed ? 'lg:justify-center lg:px-0' : ''}`
                }>
                  {({ isActive }) => (
                    <>
                      {isActive && <span className="absolute left-0 top-1/2 h-5 w-[3px] -translate-y-1/2 rounded-full bg-cyan-400 shadow-[0_0_10px_rgba(0,212,255,0.7)]" />}
                      <Icon size={17} className={isActive ? 'text-cyan-300' : ''} />
                      {!collapsed && <span className="truncate">{label}</span>}
                      {collapsed && <span className="pointer-events-none absolute left-full ml-2 whitespace-nowrap rounded border border-white/10 bg-[#11171c] px-2 py-1 text-[11px] text-slate-200 opacity-0 transition group-hover:opacity-100">{label}</span>}
                    </>
                  )}
                </NavLink>
              ))}
            </div>
          </div>
        ))}
      </nav>
      <div className="border-t border-white/[0.06] p-2.5">
        <div className={`mb-2 flex items-center gap-2 ${collapsed ? 'lg:justify-center' : ''}`}>
          <ShireMark size={26} />
          {!collapsed && (
            <div className="leading-tight">
              <p className="text-[10px] font-semibold uppercase tracking-[0.25em] text-slate-300">SHiRE</p>
              <p className="text-[9px] text-slate-600">Build stronger. Live bolder.</p>
            </div>
          )}
        </div>
        <button onClick={onToggle} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-[11px] text-slate-500 hover:text-white lg:flex">
          {collapsed ? <PanelLeftOpen size={15} /> : <><PanelLeftClose size={15} /><span>Collapse</span></>}
        </button>
      </div>
    </div>
  );
}