"use client";

import { use, useState, useEffect } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import {
  Monitor, Globe, Settings, Smartphone, Mail, BookOpen,
  Lock, CheckCircle2, Loader2, ChevronRight, Pencil,
} from "lucide-react";

// ---------------------------------------------------------------------------
// Surface definitions
// ---------------------------------------------------------------------------

interface Surface {
  id: string;
  name: string;
  description: string;
  icon: React.ElementType;
  themes: Theme[];
}

interface Theme {
  id: string;
  name: string;
  description: string;
  tags: string[];
  url: string;
  preview: React.ReactNode;
}

// Mini UI mockups — each styled to feel like the library
const ShadcnPreview = () => (
  <div className="w-full h-full bg-white border border-zinc-200 rounded-lg p-2.5 flex flex-col gap-2">
    <div className="flex items-center gap-1.5">
      <div className="w-3 h-3 rounded bg-zinc-900" />
      <div className="h-2 w-14 bg-zinc-200 rounded" />
    </div>
    <div className="h-px bg-zinc-100" />
    <div className="space-y-1 flex-1">
      <div className="h-1.5 w-full bg-zinc-100 rounded" />
      <div className="h-1.5 w-2/3 bg-zinc-100 rounded" />
    </div>
    <div className="flex gap-1.5">
      <span className="h-5 px-2 bg-zinc-900 text-white rounded text-[8px] flex items-center font-medium">Save</span>
      <span className="h-5 px-2 border border-zinc-200 rounded text-[8px] flex items-center text-zinc-500">Cancel</span>
    </div>
  </div>
);

const MantiinePreview = () => (
  <div className="w-full h-full bg-white border border-zinc-200 rounded-lg p-2.5 flex flex-col gap-2">
    <div className="flex items-center justify-between">
      <div className="h-2 w-12 bg-zinc-800 rounded" />
      <span className="h-4 px-1.5 bg-blue-600 text-white rounded text-[7px] flex items-center">New</span>
    </div>
    <div className="border border-zinc-200 rounded overflow-hidden">
      <div className="h-4 bg-zinc-50 border-b border-zinc-200 flex items-center px-1.5 gap-1">
        <div className="h-1.5 w-8 bg-zinc-300 rounded" />
        <div className="h-1.5 w-10 bg-zinc-300 rounded ml-auto" />
      </div>
      {[1,2].map(i => (
        <div key={i} className="h-4 border-b border-zinc-100 flex items-center px-1.5 gap-1 last:border-0">
          <div className="h-1.5 w-12 bg-zinc-200 rounded" />
          <div className="h-1.5 w-8 bg-zinc-200 rounded ml-auto" />
        </div>
      ))}
    </div>
    <div className="flex gap-1 mt-auto">
      <span className="h-5 px-2 bg-blue-600 text-white rounded text-[8px] flex items-center">Apply</span>
    </div>
  </div>
);

const HeroUIPreview = () => (
  <div className="w-full h-full bg-white rounded-lg p-2.5 flex flex-col gap-2" style={{ background: 'linear-gradient(135deg, #f8faff 0%, #fff 100%)' }}>
    <div className="flex items-center gap-1.5">
      <div className="w-3 h-3 rounded-full" style={{ background: 'linear-gradient(135deg, #7c3aed, #ec4899)' }} />
      <div className="h-2 w-12 bg-zinc-200 rounded" />
    </div>
    <div className="rounded-lg p-2 flex-1" style={{ background: 'linear-gradient(135deg, rgba(124,58,237,0.05), rgba(236,72,153,0.05))' }}>
      <div className="h-1.5 w-full bg-zinc-200 rounded mb-1" />
      <div className="h-1.5 w-3/4 bg-zinc-200 rounded" />
    </div>
    <span className="h-5 px-2 text-white rounded-full text-[8px] flex items-center justify-center self-start font-medium" style={{ background: 'linear-gradient(135deg, #7c3aed, #ec4899)' }}>
      Get started →
    </span>
  </div>
);

const DaisyPreview = () => (
  <div className="w-full h-full bg-[#1d232a] rounded-lg p-2.5 flex flex-col gap-2">
    <div className="flex items-center gap-1">
      <div className="w-2 h-2 rounded-full bg-[#f59e0b]" />
      <div className="w-2 h-2 rounded-full bg-[#10b981]" />
      <div className="w-2 h-2 rounded-full bg-[#3b82f6]" />
    </div>
    <div className="space-y-1 flex-1">
      <div className="h-1.5 w-full bg-zinc-700 rounded" />
      <div className="h-1.5 w-5/6 bg-zinc-700 rounded" />
    </div>
    <div className="flex gap-1">
      <span className="h-5 px-2 bg-[#f59e0b] text-black rounded-full text-[8px] flex items-center font-bold">Primary</span>
      <span className="h-5 px-2 bg-[#10b981] text-black rounded-full text-[8px] flex items-center font-bold">Success</span>
    </div>
  </div>
);

const AcernityPreview = () => (
  <div className="w-full h-full bg-zinc-950 rounded-lg p-2.5 flex flex-col gap-2">
    <div className="h-2 w-20 rounded" style={{ background: 'linear-gradient(90deg, #a855f7, #3b82f6)' }} />
    <div className="space-y-1 flex-1">
      <div className="h-1.5 w-full bg-zinc-800 rounded" />
      <div className="h-1.5 w-2/3 bg-zinc-800 rounded" />
    </div>
    <div className="h-5 rounded border flex items-center justify-center" style={{ borderColor: 'rgba(168,85,247,0.4)', background: 'rgba(168,85,247,0.05)' }}>
      <span className="text-[8px] font-medium" style={{ background: 'linear-gradient(90deg, #a855f7, #3b82f6)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>Get started</span>
    </div>
  </div>
);

const TailwindPreview = () => (
  <div className="w-full h-full bg-white rounded-lg p-2.5 flex flex-col gap-2 border border-zinc-100">
    <div className="text-[8px] font-mono text-zinc-400">className=&quot;flex…&quot;</div>
    <div className="space-y-1 flex-1">
      <div className="h-5 w-full bg-gradient-to-r from-violet-100 to-blue-100 rounded flex items-center px-2">
        <div className="h-1.5 w-10 bg-violet-300 rounded" />
      </div>
      <div className="h-5 w-full bg-zinc-100 rounded" />
    </div>
    <div className="h-5 bg-zinc-900 rounded flex items-center justify-center">
      <span className="text-white text-[8px] font-medium">Custom →</span>
    </div>
  </div>
);

const TremorPreview = () => (
  <div className="w-full h-full bg-white rounded-lg p-2.5 flex flex-col gap-2 border border-zinc-200">
    <div className="flex items-center justify-between">
      <div className="h-2 w-14 bg-zinc-800 rounded" />
      <div className="h-2 w-6 bg-blue-500 rounded" />
    </div>
    <div className="flex gap-1 flex-1 items-end">
      {[60, 80, 45, 90, 70, 55].map((h, i) => (
        <div key={i} className="flex-1 bg-blue-100 rounded-t" style={{ height: `${h}%` }}>
          <div className="bg-blue-500 rounded-t w-full" style={{ height: '30%' }} />
        </div>
      ))}
    </div>
  </div>
);

const NativewindPreview = () => (
  <div className="w-full h-full flex items-center justify-center">
    <div className="w-16 h-24 bg-zinc-900 rounded-xl border-2 border-zinc-700 flex flex-col overflow-hidden">
      <div className="h-2 bg-zinc-800 flex items-center justify-center">
        <div className="w-4 h-0.5 bg-zinc-600 rounded-full" />
      </div>
      <div className="flex-1 bg-zinc-950 p-1 flex flex-col gap-1">
        <div className="h-2 w-full bg-zinc-800 rounded" />
        <div className="h-6 w-full bg-zinc-800 rounded flex items-center justify-center">
          <div className="h-1 w-6 bg-zinc-600 rounded" />
        </div>
        <div className="h-3 w-full bg-violet-600 rounded flex items-center justify-center">
          <span className="text-white text-[5px]">Button</span>
        </div>
      </div>
    </div>
  </div>
);

const GluestackPreview = () => (
  <div className="w-full h-full flex items-center justify-center">
    <div className="w-16 h-24 bg-white rounded-xl border border-zinc-200 flex flex-col overflow-hidden shadow-sm">
      <div className="h-3 bg-blue-600 flex items-center px-1.5">
        <div className="h-1 w-6 bg-blue-400 rounded" />
      </div>
      <div className="flex-1 p-1 flex flex-col gap-1">
        <div className="h-2 w-full bg-zinc-100 rounded" />
        <div className="h-2 w-4/5 bg-zinc-100 rounded" />
        <div className="mt-auto h-4 w-full bg-blue-600 rounded flex items-center justify-center">
          <span className="text-white text-[5px] font-bold">Submit</span>
        </div>
      </div>
    </div>
  </div>
);

const ReactEmailPreview = () => (
  <div className="w-full h-full bg-zinc-50 rounded-lg p-2.5 flex flex-col gap-1.5 border border-zinc-200">
    <div className="flex items-center gap-1">
      <div className="w-3 h-3 rounded bg-blue-600" />
      <div className="h-1.5 w-16 bg-zinc-300 rounded" />
    </div>
    <div className="h-px bg-zinc-200" />
    <div className="h-1.5 w-2/3 bg-zinc-800 rounded" />
    <div className="space-y-1">
      <div className="h-1.5 w-full bg-zinc-300 rounded" />
      <div className="h-1.5 w-5/6 bg-zinc-300 rounded" />
      <div className="h-1.5 w-4/5 bg-zinc-300 rounded" />
    </div>
    <div className="h-5 bg-blue-600 rounded flex items-center justify-center mt-1">
      <span className="text-white text-[8px] font-medium">Open App →</span>
    </div>
  </div>
);

const NextraPreview = () => (
  <div className="w-full h-full bg-white rounded-lg border border-zinc-200 overflow-hidden flex">
    <div className="w-1/3 bg-zinc-50 border-r border-zinc-200 p-1.5 flex flex-col gap-1">
      {['Getting started', 'Installation', 'API', 'Examples'].map(l => (
        <div key={l} className="h-2 bg-zinc-200 rounded" style={{ width: `${60 + Math.random() * 30}%` }} />
      ))}
    </div>
    <div className="flex-1 p-2 flex flex-col gap-1.5">
      <div className="h-2 w-3/4 bg-zinc-800 rounded" />
      <div className="h-1.5 w-full bg-zinc-200 rounded" />
      <div className="h-1.5 w-5/6 bg-zinc-200 rounded" />
    </div>
  </div>
);

const ALL_SURFACES: Surface[] = [
  {
    id: "web-app",
    name: "Web App",
    description: "The core product your users log into — dashboards, features, settings",
    icon: Monitor,
    themes: [
      { id: "shadcn", name: "shadcn/ui", description: "Copy-paste components on Radix primitives. You own the code, fully customisable.", tags: ["Tailwind", "Radix", "Copy-paste"], url: "https://ui.shadcn.com", preview: <ShadcnPreview /> },
      { id: "mantine", name: "Mantine", description: "100+ components with hooks, forms, charts. Best for data-heavy apps.", tags: ["React", "Charts", "Forms"], url: "https://mantine.dev", preview: <MantiinePreview /> },
      { id: "hero-ui", name: "HeroUI", description: "Beautiful, accessible components with smooth animations and dark mode.", tags: ["Tailwind", "Animations", "Accessible"], url: "https://heroui.com", preview: <HeroUIPreview /> },
      { id: "tremor", name: "Tremor", description: "Dashboard components — charts, KPIs, tables — designed for analytics UIs.", tags: ["Charts", "Dashboard", "Analytics"], url: "https://tremor.so", preview: <TremorPreview /> },
    ],
  },
  {
    id: "marketing",
    name: "Marketing Site",
    description: "Public-facing landing page, blog, pricing — brand expression and conversion",
    icon: Globe,
    themes: [
      { id: "daisy-ui", name: "DaisyUI", description: "Tailwind plugin with 48 built-in themes. Fastest path to a beautiful site.", tags: ["Tailwind", "Themes", "Plugin"], url: "https://daisyui.com", preview: <DaisyPreview /> },
      { id: "hero-ui", name: "HeroUI", description: "Beautiful components with gradients and smooth animations.", tags: ["Tailwind", "Animations", "Modern"], url: "https://heroui.com", preview: <HeroUIPreview /> },
      { id: "aceternity", name: "Aceternity UI", description: "Animated, visually striking components for premium landing pages.", tags: ["Animations", "Dark", "Premium"], url: "https://ui.aceternity.com", preview: <AcernityPreview /> },
      { id: "tailwind-only", name: "Tailwind only", description: "No component library — full creative control with pure Tailwind CSS.", tags: ["Custom", "Flexible", "Minimal"], url: "https://tailwindcss.com", preview: <TailwindPreview /> },
    ],
  },
  {
    id: "admin",
    name: "Admin Panel",
    description: "Internal tool for managing your business — users, support, billing, analytics",
    icon: Settings,
    themes: [
      { id: "mantine", name: "Mantine", description: "The best choice for admin — comprehensive tables, forms, and data components.", tags: ["Tables", "Forms", "Charts"], url: "https://mantine.dev", preview: <MantiinePreview /> },
      { id: "shadcn", name: "shadcn/ui", description: "Clean, neutral components. Great if you want the admin to match the main app.", tags: ["Tailwind", "Consistent", "Clean"], url: "https://ui.shadcn.com", preview: <ShadcnPreview /> },
      { id: "tremor", name: "Tremor", description: "Analytics-first — built for KPI dashboards, charts, and data tables.", tags: ["Analytics", "Charts", "KPIs"], url: "https://tremor.so", preview: <TremorPreview /> },
    ],
  },
  {
    id: "mobile",
    name: "Mobile App",
    description: "iOS and Android companion app — touch-first, native feel",
    icon: Smartphone,
    themes: [
      { id: "nativewind", name: "NativeWind", description: "Use Tailwind CSS in React Native. Consistent style across web and mobile.", tags: ["Tailwind", "React Native", "Expo"], url: "https://nativewind.dev", preview: <NativewindPreview /> },
      { id: "gluestack", name: "Gluestack UI", description: "Universal components for React Native — accessible, well-tested, comprehensive.", tags: ["Universal", "Accessible", "Expo"], url: "https://gluestack.io", preview: <GluestackPreview /> },
    ],
  },
  {
    id: "email",
    name: "Email",
    description: "Transactional and marketing emails — welcome, billing, notifications",
    icon: Mail,
    themes: [
      { id: "react-email", name: "React Email", description: "Build emails with React components. Works with any email provider.", tags: ["React", "Resend", "Cross-client"], url: "https://react.email", preview: <ReactEmailPreview /> },
    ],
  },
  {
    id: "docs",
    name: "Docs / Content",
    description: "Documentation, knowledge base, or blog for your product",
    icon: BookOpen,
    themes: [
      { id: "nextra", name: "Nextra", description: "Next.js-based docs site. Markdown-first, fast, with great search.", tags: ["Next.js", "Markdown", "Search"], url: "https://nextra.site", preview: <NextraPreview /> },
      { id: "shadcn", name: "shadcn/ui + custom", description: "Build a fully custom docs site that matches your product exactly.", tags: ["Custom", "Tailwind", "Flexible"], url: "https://ui.shadcn.com", preview: <ShadcnPreview /> },
    ],
  },
];

// ---------------------------------------------------------------------------
// Theme option card
// ---------------------------------------------------------------------------

function ThemeCard({
  theme,
  selected,
  locked,
  onSelect,
}: {
  theme: Theme;
  selected: boolean;
  locked: boolean;
  onSelect: () => void;
}) {
  return (
    <button
      onClick={onSelect}
      disabled={locked && !selected}
      className={cn(
        "flex flex-col text-left rounded-xl border transition-all overflow-hidden",
        "w-52 shrink-0",
        selected && locked
          ? "border-foreground ring-2 ring-foreground shadow-sm"
          : selected
          ? "border-foreground ring-1 ring-foreground"
          : "border-border hover:border-foreground/40",
        locked && !selected && "opacity-40 cursor-not-allowed"
      )}
    >
      {/* Preview */}
      <div className="h-28 p-2 bg-zinc-50 border-b border-border relative">
        {theme.preview}
        {selected && locked && (
          <div className="absolute top-1.5 right-1.5 w-5 h-5 rounded-full bg-foreground flex items-center justify-center">
            <Lock className="w-2.5 h-2.5 text-background" />
          </div>
        )}
        {selected && !locked && (
          <div className="absolute top-1.5 right-1.5 w-5 h-5 rounded-full bg-foreground flex items-center justify-center">
            <CheckCircle2 className="w-2.5 h-2.5 text-background" />
          </div>
        )}
      </div>

      {/* Info */}
      <div className="p-3 flex flex-col gap-1.5">
        <div className="flex items-center justify-between gap-2">
          <p className="text-xs font-semibold text-foreground">{theme.name}</p>
          <a
            href={theme.url}
            target="_blank"
            rel="noopener noreferrer"
            onClick={e => e.stopPropagation()}
            className="text-[10px] text-muted-foreground hover:text-foreground transition-colors shrink-0"
          >
            Docs ↗
          </a>
        </div>
        <p className="text-[11px] text-muted-foreground leading-relaxed">{theme.description}</p>
        <div className="flex flex-wrap gap-1 mt-0.5">
          {theme.tags.map(t => (
            <Badge key={t} variant="secondary" className="text-[9px] px-1.5 py-0">{t}</Badge>
          ))}
        </div>
      </div>
    </button>
  );
}

// ---------------------------------------------------------------------------
// Surface section
// ---------------------------------------------------------------------------

function SurfaceSection({
  surface,
  selectedThemeId,
  lockedThemeId,
  onSelect,
  onLock,
  onUnlock,
  saving,
}: {
  surface: Surface;
  selectedThemeId: string | null;
  lockedThemeId: string | null;
  onSelect: (themeId: string) => void;
  onLock: () => void;
  onUnlock: () => void;
  saving: boolean;
}) {
  const Icon = surface.icon;
  const lockedTheme = surface.themes.find(t => t.id === lockedThemeId);

  return (
    <div className="space-y-3">
      {/* Surface header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-lg bg-muted flex items-center justify-center">
            <Icon className="h-4 w-4 text-muted-foreground" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <p className="text-sm font-semibold">{surface.name}</p>
              {lockedTheme && (
                <Badge variant="secondary" className="text-[10px] gap-1 px-1.5">
                  <Lock className="w-2.5 h-2.5" />
                  {lockedTheme.name}
                </Badge>
              )}
            </div>
            <p className="text-xs text-muted-foreground">{surface.description}</p>
          </div>
        </div>

        {/* Lock / Unlock controls */}
        <div className="flex items-center gap-2 shrink-0">
          {lockedThemeId ? (
            <Button variant="outline" size="sm" onClick={onUnlock} className="gap-1.5 text-xs">
              <Pencil className="h-3 w-3" />
              Change
            </Button>
          ) : (
            <Button
              size="sm"
              onClick={onLock}
              disabled={!selectedThemeId || saving}
              className="gap-1.5 text-xs"
            >
              {saving ? <Loader2 className="h-3 w-3 animate-spin" /> : <Lock className="h-3 w-3" />}
              Lock in
            </Button>
          )}
        </div>
      </div>

      {/* Theme cards — horizontal scroll */}
      {!lockedThemeId && (
        <div className="flex gap-3 overflow-x-auto pb-2 -mx-1 px-1">
          {surface.themes.map(theme => (
            <ThemeCard
              key={theme.id}
              theme={theme}
              selected={selectedThemeId === theme.id}
              locked={false}
              onSelect={() => onSelect(theme.id)}
            />
          ))}
        </div>
      )}

      {/* Locked state — show only selected */}
      {lockedThemeId && (
        <div className="flex gap-3 overflow-x-auto pb-2 -mx-1 px-1">
          {surface.themes.map(theme => (
            <ThemeCard
              key={theme.id}
              theme={theme}
              selected={theme.id === lockedThemeId}
              locked={true}
              onSelect={() => {}}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Phase 1 — Surface picker
// ---------------------------------------------------------------------------

function SurfacePicker({
  onConfirm,
  saving,
}: {
  onConfirm: (ids: string[]) => void;
  saving: boolean;
}) {
  const [selected, setSelected] = useState<Set<string>>(new Set());

  const toggle = (id: string) => {
    setSelected(prev => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-xl font-bold">Design surfaces</h1>
        <p className="text-sm text-muted-foreground mt-0.5">
          Which surfaces does your product need? Select all that apply — you can always add more later.
        </p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
        {ALL_SURFACES.map(surface => {
          const Icon = surface.icon;
          const isSelected = selected.has(surface.id);
          return (
            <button
              key={surface.id}
              onClick={() => toggle(surface.id)}
              className={cn(
                "flex items-start gap-3 rounded-xl border p-4 text-left transition-all",
                isSelected
                  ? "border-foreground bg-foreground/5 ring-1 ring-foreground"
                  : "border-border hover:border-foreground/40"
              )}
            >
              <div className={cn(
                "w-8 h-8 rounded-lg flex items-center justify-center shrink-0 mt-0.5",
                isSelected ? "bg-foreground text-background" : "bg-muted text-muted-foreground"
              )}>
                <Icon className="h-4 w-4" />
              </div>
              <div>
                <p className="text-sm font-semibold">{surface.name}</p>
                <p className="text-xs text-muted-foreground mt-0.5 leading-relaxed">{surface.description}</p>
              </div>
              {isSelected && (
                <CheckCircle2 className="h-4 w-4 text-foreground ml-auto shrink-0 mt-0.5" />
              )}
            </button>
          );
        })}
      </div>

      <div className="flex items-center gap-3">
        <Button
          onClick={() => onConfirm(Array.from(selected))}
          disabled={selected.size === 0 || saving}
          className="gap-2"
        >
          {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <ChevronRight className="h-4 w-4" />}
          Confirm surfaces ({selected.size})
        </Button>
        {selected.size === 0 && (
          <p className="text-xs text-muted-foreground">Select at least one surface to continue</p>
        )}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Page
// ---------------------------------------------------------------------------

export default function DesignPage({
  params,
}: {
  params: Promise<{ workspace: string; projectId: string }>;
}) {
  const { projectId } = use(params);

  const [surfaces, setSurfaces] = useState<string[]>([]);
  const [surfaceThemes, setSurfaceThemes] = useState<Record<string, string>>({});
  const [selectedThemes, setSelectedThemes] = useState<Record<string, string>>({});
  const [activeSurfaceId, setActiveSurfaceId] = useState<string | null>(null);
  const [savingLock, setSavingLock] = useState<string | null>(null);
  const [savingSurfaces, setSavingSurfaces] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/projects/${projectId}/design-surfaces`)
      .then(r => r.json())
      .then(d => {
        const loaded = (d.surfaces ?? []) as string[];
        setSurfaces(loaded);
        setSurfaceThemes(d.surfaceThemes ?? {});
        setSelectedThemes(d.surfaceThemes ?? {});
        if (loaded.length > 0) setActiveSurfaceId(loaded[0]);
      })
      .catch(() => toast.error("Failed to load design data"))
      .finally(() => setLoading(false));
  }, [projectId]);

  const handleConfirmSurfaces = async (ids: string[]) => {
    setSavingSurfaces(true);
    try {
      const res = await fetch(`/api/projects/${projectId}/design-surfaces`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ surfaces: ids }),
      });
      if (!res.ok) throw new Error();
      setSurfaces(ids);
      setActiveSurfaceId(ids[0] ?? null);
      toast.success("Surfaces saved");
    } catch {
      toast.error("Failed to save surfaces");
    } finally {
      setSavingSurfaces(false);
    }
  };

  const handleLock = async (surfaceId: string) => {
    const themeId = selectedThemes[surfaceId];
    if (!themeId) return;
    setSavingLock(surfaceId);
    try {
      const res = await fetch(`/api/projects/${projectId}/design-surfaces`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ surface: surfaceId, theme: themeId }),
      });
      if (!res.ok) throw new Error();
      setSurfaceThemes(prev => ({ ...prev, [surfaceId]: themeId }));
      const surface = ALL_SURFACES.find(s => s.id === surfaceId);
      const theme = surface?.themes.find(t => t.id === themeId);
      toast.success(`${surface?.name} → ${theme?.name} locked in`);
    } catch {
      toast.error("Failed to lock in theme");
    } finally {
      setSavingLock(null);
    }
  };

  const handleUnlock = (surfaceId: string) => {
    setSurfaceThemes(prev => {
      const next = { ...prev };
      delete next[surfaceId];
      return next;
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <Loader2 className="h-7 w-7 animate-spin text-muted-foreground" />
      </div>
    );
  }

  // Phase 1 — no surfaces set yet
  if (surfaces.length === 0) {
    return (
      <div className="p-6 max-w-4xl mx-auto">
        <SurfacePicker onConfirm={handleConfirmSurfaces} saving={savingSurfaces} />
      </div>
    );
  }

  // Phase 2 — left nav + main content
  const activeSurfaces = ALL_SURFACES.filter(s => surfaces.includes(s.id));
  const currentSurface = activeSurfaces.find(s => s.id === activeSurfaceId) ?? activeSurfaces[0];
  const lockedCount = Object.keys(surfaceThemes).length;

  return (
    <div className="flex h-full">
      {/* Left nav */}
      <div className="w-52 shrink-0 border-r flex flex-col">
        <div className="px-4 py-4 border-b">
          <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Surfaces</p>
        </div>

        <nav className="flex-1 py-2">
          {activeSurfaces.map(surface => {
            const Icon = surface.icon;
            const isActive = surface.id === currentSurface?.id;
            const isLocked = !!surfaceThemes[surface.id];
            return (
              <button
                key={surface.id}
                onClick={() => setActiveSurfaceId(surface.id)}
                className={cn(
                  "flex items-center gap-2.5 w-full px-4 py-2.5 text-left transition-colors relative",
                  isActive
                    ? "bg-muted text-foreground"
                    : "text-muted-foreground hover:text-foreground hover:bg-muted/50"
                )}
              >
                {isActive && (
                  <div className="absolute left-0 top-1/2 -translate-y-1/2 h-6 w-0.5 bg-foreground rounded-r" />
                )}
                <Icon className="h-4 w-4 shrink-0" />
                <span className="text-sm font-medium flex-1 truncate">{surface.name}</span>
                {isLocked && <Lock className="h-3 w-3 shrink-0 text-muted-foreground" />}
              </button>
            );
          })}
        </nav>

        <div className="px-4 py-3 border-t space-y-2">
          {lockedCount === activeSurfaces.length && lockedCount > 0 && (
            <p className="text-[10px] text-muted-foreground flex items-center gap-1">
              <CheckCircle2 className="h-3 w-3" /> All surfaces locked
            </p>
          )}
          <button
            onClick={() => setSurfaces([])}
            className="text-[11px] text-muted-foreground hover:text-foreground transition-colors"
          >
            + Edit surfaces
          </button>
        </div>
      </div>

      {/* Main content */}
      <div className="flex-1 overflow-y-auto p-8">
        {currentSurface && (
          <SurfaceSection
            surface={currentSurface}
            selectedThemeId={selectedThemes[currentSurface.id] ?? null}
            lockedThemeId={surfaceThemes[currentSurface.id] ?? null}
            onSelect={themeId => setSelectedThemes(prev => ({ ...prev, [currentSurface.id]: themeId }))}
            onLock={() => handleLock(currentSurface.id)}
            onUnlock={() => handleUnlock(currentSurface.id)}
            saving={savingLock === currentSurface.id}
          />
        )}
      </div>
    </div>
  );
}
