// landing-app.jsx — header, hero, assistant demo, marketplace, ecosystem,
// built-in sections, comparison, stack, CTA, footer, root <App>.
//
// Globals expected from sibling babel scripts:
//   I, Icon, HUE, BUILTIN, MARKET_PERSONAL, MARKET_BUSINESS, ECO_PERSONAL, ECO_BUSINESS,
//   TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakToggle, TweakColor.

const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

// ── Feature flags ─────────────────────────────────────────────────────────
// MARKETPLACE_ENABLED: when false, hides the live marketplace UI:
//   - nav link "Marketplace"
//   - hero CTA "Browse marketplace"
//   - search/filter rail in the Fork-a-working-app section
//   - "Browse the full marketplace" button at the section's bottom
// The section heading + a small set of example cards stay visible.
// Flip back to `true` to restore the full marketplace.
const MARKETPLACE_ENABLED = false;

// When marketplace is disabled, only show this many example cards.
const MARKETPLACE_PREVIEW_LIMIT = 6;

// ── Translation dictionary ─────────────────────────────────────────────
// Mode-specific keys: tm("hero_lead", lang, mode) tries hero_lead_<mode>
// first, then plain hero_lead. Most chrome is mode-agnostic.
const TR = {
  en: {
    nav_assistant: "Assistant", nav_marketplace: "Marketplace",
    nav_ecosystems: "Ecosystems", nav_builtin: "Built-in", nav_compare: "Why us",
    sign_in: "Sign in", get_started: "Get started",
    mode_personal: "Personal", mode_business: "Business",

    hero_eyebrow_personal: "Not a skill, not an agent — a working product",
    hero_eyebrow_business: "Your whole company, on one platform",
    hero_title_a_personal: "Lovable builds you one app —\nwe help you ship an ",
    hero_title_b_personal: "ecosystem",
    hero_title_c_personal: ".",
    hero_title_a_business: "SaaS sells you one tool —\nwe help you ship your entire ",
    hero_title_b_business: "stack",
    hero_title_c_business: ".",
    hero_lead_personal: "Project Areti is where you build it, ship it, and connect — a real app (UI, backend, database, scheduled jobs, RBAC) bundled into one section, live the moment it installs.",
    hero_lead_business: "Project Areti is where you build, ship, and connect company-wide tools — CRM, HR, Finance, Observability. Each one a real app (UI, backend, database, jobs, RBAC) in one section, live the moment it installs.",
    hero_cta_primary: "Start building", hero_cta_secondary: "Browse marketplace",
    hero_meta_a: "Forkable like a repo", hero_meta_b: "Live the moment you install",

    async_eyebrow: "Build from anywhere",
    async_title: "Dictate. Forget it. Come back to a ready section.",
    async_lead: "The assistant ships in the background. Voice-message it the spec from your phone, walk away — come back, the section is live.",
    async_step1: "Dictate from your phone",
    async_step2: "Assistant ships while you're away",
    async_step3: "Open the app — section is live",

    assistant_eyebrow: "Section assistant",
    assistant_title: "Describe it in chat. Walk into a real section.",

    market_eyebrow: "Sections marketplace",
    market_title_personal: "Fork a working app. Plug it into your life.",
    market_title_business: "Fork a working app. Plug it into your stack.",

    eco_eyebrow: "Ecosystems",
    eco_title_personal: "Sport, Food, AI Trainer — your data, one ecosystem.",
    eco_title_business: "CRM, Company, Finances — your business, one fabric.",
    eco_lead_personal: "Sport logs workouts and vitals. Food tracks calories and macros. AI Trainer reads both and plans your week. Shared entities, one search, one RBAC. Fork the bundle, the wiring travels.",
    eco_lead_business: "Sales CRM closes deals. Company maps reporting lines. Finances rolls up cash flow. Shared entities, one search, one RBAC. Fork the bundle, the wiring travels with it.",

    builtin_eyebrow: "Built-in",
    builtin_title: "Two foundational sections — free with every workspace.",
    builtin_lead: "Documentation indexes anything as a knowledge base. AI Hub is where you build, version, and share every plugin.",

    cmp_eyebrow: "Why us",
    cmp_title: "One tab. Idea → section → publish.",
    cmp_lead_a: "Skills age out. Single agents break. ",
    cmp_lead_b: "Our sections",
    cmp_lead_c: " plug into the platform's contract — routes, schema, RBAC, search, MCP — not glue code that rots.",

    cta_title: "Build a section today.", cta_title_b: "Own it forever.",
    cta_lead: "Spin up a workspace, describe what you want, ship to the marketplace.",
    cta_primary: "Start free", cta_secondary: "Read the docs",
    cta_a: "Free workspace, 1 vCPU pod, unlimited public sections",
    cta_b: "Bring your own MCPs, .env, git branches",
    cta_c: "Auto-indexed search across everything you've connected",

    foot_product: "Product", foot_build: "Build",
    foot_community: "Community", foot_company: "Company",
    foot_tagline: "areti is the unit-of-distribution shift: a section is a complete vertical slice, not a snippet.",
    search_sections: "Search sections, authors, tags…",
    install: "Install", open_preview: "Open preview",
    trending: "Trending", all: "All",
  },
  ru: {
    nav_assistant: "Ассистент", nav_marketplace: "Маркетплейс",
    nav_ecosystems: "Экосистемы", nav_builtin: "Из коробки", nav_compare: "Почему мы",
    sign_in: "Войти", get_started: "Попробовать",
    mode_personal: "Личное", mode_business: "Бизнес",

    hero_eyebrow_personal: "Не скилл, не агент, а рабочий продукт",
    hero_eyebrow_business: "Вся компания на одной платформе",
    hero_title_a_personal: "Lovable собирает одно приложение —\nА мы помогаем выпустить ",
    hero_title_b_personal: "экосистему",
    hero_title_c_personal: ".",
    hero_title_a_business: "SaaS продаёт один инструмент —\nА мы помогаем выпустить весь ",
    hero_title_b_business: "стек",
    hero_title_c_business: ".",
    hero_lead_personal: "Project Areti — место, где собираешь, выпускаешь и связываешь приложения. Одна секция — это целое приложение: интерфейс, бэкенд, база, фоновые задачи, доступы. Поставил — работает.",
    hero_lead_business: "Project Areti — место, где собираешь, выпускаешь и связываешь инструменты для всей компании: CRM, HR, финансы, observability. Каждый — это целое приложение (UI, бэкенд, база, задачи, доступы) в одной секции. Поставил — работает.",
    hero_cta_primary: "Собрать секцию", hero_cta_secondary: "В маркетплейс",
    hero_meta_a: "Форкается как репо", hero_meta_b: "Работает с первой секунды",

    async_eyebrow: "Откуда угодно",
    async_title: "Надиктовал. Забыл. Вернулся — секция готова.",
    async_lead: "Ассистент собирает всё в фоне. Надиктовал с телефона, ушёл — возвращаешься, а секция уже живая.",
    async_step1: "Надиктовал с телефона",
    async_step2: "Ассистент работает, пока ты отдыхаешь",
    async_step3: "Открыл приложение — секция живая",

    assistant_eyebrow: "Чат-ассистент",
    assistant_title: "Расскажи в чате — получишь рабочую секцию.",

    market_eyebrow: "Маркетплейс секций",
    market_title_personal: "Возьми готовое приложение и подключи к своей жизни.",
    market_title_business: "Возьми готовое приложение и подключи к корпоративному стеку.",

    eco_eyebrow: "Экосистемы",
    eco_title_personal: "Спорт, еда и AI-тренер — все данные в одной экосистеме.",
    eco_title_business: "CRM, Company и Finances — вся компания, одна ткань.",
    eco_lead_personal: "Спорт следит за тренировками и показателями. Еда — за калориями и макросами. AI-тренер читает и то, и другое и строит план на неделю. Общие сущности, единый поиск, единые доступы.",
    eco_lead_business: "CRM закрывает сделки. Company хранит оргструктуру. Finances собирает цифры. Общие сущности, общий поиск, один RBAC. Форкаешь пакет — все связи едут вместе.",

    builtin_eyebrow: "Из коробки",
    builtin_title: "Две базовые секции — бесплатно, в каждом воркспейсе.",
    builtin_lead: "Documentation индексирует любые данные как базу знаний. AI Hub — место, где ты собираешь, версионируешь и раздаёшь плагины.",

    cmp_eyebrow: "Почему мы",
    cmp_title: "Одна вкладка. Идея → секция → публикация.",
    cmp_lead_a: "Скиллы устаревают. Отдельные агенты ломаются. ",
    cmp_lead_b: "Наши секции",
    cmp_lead_c: " живут на контракте платформы — роуты, схемы, RBAC, поиск, MCP — а не на клее, который гниёт.",

    cta_title: "Собери секцию за вечер.", cta_title_b: "А она останется твоей.",
    cta_lead: "Открыл воркспейс, рассказал, что нужно — и выложил в маркетплейс.",
    cta_primary: "Начать бесплатно", cta_secondary: "Открыть доки",
    cta_a: "Бесплатный воркспейс, 1 vCPU, сколько угодно публичных секций",
    cta_b: "Свои MCP, .env и git-ветки",
    cta_c: "Поиск по всему, что подключил — индексируется сам",

    foot_product: "Продукт", foot_build: "Сборка",
    foot_community: "Сообщество", foot_company: "Команда",
    foot_tagline: "areti меняет правила: делятся не кусками кода, а целыми секциями — со всем, что нужно для запуска.",
    search_sections: "Найди секцию, автора или тег…",
    install: "Поставить", open_preview: "Посмотреть",
    trending: "В топе", all: "Все",
  }
};
const LangCtx = createContext("en");
const ModeCtx = createContext("personal");
const useLang = () => useContext(LangCtx);
const useMode = () => useContext(ModeCtx);
const t  = (key, lang) => (TR[lang] && TR[lang][key]) || TR.en[key] || key;
// Mode-aware translation: tm("hero_lead", lang, mode) → hero_lead_<mode> first
const tm = (key, lang, mode) => {
  const k = `${key}_${mode}`;
  return (TR[lang] && TR[lang][k]) || (TR.en && TR.en[k]) || t(key, lang);
};
window.TR = TR; window.LangCtx = LangCtx; window.ModeCtx = ModeCtx;
window.useLang = useLang; window.useMode = useMode;
window.t = t; window.tm = tm;

// ──────────────────────────────────────────────────────────────────────────
// Brand mark + small bits
// ──────────────────────────────────────────────────────────────────────────
function BrandMark({ size = 28 }) {
  return (
    <span className="brand-mark"
      style={{ width: size, height: size, background: "transparent", border: 0 }}>
      <img src="assets/potato.png" alt="areti" width={size} height={size}
        style={{ width: size, height: size, objectFit: "contain", display: "block" }} />
    </span>
  );
}

function Brand({ subtitle }) {
  return (
    <a href="#top" className="brand">
      <BrandMark size={44} />
      <span style={{ display: "flex", flexDirection: "column" }}>
        <span className="brand-name">areti</span>
        {subtitle && <span className="brand-sub">{subtitle}</span>}
      </span>
    </a>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Header
// ──────────────────────────────────────────────────────────────────────────
function Header({ theme, setTheme, lang, setLang, mode, setMode, marketplaceHref = "#marketplace" }) {
  return (
    <header className="nav">
      <div className="nav-inner">
        <Brand />
        <span className="mode-toggle" role="group" aria-label="Mode">
          <button type="button" className={mode === "personal" ? "on" : ""} onClick={() => setMode("personal")}>
            <I.user width={14} height={14} /> {t("mode_personal", lang)}
          </button>
          <button type="button" className={mode === "business" ? "on" : ""} onClick={() => setMode("business")}>
            <I.building width={14} height={14} /> {t("mode_business", lang)}
          </button>
        </span>
        <nav className="nav-links" aria-label="Primary">
          <a className="nav-link" href="#assistant">{t("nav_assistant", lang)}</a>
          {MARKETPLACE_ENABLED && (
            <a className="nav-link" href={marketplaceHref}>{t("nav_marketplace", lang)}</a>
          )}
          <a className="nav-link" href="#ecosystems">{t("nav_ecosystems", lang)}</a>
          <a className="nav-link" href="#built-in">{t("nav_builtin", lang)}</a>
          <a className="nav-link" href="#compare">{t("nav_compare", lang)}</a>
        </nav>
        <div className="nav-cta">
          <span className="lang-toggle" role="group" aria-label="Language">
            <button type="button" className={lang === "en" ? "on" : ""} onClick={() => setLang("en")}>EN</button>
            <span className="sep">|</span>
            <button type="button" className={lang === "ru" ? "on" : ""} onClick={() => setLang("ru")}>RU</button>
          </span>
          <button className="icon-btn" type="button" aria-label="Toggle theme"
            onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
            {theme === "dark" ? <I.sun /> : <I.moon />}
          </button>
          <button className="btn btn-ghost btn-sm" type="button">{t("sign_in", lang)}</button>
          <button className="btn btn-primary btn-sm" type="button">
            {t("get_started", lang)}
            <I.arrowRight />
          </button>
        </div>
      </div>
    </header>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Hero — combined: copy on left, phone "Build from anywhere" on right
// ─────────────────────────────────────────────────────────────────
function PhoneVisual({ step, lang, mode = "personal" }) {
  // PERSONAL: "Add a subscription tracker"  → Subscriptions section
  // BUSINESS: "Build a conference-contacts app" → Contacts section
  const isRu = lang === "ru";
  const labels = isRu
    ? { dict: "Слушаю…", work: "Собираю…", done: "Готово — секция живая" }
    : { dict: "Listening…", work: "Building…", done: "Live — open it" };

  const content = mode === "business"
    ? {
        prompt: isRu ? "«Сделай приложение для контактов с конференций»" : "\"Build a conference-contacts app\"",
        appName: "Contacts",
        tiles: [["18", isRu ? "новых" : "new"], ["3", "events"]],
        rows: [
          { a: "Maya Chen",   b: "OpenAI · UX",         c: "@maya" },
          { a: "Jonas Park",  b: "Linear · PM",         c: "@jonas_p" },
          { a: "Ali Bakr",    b: "Stripe · Engineer",   c: "@ali" },
        ],
        files: ["schema.sql", "app/contacts/page.tsx", "scan/qr.ts"],
        tags: ["+migrate", "UI", "qr"],
      }
    : {
        prompt: isRu ? "«Добавь трекер подписок»" : "\"Add a subscription tracker\"",
        appName: "Subscriptions",
        tiles: [["$50.22", "monthly"], ["12", "active"]],
        rows: [
          { a: "Netflix",   b: "next May 24",     c: "$15.99" },
          { a: "Spotify",   b: "Family · May 18", c: "$16.99" },
          { a: "iCloud+",   b: "Yearly · Aug 02", c: "$2.99" },
        ],
        files: ["schema.sql", "app/subs/page.tsx", "jobs/sync.ts"],
        tags: ["+migrate", "UI", "cron"],
      };

  return (
    <div className="phone-frame">
      <div className="phone-notch"/>
      <div className="phone-screen">
        <div className="phone-bar">
          <span>9:41</span>
          <span style={{display:"flex", gap:4, alignItems:"center"}}>
            <span style={{fontSize:9}}>5G</span>
            <span style={{width:14, height:7, border:"1px solid currentColor", borderRadius:2, position:"relative"}}>
              <span style={{position:"absolute", inset:1, background:"currentColor", width:"70%"}}/>
            </span>
          </span>
        </div>
        <div className="phone-body">
          <div className="phone-app-head">
            <span className="phone-app-name">areti</span>
            <span className="phone-app-state">{step===0?labels.dict:step===1?labels.work:labels.done}</span>
          </div>

          {step === 0 && (
            <div className="phone-mic-card">
              <div className="phone-mic-wave">
                {[0,1,2,3,4,5,6,7,8,9,10,11].map(i => (
                  <span key={i} style={{animationDelay: `${i*0.06}s`}}/>
                ))}
              </div>
              <div className="phone-bubble">{content.prompt}</div>
            </div>
          )}

          {step === 1 && (
            <div className="phone-work">
              {content.files.map((f, i) => (
                <div className="phone-row" key={f}>
                  <span className="phone-spinner"/>
                  <span style={{fontSize:12, color:"hsl(var(--muted-foreground))"}}>{f}</span>
                  <span className={`phone-tag ${i===0?"ok":""}`}>{content.tags[i]}</span>
                </div>
              ))}
              <div className="phone-progress"><span/></div>
            </div>
          )}

          {step === 2 && (
            <div className="phone-done">
              <div className="phone-done-card">
                <div className="phone-done-head">
                  <span className="phone-done-ic"><I.check width={14} height={14}/></span>
                  <span style={{fontSize:13, fontWeight:600}}>{content.appName}</span>
                  <span className="phone-tag ok" style={{marginLeft:"auto"}}>live</span>
                </div>
                <div className="phone-tile-row">
                  {content.tiles.map(([lbl, sub], i) => (
                    <span className="phone-tile" key={i}><span className="lbl">{lbl}</span><span className="sub">{sub}</span></span>
                  ))}
                </div>
                {content.rows.map((r, i) => (
                  <div className="phone-list-row" key={i}>
                    <b style={{fontWeight:600}}>{r.a}</b>
                    <span style={{color:"hsl(var(--muted-foreground))", marginLeft:6}}>{r.b}</span>
                    {r.c && <span style={{float:"right", fontFamily:"var(--font-mono)", fontSize:11}}>{r.c}</span>}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Hero() {
  const lang = useLang();
  const mode = useMode();

  const [step, setStep] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setStep(s => (s + 1) % 3), 2600);
    return () => clearInterval(id);
  }, []);
  const steps = [
    { ic: "mic",   k: "async_step1" },
    { ic: "cog",   k: "async_step2" },
    { ic: "check", k: "async_step3" },
  ];

  return (
    <section className="hero" id="top">
      <div className="hero-grid" />
      <div className="container hero-inner">
        <div className="hero-copy">
          <span className="eyebrow"><span className="dot" /> {tm("hero_eyebrow", lang, mode)}</span>
          <h1 className="h-display">
            {tm("hero_title_a", lang, mode)}
            <span className="ink-grad">{tm("hero_title_b", lang, mode)}</span>
            {tm("hero_title_c", lang, mode)}
          </h1>
          <p className="lead">{tm("hero_lead", lang, mode)}</p>
          <div className="hero-cta-row">
            <button className="btn btn-primary btn-lg" type="button">
              {t("hero_cta_primary", lang)}
              <I.arrowRight />
            </button>
            {MARKETPLACE_ENABLED && (
              <a className="btn btn-outline btn-lg" href="Marketplace.html">
                <I.grid />
                {t("hero_cta_secondary", lang)}
              </a>
            )}
          </div>
          <div className="hero-meta">
            <span className="hero-meta-item"><I.check /> {t("hero_meta_a", lang)}</span>
            <span className="hero-meta-item"><I.check /> {t("hero_meta_b", lang)}</span>
          </div>
        </div>

        <div className="hero-right">
          <div className="async-header">
            <span className="eyebrow"><span className="dot"/> {t("async_eyebrow", lang)}</span>
            <h3 className="async-title">{t("async_title", lang)}</h3>
            <p className="async-lead">{t("async_lead", lang)}</p>
          </div>
          <PhoneVisual step={step} lang={lang} mode={mode}/>
          <div className="async-steps async-steps-row">
            {steps.map((s, i) => {
              const active = i === step;
              const Ic = I[s.ic] || I.check;
              return (
                <div key={i} className={`async-step ${active ? "on" : ""}`}>
                  <span className="ic"><Ic width={13} height={13}/></span>
                  <span className="lbl">{t(s.k, lang)}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </section>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Assistant demo — chat builds a section, preview shows it live
// ──────────────────────────────────────────────────────────────────────────
function AssistantDemo() {
  const lang = useLang();
  const mode = useMode();
  const [tab, setTab] = useState("preview");

  const script = mode === "business" ? {
    user1: "Build me a sales CRM. Pipeline stages, deals, contacts, activity feed.",
    bot1Intro: "Sales CRM",
    bot1After: " section with deals, contacts, activities, pipeline kanban, and an activity feed.",
    tools1: [
      ["db.migrate", "create table deals, contacts, activities (...)"],
      ["rls.policy", "scope by org_id, owner can write"],
      ["ui.page",    "/app/crm → render <Pipeline/>"],
    ],
    user2: "Add a webhook on stage change.",
    bot2Intro: "stage_change_webhook",
    bot2After: ". Fires on every deal stage transition, posts to your URL plus Slack.",
    tools2: [
      ["trigger.webhook", "deals.stage_change → POST {{webhook_url}}"],
      ["mcp.expose",      "section.crm → MCP tool"],
    ],
    inputPlaceholder: 'Try: "Add a slack notify when deal > $50k"',
  } : {
    user1: "Build me a habit tracker. Daily checkboxes, streaks, weekly review job.",
    bot1Intro: "Habit Tracker",
    bot1After: " section with a daily grid, streak counters, and a weekly Trigger.dev job.",
    tools1: [
      ["db.migrate", "create table habits (id uuid pk, …)"],
      ["rls.policy", "allow owner read/write on habits"],
      ["ui.page",    "/app/habits → render <HabitGrid/>"],
    ],
    user2: "Add a simple weekly review email.",
    bot2Intro: "weekly_review",
    bot2After: ". Runs on Sundays and emails the streak summary.",
    tools2: [
      ["trigger.cron", "weekly_review · 0 18 * * 0"],
      ["mcp.expose",   "section.habits → MCP tool"],
    ],
    inputPlaceholder: 'Try: "Connect this to my Daily Habits"',
  };

  return (
    <section className="section" id="assistant">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot" /> {t("assistant_eyebrow", lang)}</span>
          <h2 className="h-section">{t("assistant_title", lang)}</h2>
        </div>

        <div className="demo-panel">
          <div className="demo-chat">
            <div className="demo-tab">
              <span className="live-dot" />
              <span>workspace · pod-7f2 · main</span>
              <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 11 }}>
                claude · 9 turns
              </span>
            </div>
            <div className="demo-chat-body">
              <ChatMessage who="user" text={script.user1} />
              <ChatMessage who="bot">
                <div>I'll scaffold a <b>{script.bot1Intro}</b>{script.bot1After}</div>
                {script.tools1.map(([name, line]) => <ToolCall key={name} name={name} line={line} ok />)}
              </ChatMessage>
              <ChatMessage who="user" text={script.user2} />
              <ChatMessage who="bot">
                <div>Wiring <span className="mono" style={{fontSize:12, background:"hsl(var(--muted))", padding:"1px 5px", borderRadius:4}}>{script.bot2Intro}</span>{script.bot2After}</div>
                {script.tools2.map(([name, line]) => <ToolCall key={name} name={name} line={line} ok />)}
                <div style={{ marginTop: 6 }}>
                  Done. Open the preview to click around — each change auto-commits and you can rewind.
                </div>
              </ChatMessage>
            </div>
            <div className="demo-chat-input">
              <input placeholder={script.inputPlaceholder} />
              <button className="btn btn-primary btn-sm" type="button">
                <I.send />
              </button>
            </div>
          </div>

          <div className="demo-preview">
            <div className="demo-preview-tabs">
              <button className={`pt ${tab === "preview" ? "active" : ""}`} onClick={() => setTab("preview")}>Preview</button>
              <button className={`pt ${tab === "schema" ? "active" : ""}`} onClick={() => setTab("schema")}>Schema</button>
              <button className={`pt ${tab === "jobs" ? "active" : ""}`} onClick={() => setTab("jobs")}>Jobs</button>
              <button className={`pt ${tab === "rbac" ? "active" : ""}`} onClick={() => setTab("rbac")}>RBAC</button>
              <span className="right">
                <span className="pt"><I.copy /></span>
                <span className="pt"><I.externalLink /></span>
              </span>
            </div>
            <div className="demo-preview-body">
              {tab === "preview" && (mode === "business" ? <CRMPreview/> : <HabitTrackerPreview/>)}
              {tab === "schema"  && (mode === "business" ? <CRMSchemaPreview/> : <SchemaPreview/>)}
              {tab === "jobs"    && (mode === "business" ? <CRMJobsPreview/> : <JobsPreview/>)}
              {tab === "rbac"    && <RbacPreview/>}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function CRMPreview() {
  const cols = [
    { name: "Lead",      tone: "muted",   items: [["Vercel","$48k · demo Mon"], ["Linear","$22k · cold"]] },
    { name: "Qualified", tone: "primary", items: [["Stripe","$120k · RFP sent"], ["Figma","$60k · in legal"]] },
    { name: "Proposal",  tone: "amber",   items: [["Notion","$84k · review"]] },
    { name: "Closing",   tone: "green",   items: [["Anthropic","$310k · PO Fri"]] },
  ];
  const hueMap = HUE;
  return (
    <div className="gen-section">
      <div className="gen-section-head">
        <div><h3>Sales CRM</h3><p>Pipeline · May · auto-generated by Assistant</p></div>
        <button className="btn btn-outline btn-sm" type="button"><I.plus /> New deal</button>
      </div>
      <div className="kpi-row">
        <div className="kpi"><div className="lbl">Open pipeline</div><div className="val">$644k</div><div className="delta">+$112k MoM</div></div>
        <div className="kpi"><div className="lbl">Won this Q</div><div className="val">$1.4M</div><div className="delta">82% to plan</div></div>
        <div className="kpi"><div className="lbl">Win rate</div><div className="val">28%</div><div className="delta">+4 pts</div></div>
      </div>
      <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:10}}>
        {cols.map(c => {
          const hue = hueMap[c.tone] || hueMap.primary;
          return (
            <div key={c.name} style={{
              background: "hsl(var(--muted) / 0.4)",
              border: "1px solid hsl(var(--border))",
              borderRadius: 10, padding: 10, minHeight: 200,
            }}>
              <div style={{fontSize:11, fontWeight:600, textTransform:"uppercase", letterSpacing:".07em", color:`hsl(${hue})`, marginBottom:8}}>{c.name}</div>
              <div style={{display:"flex", flexDirection:"column", gap:6}}>
                {c.items.map(([n, s]) => (
                  <div key={n} style={{
                    background: "hsl(var(--card))",
                    border: "1px solid hsl(var(--border))",
                    borderRadius: 8, padding: "8px 10px",
                    fontSize: 12,
                  }}>
                    <div style={{fontWeight:600, fontSize:13}}>{n}</div>
                    <div style={{color:"hsl(var(--muted-foreground))"}}>{s}</div>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function CRMSchemaPreview() {
  return (
    <div className="gen-section">
      <div className="gen-section-head"><div><h3>Schema</h3><p>Generated migrations · Supabase + RLS</p></div></div>
      <pre style={{
        margin: 0, padding: 16, borderRadius: 12,
        background: "hsl(16 18% 14%)", color: "hsl(180 6% 98%)",
        fontFamily: "var(--font-mono)", fontSize: 12, lineHeight: 1.6, overflow: "auto",
      }}>{`create table deals (
  id        uuid primary key default gen_random_uuid(),
  org_id    uuid not null,
  owner_id  uuid references auth.users,
  name      text not null,
  amount_cents bigint default 0,
  stage     text not null default 'lead',
  close_on  date,
  created_at timestamptz default now()
);
create table contacts (
  id uuid primary key default gen_random_uuid(),
  deal_id uuid references deals on delete cascade,
  name text, email text, role text
);
create table activities (
  deal_id uuid references deals on delete cascade,
  at timestamptz default now(),
  kind text, body text
);

alter table deals enable row level security;
create policy org_rw on deals
  using (org_id = current_setting('app.org')::uuid);`}</pre>
    </div>
  );
}

function CRMJobsPreview() {
  const jobs = [
    { name: "stage_change_webhook", cron: "(event)",   last: "8 min ago",   status: "ok" },
    { name: "weekly_pipeline_email", cron: "0 9 * * 1", last: "Monday",     status: "ok" },
    { name: "sla_reminder",          cron: "@hourly",   last: "6 minutes",  status: "ok" },
  ];
  return (
    <div className="gen-section">
      <div className="gen-section-head"><div><h3>Jobs</h3><p>Trigger.dev · auto-registered</p></div></div>
      <div className="habit-table">
        <div className="habit-row hd" style={{ gridTemplateColumns: "1fr 1fr 1fr 80px" }}>
          <span className="name">Job</span><span className="name">Schedule</span><span className="name">Last run</span><span className="name" style={{textAlign:"right"}}>Status</span>
        </div>
        {jobs.map(j => (
          <div className="habit-row" key={j.name} style={{ gridTemplateColumns: "1fr 1fr 1fr 80px" }}>
            <span className="name mono" style={{fontSize:12}}>{j.name}</span>
            <span className="mono muted" style={{fontSize:12}}>{j.cron}</span>
            <span className="muted" style={{fontSize:12}}>{j.last}</span>
            <span style={{textAlign:"right"}}>
              <span style={{
                fontSize: 11, padding: "2px 8px", borderRadius: 9999,
                background: "hsl(var(--success) / 0.12)", color: "hsl(142 71% 30%)",
                fontWeight: 500,
              }}>{j.status}</span>
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}


function ChatMessage({ who, text, children }) {
  return (
    <div className={`msg ${who}`} style={who === "user" ? { marginLeft: "auto" } : null}>
      {who === "bot" && (
        <span className="msg-av bot">
          <I.spark width={14} height={14} />
        </span>
      )}
      <div className="msg-bubble">
        {text || children}
      </div>
      {who === "user" && <span className="msg-av user">AK</span>}
    </div>
  );
}

function ToolCall({ name, line, ok }) {
  return (
    <div className="tool-call">
      <div className="tc-head">
        {ok && <span className="ok"><I.check /></span>}
        <span>{name}</span>
        <span style={{ marginLeft: "auto", color: ok ? "hsl(var(--success))" : "inherit" }}>
          {ok ? "ok" : "…"}
        </span>
      </div>
      <div className="tc-body">{line}</div>
    </div>
  );
}

// ── Demo preview tabs ──────────────────────────────────────────────────────
function HabitTrackerPreview() {
  const days = ["M", "T", "W", "T", "F", "S", "S"];
  const habits = [
    { name: "Morning run",        sub: "30 minutes",        on: [1,1,1,0,1,1,0], streak: 12 },
    { name: "Read",               sub: "20 pages",          on: [1,1,1,1,1,0,0], streak: 5  },
    { name: "Weekly review",      sub: "Sunday eve",        on: [0,0,0,0,0,0,1], streak: 8  },
    { name: "Inbox zero",         sub: "End of day",        on: [1,1,0,1,1,1,0], streak: 3  },
  ];
  return (
    <div className="gen-section">
      <div className="gen-section-head">
        <div>
          <h3>Habit Tracker</h3>
          <p>Week of May 10 · auto-generated by Assistant</p>
        </div>
        <button className="btn btn-outline btn-sm" type="button">
          <I.plus /> New habit
        </button>
      </div>
      <div className="kpi-row">
        <div className="kpi"><div className="lbl">Done today</div><div className="val">3 / 4</div><div className="delta">+1 vs avg</div></div>
        <div className="kpi"><div className="lbl">Longest streak</div><div className="val">12d</div><div className="delta">Morning run</div></div>
        <div className="kpi"><div className="lbl">Weekly score</div><div className="val">82%</div><div className="delta">+9% wow</div></div>
      </div>
      <div className="habit-table">
        <div className="habit-row hd">
          <span className="name">Habit</span>
          {days.map((d, i) => <span className="day" key={i} style={{ background: "transparent" }}>{d}</span>)}
          <span className="streak" style={{ fontFamily: "inherit", fontSize: 11, color: "hsl(var(--muted-foreground))", textTransform: "uppercase", letterSpacing: ".06em" }}>Streak</span>
        </div>
        {habits.map((h) => (
          <div className="habit-row" key={h.name}>
            <span className="name">{h.name}<span className="sub">{h.sub}</span></span>
            {h.on.map((on, i) => (
              <span className={`day ${on ? "done" : ""}`} key={i}>
                {on ? <I.check /> : null}
              </span>
            ))}
            <span className="streak"><span className="fire">●</span> {h.streak}d</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function SchemaPreview() {
  return (
    <div className="gen-section">
      <div className="gen-section-head"><div><h3>Schema</h3><p>Generated migrations · Supabase + RLS</p></div></div>
      <pre style={{
        margin: 0, padding: 16, borderRadius: 12,
        background: "hsl(16 18% 14%)", color: "hsl(180 6% 98%)",
        fontFamily: "var(--font-mono)", fontSize: 12, lineHeight: 1.6, overflow: "auto",
      }}>{`create table habits (
  id        uuid primary key default gen_random_uuid(),
  user_id   uuid references auth.users on delete cascade,
  name      text not null,
  cadence   text not null default 'daily',
  created_at timestamptz default now()
);

create table habit_logs (
  habit_id  uuid references habits on delete cascade,
  done_on   date not null,
  primary key (habit_id, done_on)
);

-- RLS
alter table habits enable row level security;
create policy owner_rw on habits
  using  (auth.uid() = user_id)
  with check (auth.uid() = user_id);`}</pre>
    </div>
  );
}

function JobsPreview() {
  const jobs = [
    { name: "weekly_review", cron: "0 18 * * 0", last: "2 days ago", status: "ok" },
    { name: "streak_recompute", cron: "@hourly", last: "3 minutes ago", status: "ok" },
    { name: "digest_email", cron: "30 7 * * *", last: "yesterday", status: "ok" },
  ];
  return (
    <div className="gen-section">
      <div className="gen-section-head"><div><h3>Jobs</h3><p>Trigger.dev · auto-registered</p></div></div>
      <div className="habit-table">
        <div className="habit-row hd" style={{ gridTemplateColumns: "1fr 1fr 1fr 80px" }}>
          <span className="name">Job</span><span className="name">Schedule</span><span className="name">Last run</span><span className="name" style={{textAlign:"right"}}>Status</span>
        </div>
        {jobs.map(j => (
          <div className="habit-row" key={j.name} style={{ gridTemplateColumns: "1fr 1fr 1fr 80px" }}>
            <span className="name mono" style={{fontSize:12}}>{j.name}</span>
            <span className="mono muted" style={{fontSize:12}}>{j.cron}</span>
            <span className="muted" style={{fontSize:12}}>{j.last}</span>
            <span style={{textAlign:"right"}}>
              <span style={{
                fontSize: 11, padding: "2px 8px", borderRadius: 9999,
                background: "hsl(var(--success) / 0.12)", color: "hsl(142 71% 30%)",
                fontWeight: 500,
              }}>{j.status}</span>
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

function RbacPreview() {
  return (
    <div className="gen-section">
      <div className="gen-section-head"><div><h3>RBAC</h3><p>Roles + policies generated for this section</p></div></div>
      <div style={{display:"grid", gap: 10}}>
        {[
          ["owner", "full read/write on habits, habit_logs", HUE.primary],
          ["viewer", "read-only on shared habits", HUE.cyan],
          ["assistant", "read on habits when MCP is enabled", HUE.violet],
        ].map(([role, desc, hue]) => (
          <div key={role} style={{
            display:"flex", alignItems:"center", gap:12,
            padding:"12px 14px", border:"1px solid hsl(var(--border))",
            borderRadius:10, background:"hsl(var(--card))",
          }}>
            <span style={{
              width:32, height:32, borderRadius:8,
              background:`hsl(${hue} / 0.12)`, color:`hsl(${hue})`,
              display:"inline-flex", alignItems:"center", justifyContent:"center",
            }}><I.shield /></span>
            <span style={{display:"flex", flexDirection:"column"}}>
              <span style={{fontSize:13, fontWeight:600}}>{role}</span>
              <span style={{fontSize:12, color:"hsl(var(--muted-foreground))"}}>{desc}</span>
            </span>
            <span className="mono" style={{
              marginLeft:"auto", fontSize:11,
              background:"hsl(var(--muted))", padding:"2px 8px",
              borderRadius:6, color:"hsl(var(--muted-foreground))",
            }}>policy.sql</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Marketplace
// ──────────────────────────────────────────────────────────────────────────
function MarketplaceSection() {
  const lang = useLang();
  const mode = useMode();
  const data = mode === "business" ? MARKET_BUSINESS : MARKET_PERSONAL;
  const catsPersonal = ["All", "Finance", "Tracker", "Career", "Fitness", "Home", "Travel"];
  const catsBusiness = ["All", "Sales", "People", "Finance", "DevOps", "Support", "Risk"];
  const cats = mode === "business" ? catsBusiness : catsPersonal;
  const [filter, setFilter] = useState("All");
  useEffect(() => { setFilter("All"); }, [mode]);
  const filtered = filter === "All" ? data : data.filter(m => (m.tags || []).includes(filter));
  // When marketplace is disabled, show a curated preview set (no search/chips/full-browse CTA).
  const visibleCards = MARKETPLACE_ENABLED ? filtered : data.slice(0, MARKETPLACE_PREVIEW_LIMIT);

  // Preview-mode layout: heading on the left, simple illustrative cards on the right.
  if (!MARKETPLACE_ENABLED) {
    return (
      <section className="section section-tinted" id="marketplace">
        <div className="container">
          <div className="market-split">
            <div className="market-split-copy">
              <span className="eyebrow"><span className="dot" /> {t("market_eyebrow", lang)}</span>
              <h2 className="h-section">{tm("market_title", lang, mode)}</h2>
              <p className="lead">
                Stars, forks, leaderboards — the primitives users already know. The
                difference: every card is a runnable section, not a dead repo. One
                click installs it into your platform and it just works.
              </p>
            </div>
            <div className="market-example-grid">
              {visibleCards.map(card => <MarketExampleCard key={card.title} card={card} />)}
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="section section-tinted" id="marketplace">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot" /> {t("market_eyebrow", lang)}</span>
          <h2 className="h-section">{tm("market_title", lang, mode)}</h2>
          <p className="lead">
            Stars, forks, leaderboards — the primitives users already know. The
            difference: every card is a runnable section, not a dead repo. One
            click installs it into your platform and it just works.
          </p>
        </div>

        <div className="market-rail">
          <a className="rail-search" href="Marketplace.html" style={{textDecoration:"none", color:"inherit"}}>
            <I.search />
            <span>{t("search_sections", lang)}</span>
            <span className="kbd">⌘K</span>
          </a>
          {cats.map(c => (
            <button
              key={c}
              type="button"
              className={`chip ${filter === c ? "active" : ""}`}
              onClick={() => setFilter(c)}
            >
              {c}
            </button>
          ))}
          <a className="chip" href="Marketplace.html" style={{ marginLeft: "auto", color: "hsl(var(--primary))", textDecoration:"none" }}>
            <I.trending /> {t("trending", lang)}
          </a>
        </div>

        <div className="market-grid">
          {visibleCards.map(card => <MarketCard key={card.title} card={card} />)}
        </div>
        <div style={{display:"flex", justifyContent:"center", marginTop: 32}}>
          <a className="btn btn-outline btn-lg" href="Marketplace.html">
            <I.grid /> {lang === "ru" ? "Открыть весь маркетплейс" : "Browse the full marketplace"}
            <I.arrowRight />
          </a>
        </div>
      </div>
    </section>
  );
}

// Simplified, illustrative card used in the preview-mode (MARKETPLACE_ENABLED=false).
// Just: tag, icon, title, one-line desc. No stats, no verified badge, no author.
function MarketExampleCard({ card }) {
  const IconCmp = I[card.iconKey];
  return (
    <article className="mk-example">
      <div className="mk-example-head">
        <span className="mk-example-icon" style={{
          background: `hsl(${card.hue} / 0.14)`, color: `hsl(${card.hue})`
        }}>
          <IconCmp />
        </span>
        <span className="mk-example-tag">{(card.tags?.[0]) || "Section"}</span>
      </div>
      <div className="mk-example-title">{card.title}</div>
      <div className="mk-example-desc">{card.desc}</div>
    </article>
  );
}

function MarketCard({ card }) {
  const IconCmp = I[card.iconKey];
  return (
    <article className="mk-card">
      <div className="mk-thumb" style={{ "--mk-color": `hsl(${card.hue})` }}>
        <span className="glow" />
        <span style={{ position:"absolute", top:14, left:14, fontSize:10, fontWeight:600,
          letterSpacing:".07em", textTransform:"uppercase",
          color:"hsl(var(--muted-foreground))" }}>{(card.tags?.[0]) || "Section"}</span>
        <span style={{
          position: "absolute", right: 14, top: 14,
          width: 30, height: 30, borderRadius: 8,
          background: `hsl(${card.hue} / 0.12)`, color: `hsl(${card.hue})`,
          display: "inline-flex", alignItems: "center", justifyContent: "center",
        }}><IconCmp /></span>
        <div className="mk-thumb-bars" style={{ top: 48 }}>
          <span className="mk-thumb-row" style={{ width: "55%" }} />
          <div style={{ display: "flex", gap: 6, height: 28 }}>
            <span className="mk-thumb-tile" />
            <span className="mk-thumb-tile" style={{ background: `hsl(${card.hue} / 0.12)`, borderColor: `hsl(${card.hue} / 0.3)` }} />
            <span className="mk-thumb-tile" />
          </div>
          <span className="mk-thumb-row" style={{ width: "70%" }} />
          <span className="mk-thumb-row" style={{ width: "40%" }} />
        </div>
      </div>
      <div className="mk-meta">
        <div className="mk-meta-head">
          <div className="mk-title">{card.title}</div>
          {card.verified && <span className="pubchip verified">Verified</span>}
        </div>
        <div className="mk-author"><I.user width={11} height={11} /> {card.author}</div>
        <div className="mk-desc">{card.desc}</div>
      </div>
      <div className="mk-foot">
        <div className="mk-stats">
          <span className="mk-stat"><I.starFill /> {card.stars.toLocaleString()}</span>
          <span className="mk-stat"><I.fork /> {card.forks}</span>
          <span className="mk-stat credits">{card.credits}</span>
        </div>
        {MARKETPLACE_ENABLED ? (
          <a className="mk-install" href={`Marketplace.html#${card.id}`}>{t("open_preview", (window.__lang || "en"))} <I.arrowRight /></a>
        ) : (
          <span className="mk-install" style={{opacity:.55, cursor:"default"}}>Example <I.arrowRight /></span>
        )}
      </div>
    </article>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Ecosystem diagram
// ──────────────────────────────────────────────────────────────────────────
function EcosystemSection() {
  const lang = useLang();
  const mode = useMode();
  const nodes = mode === "business" ? ECO_BUSINESS : ECO_PERSONAL;
  return (
    <section className="section" id="ecosystems">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot" /> {t("eco_eyebrow", lang)}</span>
          <h2 className="h-section">{tm("eco_title", lang, mode)}</h2>
          <p className="lead">{tm("eco_lead", lang, mode)}</p>
        </div>

        <div className="eco-board">
          <div className="eco-grid-bg" />
          <div className="eco-positions">
            <EcosystemDiagram />
            {nodes.map(node => <EcosystemNode key={node.id} node={node} />)}
          </div>

          <div className="eco-rails">
            <span className="eco-rail"><I.search /> Universal semantic search</span>
            <span className="eco-rail"><I.shield /> RBAC across every section</span>
            <span className="eco-rail"><I.network /> MCP-exposed to the agent</span>
            <span className="eco-rail"><I.fork /> Forkable as one bundle</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function EcosystemDiagram() {
  // SVG with viewBox 1000x480 covering the eco-positions area.
  const stroke = "hsl(150 60% 36% / 0.4)";
  return (
    <svg className="eco-svg" viewBox="0 0 1000 480" preserveAspectRatio="none">
      <defs>
        <linearGradient id="eline" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%"  stopColor="hsl(150 60% 36%)" stopOpacity="0.6"/>
          <stop offset="100%" stopColor="hsl(150 60% 66%)" stopOpacity="0.6"/>
        </linearGradient>
      </defs>
      {/* Subs → Finance (top) */}
      <path d="M 230 80 C 400 30, 600 30, 770 80" fill="none" stroke="url(#eline)" strokeWidth="1.5" strokeDasharray="6 5"/>
      {/* Subs → Habits */}
      <path d="M 230 110 C 280 220, 380 320, 470 350" fill="none" stroke="url(#eline)" strokeWidth="1.5" strokeDasharray="6 5"/>
      {/* Finance → Habits */}
      <path d="M 770 110 C 720 220, 620 320, 530 350" fill="none" stroke="url(#eline)" strokeWidth="1.5" strokeDasharray="6 5"/>
      {/* small data dots along paths */}
      {[[500,55],[330,200],[670,200]].map(([x,y],i)=>(
        <circle key={i} cx={x} cy={y} r="3.5" fill="hsl(150 60% 36%)" opacity="0.8"/>
      ))}
    </svg>
  );
}

function EcosystemNode({ node }) {
  const IconCmp = I[node.iconKey];
  return (
    <div className="eco-node" style={node.pos}>
      <div className="head">
        <span className="ic" style={{ background: `hsl(${node.hue} / 0.12)`, color: `hsl(${node.hue})` }}>
          <IconCmp />
        </span>
        <span style={{ display: "flex", flexDirection: "column" }}>
          <span className="name">{node.name}</span>
          <span className="sub">{node.sub}</span>
        </span>
      </div>
      <div className="data">
        {node.data.map(([k, v], i) => (
          <div key={i}><b>{k}</b> &nbsp;{v}</div>
        ))}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Built-in sections + domain row
// ──────────────────────────────────────────────────────────────────────────
function BuiltInSection() {
  return (
    <section className="section section-tinted" id="built-in">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot" /> {t("builtin_eyebrow", useLang())}</span>
          <h2 className="h-section">{t("builtin_title", useLang())}</h2>
          <p className="lead">{t("builtin_lead", useLang())}</p>
        </div>

        <div className="builtin-grid">
          {BUILTIN.map((s) => {
            const IconCmp = I[s.iconKey];
            return (
              <article className="bi-card" key={s.id}>
                <span className="wash" style={{ background: `hsl(${s.hue} / 0.05)` }} />
                <span className="bi-ic" style={{ background: `hsl(${s.hue} / 0.12)`, color: `hsl(${s.hue})` }}>
                  <IconCmp />
                </span>
                <div className="bi-title">
                  {s.title}
                  {s.badge && (
                    <span style={{
                      fontSize: 10, fontWeight: 600,
                      padding: "2px 6px", borderRadius: 9999,
                      background: "hsl(150 60% 66% / 0.15)", color: "hsl(150 60% 66%)",
                      border: "1px solid hsl(150 60% 66% / 0.3)",
                      letterSpacing: ".08em",
                    }}>{s.badge}</span>
                  )}
                </div>
                <div className="bi-desc">{s.desc}</div>
                <ul style={{ listStyle: "none", padding: 0, margin: "12px 0 0", display: "flex", flexDirection: "column", gap: 6 }}>
                  {s.bullets.map(b => (
                    <li key={b} style={{ fontSize: 12, color: "hsl(var(--muted-foreground))", display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ width: 4, height: 4, borderRadius: 99, background: "hsl(var(--muted-foreground) / 0.6)" }} />
                      {b}
                    </li>
                  ))}
                </ul>
              </article>
            );
          })}
        </div>

      </div>
    </section>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Comparison
// ──────────────────────────────────────────────────────────────────────────
function ComparisonSection() {
  const lang = useLang();
  const cols = ["areti", "Wabi AI", "Claude skills", "Lovable"];
  const rows = [
    ["End-to-end sections (UI + backend + schema + jobs + RBAC)", [1, 0, 0, 1]],
    ["Live the moment you install",                                [1, 1, 0, 1]],
    ["Persistent workspaces",                                      [1, 0, 0, 1]],
    ["Forkable, remixable like a repo",                            [1, 0, 0, 0]],
    ["Marketplace with stars, forks, ecosystems",                  [1, 0, 0, 0]],
    ["Built through visible UI tooling",                           [1, 1, 0, 1]],
    ["Cross-product ecosystems (shared entities · search · RBAC)", [1, 0, 0, 0]],
  ];
  return (
    <section className="section" id="compare">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot" /> {t("cmp_eyebrow", lang)}</span>
          <h2 className="h-section">{t("cmp_title", lang)}</h2>
          <p className="lead">
            {t("cmp_lead_a", lang)}
            <strong>{t("cmp_lead_b", lang)}</strong>
            {t("cmp_lead_c", lang)}
          </p>
        </div>

        <div className="cmp-table" role="table" aria-label="Comparison">
          <div className="cmp-cell head">Capability</div>
          {cols.map((c, i) => (
            <div key={c} className={`cmp-cell head ${i === 0 ? "us-h" : ""}`}>{c}</div>
          ))}
          {rows.map(([label, vals], r) => (
            <React.Fragment key={r}>
              <div className="cmp-cell row-h">{label}</div>
              {vals.map((v, i) => (
                <div key={i} className={`cmp-cell ${i === 0 ? "us " : ""}${v ? "cmp-yes" : "cmp-no"}`}>
                  {v ? <I.check /> : <I.x />}
                </div>
              ))}
            </React.Fragment>
          ))}
        </div>
      </div>
    </section>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Stack strip
// ──────────────────────────────────────────────────────────────────────────
function StackStrip() {
  const items = [
    { name: "Next.js",      iconKey: "triangle", hue: HUE.primary },
    { name: "Supabase",     iconKey: "database", hue: HUE.green },
    { name: "Trigger.dev",  iconKey: "bolt",     hue: HUE.amber },
    { name: "Kubernetes",   iconKey: "container",hue: HUE.cyan },
    { name: "Claude Code",  iconKey: "spark",    hue: HUE.violet },
    { name: "Codex",        iconKey: "wand",     hue: HUE.rose },
    { name: "Superpowers",  iconKey: "zap",      hue: HUE.indigo },
  ];
  return (
    <section className="section-tight">
      <div className="container">
        <div className="stack-strip">
          <span className="label">Stack</span>
          {items.map(it => {
            const IconCmp = I[it.iconKey];
            return (
              <span className="item" key={it.name}>
                <span className="ic" style={{ background: `hsl(${it.hue} / 0.12)`, color: `hsl(${it.hue})` }}>
                  <IconCmp />
                </span>
                {it.name}
              </span>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// CTA + footer
// ──────────────────────────────────────────────────────────────────────────
function CTA() {
  const lang = useLang();
  return (
    <section className="section">
      <div className="container">
        <div className="cta-card">
          <span className="grid-bg" />
          <div className="lockup">
            <span className="mark"><I.spark width={40} height={40} /></span>
            <h3>{t("cta_title", lang)}<br/>{t("cta_title_b", lang)}</h3>
            <p>{t("cta_lead", lang)}</p>
            <div className="actions">
              <button className="btn btn-primary btn-lg" type="button">
                {t("cta_primary", lang)}
                <I.arrowRight />
              </button>
              <button className="btn btn-outline btn-lg" type="button">
                <I.book /> {t("cta_secondary", lang)}
              </button>
            </div>
          </div>
          <div className="cta-checks">
            <div className="item"><I.check /> {t("cta_a", lang)}</div>
            <div className="item"><I.check /> {t("cta_b", lang)}</div>
            <div className="item"><I.check /> {t("cta_c", lang)}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  const lang = useLang();
  return (
    <footer className="foot">
      <div className="container">
        <div className="foot-grid">
          <div>
            <Brand />
            <p style={{ fontSize: 13, color: "hsl(var(--muted-foreground))", maxWidth: 320, marginTop: 16 }}>
              {t("foot_tagline", lang)}
            </p>
          </div>
          <div className="foot-col">
            <h4>{t("foot_product", lang)}</h4>
            <a href="#assistant">{t("nav_assistant", lang)}</a>
            {MARKETPLACE_ENABLED && (
              <a href="Marketplace.html">{t("nav_marketplace", lang)}</a>
            )}
            <a href="#ecosystems">{t("nav_ecosystems", lang)}</a>
            <a href="#built-in">{t("nav_builtin", lang)}</a>
            <a href="#compare">{t("nav_compare", lang)}</a>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 areti · Built on Next.js, Supabase, Trigger.dev, Kubernetes, Claude.</span>
        </div>
      </div>
    </footer>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Tweaks (theme + accent)
// ──────────────────────────────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "blue-violet",
  "heroInk": "gradient"
}/*EDITMODE-END*/;

function applyAccent(tw) {
  // Accent palette swaps the logo gradient + ink-grad gradient
  const palettes = {
    "blue-violet":  ["30 50% 64%", "30 40% 38%"],
    "blue-cyan":    ["30 50% 64%", "30 60% 72%"],
    "indigo-rose":  ["30 35% 30%", "30 50% 60%"],
    "monochrome":   ["16 18% 17%", "16 18% 35%"],
  };
  const [a, b] = palettes[tw.accent] || palettes["blue-violet"];
  document.documentElement.style.setProperty(
    "--gradient-logo",
    `linear-gradient(to top right, hsl(${a}), hsl(${b}))`
  );
  // Hero headline ink
  document.documentElement.style.setProperty(
    "--ink-grad-bg",
    tw.heroInk === "gradient"
      ? `linear-gradient(to top right, hsl(${a}), hsl(${b}))`
      : "transparent"
  );
  document.querySelectorAll(".ink-grad").forEach(el => {
    if (tw.heroInk === "solid") {
      el.style.background = "transparent";
      el.style.color = "hsl(var(--foreground))";
      el.style.webkitTextFillColor = "currentColor";
    } else {
      el.style.background = `linear-gradient(to top right, hsl(${a}), hsl(${b}))`;
      el.style.webkitBackgroundClip = "text";
      el.style.backgroundClip = "text";
      el.style.color = "transparent";
      el.style.webkitTextFillColor = "transparent";
    }
  });
}

function Tweaks() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useEffect(() => { applyAccent(tweaks); }, [tweaks]);
  return (
    <TweaksPanel title="Tweaks" defaultOpen={false}>
      <TweakSection label="Accent palette" />
      <TweakSelect label="Brand" value={tweaks.accent}
        options={[
          { value: "blue-violet", label: "Blue → Violet" },
          { value: "blue-cyan",   label: "Blue → Cyan" },
          { value: "indigo-rose", label: "Indigo → Rose" },
          { value: "monochrome",  label: "Monochrome" },
        ]}
        onChange={v => setTweak("accent", v)} />

      <TweakSection label="Hero headline" />
      <TweakRadio label="Ink" value={tweaks.heroInk}
        options={["gradient", "solid"]}
        onChange={v => setTweak("heroInk", v)} />
    </TweaksPanel>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Root
// ──────────────────────────────────────────────────────────────────────────
function App() {
  const [theme, setTheme] = useState(() =>
    localStorage.getItem("idp-theme") ||
    (matchMedia && matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
  );
  const [lang, setLang] = useState(() => localStorage.getItem("idp-lang") || "en");
  const [mode, setMode] = useState(() => localStorage.getItem("idp-mode") || "personal");
  useEffect(() => {
    document.documentElement.classList.toggle("dark", theme === "dark");
    document.body.dataset.theme = theme;
    localStorage.setItem("idp-theme", theme);
  }, [theme]);
  useEffect(() => {
    document.documentElement.lang = lang;
    localStorage.setItem("idp-lang", lang);
    window.__lang = lang;
  }, [lang]);
  useEffect(() => {
    document.body.dataset.mode = mode;
    localStorage.setItem("idp-mode", mode);
    window.__mode = mode;
  }, [mode]);
  return (
    <LangCtx.Provider value={lang}>
     <ModeCtx.Provider value={mode}>
      <Header theme={theme} setTheme={setTheme} lang={lang} setLang={setLang} mode={mode} setMode={setMode} marketplaceHref="Marketplace.html" />
      <Hero />
      <MarketplaceSection />
      <AssistantDemo />
      <EcosystemSection />
      <BuiltInSection />
      <ComparisonSection />
      <StackStrip />
      <CTA />
      <Footer />
      <Tweaks />
    </ModeCtx.Provider>
    </LangCtx.Provider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
