/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

// ============================================================
// i18n
// ============================================================
const I18N = {
  es: {
    appName: "creation path",
    tagline: "Una ruta guiada para esculpir tu proyecto",
    start: "Empezar",
    back: "Atrás",
    next: "Siguiente",
    skip: "Omitir",
    continue: "Continuar",
    step: "Paso",
    of: "de",
    // Step 1
    s1_title: "¿Qué quieres crear hoy?",
    s1_sub: "Elige un punto de partida. Podrás cambiarlo más tarde.",
    type_landing: "Landing page",
    type_landing_d: "Una página de aterrizaje para presentar una idea, producto o evento.",
    type_site: "Sitio web",
    type_site_d: "Varias páginas conectadas, ideal para empresas, portafolios o blogs.",
    type_app: "Aplicación web",
    type_app_d: "Una app interactiva con lógica, vistas y estados — desde un panel hasta una herramienta.",
    type_ai: "Asistente IA",
    type_ai_d: "Un chat o agente conversacional con personalidad y conocimiento propios.",
    // Step 2
    s2_title: "¿Tu proyecto necesita guardar datos?",
    s2_sub: "Si activas almacenamiento, prepararemos una base de datos lista para usar.",
    s2_yes: "Sí, voy a guardar datos",
    s2_yes_d: "Usuarios, formularios, contenido dinámico, sesiones…",
    s2_no: "No, será estático",
    s2_no_d: "Solo lectura — sin formularios ni cuentas.",
    // Step 3
    s3_title: "¿Vas a integrar IA?",
    s3_sub: "Conecta una API key para que tu proyecto pueda llamar a modelos.",
    s3_yes: "Sí, conectaré IA",
    s3_no: "No por ahora",
    s3_keyl: "API key",
    s3_keyp: "sk-•••• (la guardaremos cifrada)",
    s3_provider: "Proveedor",
    // Step 4
    s4_title: "Cuéntanos sobre tu proyecto",
    s4_sub: "Estos datos guían al agente cuando empieza a esculpir el código.",
    s4_name: "Título del proyecto",
    s4_namep: "Mi proyecto luminoso",
    s4_goal: "Objetivo",
    s4_goalp: "¿Qué problema resuelve? ¿Para quién?",
    s4_desc: "Descripción",
    s4_descp: "Explica con tus palabras qué hará y cómo se sentirá.",
    // Step 5
    s5_title: "Conecta tu cuaderno",
    s5_sub: "Trae notas, documentos, capturas y referencias que ya tienes en la plataforma.",
    s5_connect: "Conectar cuaderno",
    s5_connected: "Cuaderno conectado",
    s5_files: "archivos sincronizados",
    s5_skip: "Continuar sin contexto adicional",
    // Step 6
    s6_title: "Tu estructura está lista",
    s6_sub: "Generamos el andamiaje según tu elección. El agente trabajará dentro de estos archivos sin alterar la estructura.",
    s6_open: "Abrir editor",
    // Editor
    ed_files: "Archivos",
    ed_skills: "Skills MCP",
    ed_search_skills: "Buscar skill…",
    ed_agent: "Agente",
    ed_run: "Ejecutar",
    ed_deploy: "Desplegar en aimaker",
    ed_preview: "Vista previa",
    ed_console: "Consola",
    ed_thinking: "Esculpiendo…",
    tutor_title: "Tutor",
    tutor_dismiss: "Entendido",
    // Deploy
    dep_title: "Desplegando tu proyecto",
    dep_building: "Empaquetando código",
    dep_uploading: "Subiendo a aimaker",
    dep_warming: "Encendiendo el servidor",
    dep_done: "¡Tu app está en vivo!",
    dep_url: "URL pública",
    dep_copy: "Copiar",
    dep_copied: "Copiado",
    dep_open: "Abrir app",
    dep_share: "Compartir",
    dep_close: "Volver al editor",
    // Live
    live_back: "Volver al editor",
    live_redeploy: "Re-desplegar",
    live_url: "URL en vivo",
  },
  en: {
    appName: "creation path",
    tagline: "A guided path to sculpt your project",
    start: "Begin",
    back: "Back",
    next: "Next",
    skip: "Skip",
    continue: "Continue",
    step: "Step",
    of: "of",
    s1_title: "What do you want to create today?",
    s1_sub: "Pick a starting point. You can change it later.",
    type_landing: "Landing page",
    type_landing_d: "A single page to introduce an idea, product or event.",
    type_site: "Website",
    type_site_d: "Multiple connected pages — companies, portfolios, blogs.",
    type_app: "Web application",
    type_app_d: "An interactive app with logic, views and state.",
    type_ai: "AI assistant",
    type_ai_d: "A conversational agent with its own personality and knowledge.",
    s2_title: "Does your project need to store data?",
    s2_sub: "If you enable storage, we'll prepare a ready-to-use database.",
    s2_yes: "Yes, I'll store data",
    s2_yes_d: "Users, forms, dynamic content, sessions…",
    s2_no: "No, it's static",
    s2_no_d: "Read-only — no forms or accounts.",
    s3_title: "Are you integrating AI?",
    s3_sub: "Connect an API key so your project can call models.",
    s3_yes: "Yes, I'll connect AI",
    s3_no: "Not yet",
    s3_keyl: "API key",
    s3_keyp: "sk-•••• (stored encrypted)",
    s3_provider: "Provider",
    s4_title: "Tell us about your project",
    s4_sub: "These details guide the agent when it starts sculpting the code.",
    s4_name: "Project title",
    s4_namep: "My luminous project",
    s4_goal: "Goal",
    s4_goalp: "What problem does it solve? For whom?",
    s4_desc: "Description",
    s4_descp: "In your own words, describe what it will do and how it will feel.",
    s5_title: "Connect your notebook",
    s5_sub: "Bring notes, docs, screenshots and references you already have in the platform.",
    s5_connect: "Connect notebook",
    s5_connected: "Notebook connected",
    s5_files: "files synced",
    s5_skip: "Continue without extra context",
    s6_title: "Your structure is ready",
    s6_sub: "We generated scaffolding for your choice. The agent will work inside these files without changing the structure.",
    s6_open: "Open editor",
    ed_files: "Files",
    ed_skills: "MCP skills",
    ed_search_skills: "Search skill…",
    ed_agent: "Agent",
    ed_run: "Run",
    ed_deploy: "Deploy to aimaker",
    ed_preview: "Preview",
    ed_console: "Console",
    ed_thinking: "Sculpting…",
    tutor_title: "Tutor",
    tutor_dismiss: "Got it",
    dep_title: "Deploying your project",
    dep_building: "Packing code",
    dep_uploading: "Uploading to aimaker",
    dep_warming: "Warming the server",
    dep_done: "Your app is live!",
    dep_url: "Public URL",
    dep_copy: "Copy",
    dep_copied: "Copied",
    dep_open: "Open app",
    dep_share: "Share",
    dep_close: "Back to editor",
    live_back: "Back to editor",
    live_redeploy: "Re-deploy",
    live_url: "Live URL",
  },
  fr: {
    appName: "creation path",
    tagline: "Un chemin guidé pour sculpter votre projet",
    start: "Commencer",
    back: "Retour",
    next: "Suivant",
    skip: "Passer",
    continue: "Continuer",
    step: "Étape",
    of: "sur",
    s1_title: "Que voulez-vous créer aujourd'hui ?",
    s1_sub: "Choisissez un point de départ. Modifiable plus tard.",
    type_landing: "Page d'accueil",
    type_landing_d: "Une page pour présenter une idée, un produit ou un événement.",
    type_site: "Site web",
    type_site_d: "Plusieurs pages connectées — entreprises, portfolios, blogs.",
    type_app: "Application web",
    type_app_d: "Une app interactive avec logique, vues et états.",
    type_ai: "Assistant IA",
    type_ai_d: "Un agent conversationnel avec personnalité et savoir.",
    s2_title: "Votre projet doit-il stocker des données ?",
    s2_sub: "Si oui, nous préparerons une base de données prête à l'emploi.",
    s2_yes: "Oui, je vais stocker",
    s2_yes_d: "Utilisateurs, formulaires, contenu dynamique, sessions…",
    s2_no: "Non, c'est statique",
    s2_no_d: "Lecture seule — sans formulaires ni comptes.",
    s3_title: "Allez-vous intégrer l'IA ?",
    s3_sub: "Connectez une clé API pour appeler des modèles.",
    s3_yes: "Oui, je connecte l'IA",
    s3_no: "Pas encore",
    s3_keyl: "Clé API",
    s3_keyp: "sk-•••• (stockée chiffrée)",
    s3_provider: "Fournisseur",
    s4_title: "Parlez-nous de votre projet",
    s4_sub: "Ces détails guident l'agent au moment de sculpter le code.",
    s4_name: "Titre du projet",
    s4_namep: "Mon projet lumineux",
    s4_goal: "Objectif",
    s4_goalp: "Quel problème résout-il ? Pour qui ?",
    s4_desc: "Description",
    s4_descp: "Avec vos mots, décrivez ce qu'il fera et comment il se sentira.",
    s5_title: "Connectez votre carnet",
    s5_sub: "Importez notes, documents et références déjà dans la plateforme.",
    s5_connect: "Connecter le carnet",
    s5_connected: "Carnet connecté",
    s5_files: "fichiers synchronisés",
    s5_skip: "Continuer sans contexte",
    s6_title: "Votre structure est prête",
    s6_sub: "Nous avons généré l'échafaudage. L'agent travaillera dans ces fichiers sans changer la structure.",
    s6_open: "Ouvrir l'éditeur",
    ed_files: "Fichiers",
    ed_skills: "Skills MCP",
    ed_search_skills: "Chercher une skill…",
    ed_agent: "Agent",
    ed_run: "Exécuter",
    ed_deploy: "Déployer sur aimaker",
    ed_preview: "Aperçu",
    ed_console: "Console",
    ed_thinking: "Sculpte…",
    tutor_title: "Tuteur",
    tutor_dismiss: "Compris",
    dep_title: "Déploiement en cours",
    dep_building: "Empaquetage du code",
    dep_uploading: "Téléversement vers aimaker",
    dep_warming: "Démarrage du serveur",
    dep_done: "Votre app est en ligne !",
    dep_url: "URL publique",
    dep_copy: "Copier",
    dep_copied: "Copié",
    dep_open: "Ouvrir",
    dep_share: "Partager",
    dep_close: "Retour à l'éditeur",
    live_back: "Retour à l'éditeur",
    live_redeploy: "Re-déployer",
    live_url: "URL en ligne",
  },
};

const LangCtx = createContext({ t: I18N.es, lang: "es", setLang: () => {} });
const useT = () => useContext(LangCtx);

// ============================================================
// Icons (minimal line)
// ============================================================
const Icon = {
  arrow: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 6l6 6-6 6" /></svg>,
  back: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M19 12H5M11 6l-6 6 6 6" /></svg>,
  check: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12l5 5L20 7" /></svg>,
  spark: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5L18 18M6 18l2.5-2.5M15.5 8.5L18 6" /></svg>,
  folder: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z" /></svg>,
  file: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z M14 3v6h6" /></svg>,
  search: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" /></svg>,
  copy: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V5a2 2 0 0 1 2-2h10" /></svg>,
  globe: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" /></svg>,
  notebook: (p) => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="5" y="3" width="14" height="18" rx="2" /><path d="M9 3v18M5 8h2M5 12h2M5 16h2" /></svg>,
  close: (p) => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M6 6l12 12M18 6L6 18" /></svg>,
};

// ============================================================
// Common UI atoms
// ============================================================
const Roman = ({ n }) => {
  const r = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"][n - 1] || String(n);
  return <span className="roman">{r}</span>;
};

const Btn = ({ variant = "primary", children, ...p }) => (
  <button className={`btn btn-${variant}`} {...p}>{children}</button>
);

const Pill = ({ children, tone = "default" }) => (
  <span className={`pill pill-${tone}`}>{children}</span>
);

const Card = ({ selected, onClick, children, className = "" }) => (
  <button
    type="button"
    onClick={onClick}
    className={`card-opt ${selected ? "is-selected" : ""} ${className}`}
  >
    {children}
  </button>
);

// ============================================================
// Top bar (always visible)
// ============================================================
function TopBar({ onHome }) {
  const { lang, setLang, t } = useT();
  return (
    <header className="topbar">
      <button className="brand" onClick={onHome}>
        <span className="brand-mark" aria-hidden>
          <svg viewBox="0 0 32 32" width="22" height="22">
            <circle cx="16" cy="16" r="14" fill="none" stroke="currentColor" strokeWidth="1.2" />
            <path d="M6 20 Q12 6 16 16 T26 12" fill="none" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
            <circle cx="6" cy="20" r="1.6" fill="currentColor" />
            <circle cx="26" cy="12" r="1.6" fill="currentColor" />
          </svg>
        </span>
        <span className="brand-name">{t.appName}</span>
      </button>
      <div className="topbar-right">
        <div className="lang-switch" role="tablist" aria-label="Language">
          {["es", "en", "fr"].map((l) => (
            <button
              key={l}
              role="tab"
              aria-selected={lang === l}
              className={`lang-btn ${lang === l ? "is-active" : ""}`}
              onClick={() => setLang(l)}
            >{l}</button>
          ))}
        </div>
      </div>
    </header>
  );
}

// ============================================================
// Welcome
// ============================================================
function Welcome({ onStart }) {
  const { t } = useT();
  return (
    <div className="welcome">
      <div className="welcome-inner">
        <Pill tone="muted">— {t.appName} —</Pill>
        <h1 className="display">
          {t.tagline.split(" ").map((w, i, arr) => (
            <React.Fragment key={i}>
              <span className="word">{w}</span>{i < arr.length - 1 ? " " : ""}
            </React.Fragment>
          ))}
        </h1>
        <p className="lede">
          {{
            es: "Responde unas preguntas, conecta tu cuaderno, deja que el agente esculpa el código y despliega cuando estés listo.",
            en: "Answer a few questions, connect your notebook, let the agent sculpt the code, and deploy when you're ready.",
            fr: "Répondez à quelques questions, connectez votre carnet, laissez l'agent sculpter le code, puis déployez."
          }[useT().lang]}
        </p>
        <div className="welcome-actions">
          <Btn variant="primary" onClick={onStart}>{t.start} <Icon.arrow /></Btn>
          <span className="welcome-meta">6 · {t.step.toLowerCase()}</span>
        </div>
        <div className="welcome-figure" aria-hidden>
          <svg viewBox="0 0 600 200" width="100%" height="200">
            <defs>
              <pattern id="dots" width="14" height="14" patternUnits="userSpaceOnUse">
                <circle cx="1" cy="1" r="1" fill="currentColor" opacity="0.18" />
              </pattern>
            </defs>
            <rect width="600" height="200" fill="url(#dots)" />
            <path d="M20 150 C 120 40, 220 180, 320 90 S 520 130, 580 60" fill="none" stroke="var(--accent)" strokeWidth="1.4" />
            <circle cx="20" cy="150" r="4" fill="var(--accent)" />
            <circle cx="580" cy="60" r="4" fill="var(--accent)" />
            <g fontFamily="var(--mono)" fontSize="10" fill="currentColor" opacity="0.55">
              <text x="28" y="166">idea</text>
              <text x="540" y="50">live</text>
            </g>
          </svg>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// Stepper
// ============================================================
function Stepper({ step, total }) {
  const { t } = useT();
  return (
    <div className="stepper">
      <div className="stepper-meta">
        <span className="stepper-label">{t.step}</span>
        <span className="stepper-num">
          <Roman n={step} /> <em>/</em> <Roman n={total} />
        </span>
      </div>
      <div className="stepper-track">
        {Array.from({ length: total }).map((_, i) => (
          <span key={i} className={`stepper-tick ${i < step ? "is-done" : ""} ${i === step - 1 ? "is-current" : ""}`} />
        ))}
      </div>
    </div>
  );
}

// ============================================================
// Wizard shell
// ============================================================
function Wizard({ state, setState, onDone, onBack }) {
  const { t } = useT();
  const total = 6;
  const [step, setStep] = useState(1);

  const canNext = useMemo(() => {
    if (step === 1) return !!state.projectType;
    if (step === 2) return state.storage !== null;
    if (step === 3) return state.ai !== null && (!state.ai || (state.aiKey && state.aiKey.length >= 4));
    if (step === 4) return state.title.trim() && state.goal.trim() && state.desc.trim();
    if (step === 5) return true;
    if (step === 6) return true;
    return true;
  }, [step, state]);

  const handleNext = () => {
    if (step < total) setStep(step + 1);
    else onDone();
  };

  const handleBack = () => {
    if (step === 1) onBack();
    else setStep(step - 1);
  };

  return (
    <div className="wizard">
      <Stepper step={step} total={total} />
      <div className="wizard-body">
        {step === 1 && <Step1 state={state} setState={setState} />}
        {step === 2 && <Step2 state={state} setState={setState} />}
        {step === 3 && <Step3 state={state} setState={setState} />}
        {step === 4 && <Step4 state={state} setState={setState} />}
        {step === 5 && <Step5 state={state} setState={setState} />}
        {step === 6 && <Step6 state={state} />}
      </div>
      <div className="wizard-foot">
        <button className="link-btn" onClick={handleBack}>
          <Icon.back /> {t.back}
        </button>
        <Btn variant="primary" onClick={handleNext} disabled={!canNext}>
          {step === total ? t.s6_open : t.next} <Icon.arrow />
        </Btn>
      </div>
    </div>
  );
}

// ============================================================
// Step 1 — project type
// ============================================================
function Step1({ state, setState }) {
  const { t } = useT();
  const opts = [
    { id: "landing", title: t.type_landing, desc: t.type_landing_d, glyph: "L" },
    { id: "site", title: t.type_site, desc: t.type_site_d, glyph: "S" },
    { id: "app", title: t.type_app, desc: t.type_app_d, glyph: "A" },
    { id: "ai", title: t.type_ai, desc: t.type_ai_d, glyph: "AI" },
  ];
  return (
    <div className="step">
      <header className="step-head">
        <h2 className="step-title">{t.s1_title}</h2>
        <p className="step-sub">{t.s1_sub}</p>
      </header>
      <div className="grid-4">
        {opts.map((o) => (
          <Card key={o.id} selected={state.projectType === o.id} onClick={() => setState({ ...state, projectType: o.id })}>
            <div className="opt-glyph" aria-hidden>{o.glyph}</div>
            <div className="opt-title">{o.title}</div>
            <div className="opt-desc">{o.desc}</div>
          </Card>
        ))}
      </div>
    </div>
  );
}

// ============================================================
// Step 2 — storage
// ============================================================
function Step2({ state, setState }) {
  const { t } = useT();
  return (
    <div className="step">
      <header className="step-head">
        <h2 className="step-title">{t.s2_title}</h2>
        <p className="step-sub">{t.s2_sub}</p>
      </header>
      <div className="grid-2">
        <Card selected={state.storage === true} onClick={() => setState({ ...state, storage: true })}>
          <div className="opt-glyph">+</div>
          <div className="opt-title">{t.s2_yes}</div>
          <div className="opt-desc">{t.s2_yes_d}</div>
          <div className="opt-meta">postgres · auth · storage</div>
        </Card>
        <Card selected={state.storage === false} onClick={() => setState({ ...state, storage: false })}>
          <div className="opt-glyph">○</div>
          <div className="opt-title">{t.s2_no}</div>
          <div className="opt-desc">{t.s2_no_d}</div>
          <div className="opt-meta">static · cdn</div>
        </Card>
      </div>
    </div>
  );
}

// ============================================================
// Step 3 — AI
// ============================================================
function Step3({ state, setState }) {
  const { t } = useT();
  return (
    <div className="step">
      <header className="step-head">
        <h2 className="step-title">{t.s3_title}</h2>
        <p className="step-sub">{t.s3_sub}</p>
      </header>
      <div className="grid-2">
        <Card selected={state.ai === true} onClick={() => setState({ ...state, ai: true })}>
          <div className="opt-glyph"><Icon.spark /></div>
          <div className="opt-title">{t.s3_yes}</div>
          <div className="opt-desc">openai · anthropic · mistral · local</div>
        </Card>
        <Card selected={state.ai === false} onClick={() => setState({ ...state, ai: false, aiKey: "" })}>
          <div className="opt-glyph">—</div>
          <div className="opt-title">{t.s3_no}</div>
          <div className="opt-desc">{state.ai === false ? "" : ""}</div>
        </Card>
      </div>
      {state.ai === true && (
        <div className="ai-form">
          <label className="field">
            <span className="field-label">{t.s3_provider}</span>
            <div className="provider-row">
              {["openai", "anthropic", "mistral", "local"].map((p) => (
                <button
                  key={p}
                  className={`chip ${state.aiProvider === p ? "is-on" : ""}`}
                  onClick={() => setState({ ...state, aiProvider: p })}
                >{p}</button>
              ))}
            </div>
          </label>
          <label className="field">
            <span className="field-label">{t.s3_keyl}</span>
            <input
              className="input mono"
              type="password"
              value={state.aiKey}
              placeholder={t.s3_keyp}
              onChange={(e) => setState({ ...state, aiKey: e.target.value })}
            />
          </label>
        </div>
      )}
    </div>
  );
}

// ============================================================
// Step 4 — info
// ============================================================
function Step4({ state, setState }) {
  const { t } = useT();
  return (
    <div className="step">
      <header className="step-head">
        <h2 className="step-title">{t.s4_title}</h2>
        <p className="step-sub">{t.s4_sub}</p>
      </header>
      <div className="form-grid">
        <label className="field">
          <span className="field-label">{t.s4_name}</span>
          <input className="input" value={state.title} placeholder={t.s4_namep} onChange={(e) => setState({ ...state, title: e.target.value })} />
        </label>
        <label className="field">
          <span className="field-label">{t.s4_goal}</span>
          <input className="input" value={state.goal} placeholder={t.s4_goalp} onChange={(e) => setState({ ...state, goal: e.target.value })} />
        </label>
        <label className="field field-wide">
          <span className="field-label">{t.s4_desc}</span>
          <textarea className="input" rows={4} value={state.desc} placeholder={t.s4_descp} onChange={(e) => setState({ ...state, desc: e.target.value })} />
        </label>
      </div>
    </div>
  );
}

// ============================================================
// Step 5 — notebook
// ============================================================
function Step5({ state, setState }) {
  const { t } = useT();
  const sample = [
    { name: "brief.md", kind: "doc" },
    { name: "moodboard-01.png", kind: "img" },
    { name: "moodboard-02.png", kind: "img" },
    { name: "audience-notes.md", kind: "doc" },
    { name: "competitive.pdf", kind: "doc" },
    { name: "logo-sketch.svg", kind: "img" },
  ];
  return (
    <div className="step">
      <header className="step-head">
        <h2 className="step-title">{t.s5_title}</h2>
        <p className="step-sub">{t.s5_sub}</p>
      </header>
      <div className="notebook-card">
        <div className="notebook-icon"><Icon.notebook /></div>
        <div className="notebook-body">
          <div className="notebook-name">notebook.local / {state.title || "untitled"}</div>
          {!state.notebookConnected ? (
            <div className="notebook-empty">— —</div>
          ) : (
            <div className="notebook-files">
              {sample.map((f) => (
                <div key={f.name} className="nb-file">
                  <span className="nb-glyph">{f.kind === "img" ? "▢" : "≡"}</span>
                  <span className="nb-name">{f.name}</span>
                </div>
              ))}
            </div>
          )}
          <div className="notebook-actions">
            {!state.notebookConnected ? (
              <Btn variant="primary" onClick={() => setState({ ...state, notebookConnected: true })}>
                {t.s5_connect} <Icon.arrow />
              </Btn>
            ) : (
              <span className="ok-line"><Icon.check /> {sample.length} {t.s5_files} · {t.s5_connected}</span>
            )}
            <button className="link-btn" onClick={() => setState({ ...state, notebookConnected: false })}>
              {t.s5_skip}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// Step 6 — structure preview
// ============================================================
const STRUCTURES = {
  landing: [
    { name: "index.html", lvl: 0 },
    { name: "styles.css", lvl: 0 },
    { name: "script.js", lvl: 0 },
    { name: "assets/", lvl: 0, dir: true },
    { name: "hero.svg", lvl: 1 },
    { name: "og-image.png", lvl: 1 },
    { name: "README.md", lvl: 0 },
  ],
  site: [
    { name: "pages/", lvl: 0, dir: true },
    { name: "index.html", lvl: 1 },
    { name: "about.html", lvl: 1 },
    { name: "contact.html", lvl: 1 },
    { name: "components/", lvl: 0, dir: true },
    { name: "nav.html", lvl: 1 },
    { name: "footer.html", lvl: 1 },
    { name: "styles/", lvl: 0, dir: true },
    { name: "tokens.css", lvl: 1 },
    { name: "main.css", lvl: 1 },
    { name: "README.md", lvl: 0 },
  ],
  app: [
    { name: "src/", lvl: 0, dir: true },
    { name: "App.jsx", lvl: 1 },
    { name: "routes/", lvl: 1, dir: true },
    { name: "Home.jsx", lvl: 2 },
    { name: "Dashboard.jsx", lvl: 2 },
    { name: "components/", lvl: 1, dir: true },
    { name: "Button.jsx", lvl: 2 },
    { name: "Card.jsx", lvl: 2 },
    { name: "lib/", lvl: 1, dir: true },
    { name: "db.js", lvl: 2 },
    { name: "auth.js", lvl: 2 },
    { name: "package.json", lvl: 0 },
    { name: "README.md", lvl: 0 },
  ],
  ai: [
    { name: "agent/", lvl: 0, dir: true },
    { name: "system.md", lvl: 1 },
    { name: "tools.json", lvl: 1 },
    { name: "knowledge/", lvl: 1, dir: true },
    { name: "context.md", lvl: 2 },
    { name: "ui/", lvl: 0, dir: true },
    { name: "Chat.jsx", lvl: 1 },
    { name: "Message.jsx", lvl: 1 },
    { name: "lib/", lvl: 0, dir: true },
    { name: "ai.js", lvl: 1 },
    { name: ".env.example", lvl: 0 },
    { name: "README.md", lvl: 0 },
  ],
};

function Step6({ state }) {
  const { t } = useT();
  const tree = STRUCTURES[state.projectType] || STRUCTURES.landing;
  return (
    <div className="step">
      <header className="step-head">
        <h2 className="step-title">{t.s6_title}</h2>
        <p className="step-sub">{t.s6_sub}</p>
      </header>
      <div className="structure-card">
        <div className="structure-meta">
          <Pill tone="accent">{state.projectType}</Pill>
          {state.storage && <Pill>storage</Pill>}
          {state.ai && <Pill>ai · {state.aiProvider}</Pill>}
          <span className="structure-title">{state.title || "untitled-project"}/</span>
        </div>
        <ul className="tree">
          {tree.map((n, i) => (
            <li key={i} className="tree-row" style={{ paddingLeft: 8 + n.lvl * 18 }}>
              <span className="tree-glyph">{n.dir ? <Icon.folder /> : <Icon.file />}</span>
              <span className={`tree-name ${n.dir ? "is-dir" : ""}`}>{n.name}</span>
              {!n.dir && <span className="tree-bytes">{Math.floor(40 + Math.random() * 800)} B</span>}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

Object.assign(window, { TopBar, Welcome, Wizard, useT, LangCtx, I18N, Icon, Btn, Pill });
