/* AIPlatformPage.jsx — ADMIN control console for the Phase-0 AI integration layer.
   Lets a manager/editor scope, preview, and export the machine-readable bundle that
   coding agents consume (tokens / components / copy / glossary / icons + AGENTS.md / llms.txt),
   and wire up the MCP server. Pure UI over the window fns in ai-export.jsx. */
const { useState: useStateAI, useMemo: useMemoAI, useEffect: useEffectAI } = React;

/* ---- small local Switch (ui.jsx has none) — token-colored, light/dark safe ---- */
function AISwitch({ checked, onChange, disabled }) {
  return (
    <button type="button" role="switch" aria-checked={checked} disabled={disabled}
      onClick={() => !disabled && onChange(!checked)}
      className={cx('relative inline-flex items-center w-9 h-5 rounded-full transition-colors duration-150 focus-ring shrink-0',
        disabled ? 'opacity-40 pointer-events-none' : '', checked ? 'bg-accent' : 'bg-[color:var(--border-strong)]')}>
      <span className={cx('absolute top-0.5 w-4 h-4 rounded-full bg-panel shadow-[0_1px_2px_rgba(0,0,0,0.2)] transition-all duration-150', checked ? 'left-[18px]' : 'left-0.5')} />
    </button>
  );
}

/* ---- a labeled card ---- */
function AICard({ icon, title, desc, children, right }) {
  return (
    <section className="rounded-[14px] border border-line bg-panel overflow-hidden">
      <div className="flex items-start gap-3 px-5 pt-4 pb-3.5 border-b border-line">
        <span className="w-8 h-8 rounded-[10px] bg-accentWeak text-accent flex items-center justify-center shrink-0 mt-0.5"><Icon name={icon} size={17} /></span>
        <div className="min-w-0 flex-1">
          <h2 className="text-[15px] font-semibold text-ink leading-tight">{title}</h2>
          {desc && <p className="text-[12.5px] text-ink2 mt-1 leading-snug">{desc}</p>}
        </div>
        {right}
      </div>
      <div className="p-5">{children}</div>
    </section>
  );
}

/* ---- a copy-on-click code block ---- */
function AICodeBlock({ code, onCopy }) {
  const [copied, setCopied] = useStateAI(false);
  const doCopy = () => { try { navigator.clipboard.writeText(code); } catch (e) {} setCopied(true); setTimeout(() => setCopied(false), 1400); if (onCopy) onCopy(); };
  return (
    <div className="relative rounded-[10px] border border-line bg-sunken">
      <pre className="m-0 px-3.5 py-3 pr-12 overflow-x-auto ds-scroll text-[12.5px] leading-relaxed font-mono text-ink whitespace-pre">{code}</pre>
      <button onClick={doCopy} title={tr('Copy', '复制')}
        className="absolute top-2 right-2 inline-flex items-center gap-1 h-7 px-2 rounded-[7px] bg-panel border border-line text-ink2 hover:text-accent hover:border-accent transition text-[11.5px]">
        <Icon name={copied ? 'check' : 'copy'} size={13} className={copied ? 'text-success' : ''} />{copied ? tr('Copied', '已复制') : tr('Copy', '复制')}
      </button>
    </div>
  );
}

/* ---- one downloadable bundle-file chip with a live count ---- */
function AIFileChip({ name, label, count, onDownload }) {
  return (
    <button onClick={onDownload}
      className="group inline-flex items-center gap-2 h-9 pl-3 pr-2.5 rounded-[10px] border border-line bg-panel hover:border-accent hover:bg-hover transition text-left">
      <Icon name={/\.json$/.test(name) ? 'hash' : 'edit'} size={14} className="text-ink3 group-hover:text-accent shrink-0" />
      <span className="flex flex-col leading-none">
        <span className="font-mono text-[12px] text-ink">{name}</span>
        {label && <span className="text-[10.5px] text-ink3 mt-0.5">{label}{count != null ? ' · ' + count : ''}</span>}
      </span>
      <Icon name="download" size={14} className="text-ink3 group-hover:text-accent ml-1 shrink-0" />
    </button>
  );
}

function AIPlatformPage({ ctx }) {
  /* ---- scope config (feeds opts into every export fn) ---- */
  const [publishedOnly, setPublishedOnly] = useStateAI(false);
  const [includeDrafts, setIncludeDrafts] = useStateAI(true);
  const allThemeIds = (typeof THEMES !== 'undefined' ? THEMES : []).map(t => t.id);
  const [themes, setThemes] = useStateAI(allThemeIds);
  const [toast, setToast] = useStateAI(null);

  /* publishedOnly implies no drafts — keep the include-drafts toggle consistent */
  useEffectAI(() => { if (publishedOnly) setIncludeDrafts(false); }, [publishedOnly]);

  const opts = useMemoAI(() => ({ publishedOnly, includeDrafts, themes }), [publishedOnly, includeDrafts, themes]);
  const counts = useMemoAI(() => aiCounts(opts), [opts]);
  const version = useMemoAI(() => aiVersion(), []);
  const agentsMd = useMemoAI(() => aiAgentsMd(opts), [opts]);
  const tokensPreview = useMemoAI(() => {
    const s = aiTokensJSON(opts); return s.length > 2600 ? s.slice(0, 2600) + '\n…' : s;
  }, [opts]);

  const flash = (msg) => { setToast(msg); setTimeout(() => setToast(null), 1800); };
  const toggleTheme = (id) => setThemes(ts => ts.includes(id) ? (ts.length > 1 ? ts.filter(x => x !== id) : ts) : ts.concat(id));

  const FILES = [
    { name: 'tokens.json', label: tr('Tokens (DTCG)', 'Token（DTCG）'), count: counts.tokens },
    { name: 'components.json', label: tr('Components', '组件'), count: counts.components },
    { name: 'copy.json', label: tr('UI strings', '界面文案'), count: counts.copy },
    { name: 'glossary.json', label: tr('Glossary', '术语表'), count: counts.glossary },
    { name: 'icons.json', label: tr('Icons', '图标'), count: counts.icons },
    { name: 'AGENTS.md', label: tr('Agent rules', '接入规范'), count: null },
    { name: 'llms.txt', label: tr('Index', '索引'), count: null },
  ];

  const mcpSnippet = 'claude mcp add sicarrier \\\n  --env SICARRIER_DIR=/abs/path/to/design-system \\\n  -- node /abs/path/to/sicarrier-mcp.js';

  const summaryLine = tr(
    counts.tokens + ' tokens · ' + counts.components + ' components · ' + counts.copy + ' strings · ' + counts.glossary + ' terms · ' + counts.icons + ' icons',
    counts.tokens + ' 个 token · ' + counts.components + ' 个组件 · ' + counts.copy + ' 条文案 · ' + counts.glossary + ' 个术语 · ' + counts.icons + ' 个图标');

  return (
    <div className="h-full flex flex-col bg-app">
      <PageToolbar
        title={tr('AI integration', 'AI 接入')}
        subtitle={tr('Generate the machine-readable bundle that AI coding agents consume — tokens, components, copy, glossary and icons, plus AGENTS.md and an MCP server.',
          '生成供 AI 编码 Agent 消费的机器可读包 —— token、组件、文案、术语与图标，外加 AGENTS.md 和 MCP 服务。')}
        contextHint={<span className="inline-flex items-center gap-1.5 text-[12px] text-ink3"><Icon name="info" size={13} />{tr('Client-side · no upload', '本地生成 · 不上传')}</span>}
      />

      <div className="flex-1 overflow-y-auto ds-scroll">
        <div className="max-w-[980px] mx-auto px-6 py-5 flex flex-col gap-4">

          {/* ---- Scope config ---- */}
          <AICard icon="sliders" title={tr('Scope', '导出范围')}
            desc={tr('Choose what goes into the bundle. These settings feed every download and the preview below.', '选择导出内容。以下设置会作用于全部下载与下方预览。')}>
            <div className="flex flex-col divide-y divide-[color:var(--border)]">
              <div className="flex items-center gap-4 py-2.5 first:pt-0">
                <div className="flex-1 min-w-0">
                  <div className="text-[13.5px] font-medium text-ink">{tr('Published only', '仅已发布')}</div>
                  <div className="text-[12px] text-ink2 mt-0.5">{tr('Exclude deprecated tokens, deprecated components, and unpublished copy.', '排除已废弃的 token、已废弃组件与未发布文案。')}</div>
                </div>
                <AISwitch checked={publishedOnly} onChange={setPublishedOnly} />
              </div>
              <div className="flex items-center gap-4 py-2.5">
                <div className="flex-1 min-w-0">
                  <div className="text-[13.5px] font-medium text-ink">{tr('Include drafts', '包含草稿')}</div>
                  <div className="text-[12px] text-ink2 mt-0.5">{tr('Keep components and tokens with in-progress drafts.', '保留仍处于草稿状态的组件与 token。')}</div>
                </div>
                <AISwitch checked={includeDrafts} onChange={setIncludeDrafts} disabled={publishedOnly} />
              </div>
              <div className="py-2.5 last:pb-0">
                <div className="flex items-center justify-between gap-3 mb-2">
                  <div className="min-w-0">
                    <div className="text-[13.5px] font-medium text-ink">{tr('Themes', '主题')}</div>
                    <div className="text-[12px] text-ink2 mt-0.5">{tr('Brand themes included in the resolved value table.', '解析值表中包含的品牌主题。')}</div>
                  </div>
                  <div className="flex items-center gap-1.5 shrink-0">
                    <button onClick={() => setThemes(allThemeIds)} className="text-[12px] text-accent hover:underline">{tr('All', '全部')}</button>
                  </div>
                </div>
                <div className="flex flex-wrap gap-1.5">
                  {(typeof THEMES !== 'undefined' ? THEMES : []).map(t => {
                    const on = themes.includes(t.id);
                    return (
                      <button key={t.id} onClick={() => toggleTheme(t.id)}
                        className={cx('inline-flex items-center gap-1.5 h-7 pl-1.5 pr-2.5 rounded-[8px] border transition text-[12.5px] font-medium',
                          on ? 'border-accent bg-accentWeak text-accent' : 'border-line bg-panel text-ink2 hover:text-ink hover:bg-hover')}>
                        <span className="w-3 h-3 rounded-full border border-[color:var(--border-strong)]" style={{ background: t.accent[500] }} />
                        {t.name}
                        {on && <Icon name="check" size={12} />}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          </AICard>

          {/* ---- Export bundle ---- */}
          <AICard icon="download" title={tr('Export bundle', '导出包')}
            desc={summaryLine}
            right={<Button variant="primary" icon="download" onClick={() => { downloadAIBundle(opts); flash(tr('Downloading bundle…', '正在下载…')); }}>{tr('Download bundle', '下载整包')}</Button>}>
            <div className="text-[11px] uppercase tracking-wide text-ink3 mb-2">{tr('Or download a single file', '或单独下载某个文件')}</div>
            <div className="flex flex-wrap gap-2">
              {FILES.map(f => (
                <AIFileChip key={f.name} name={f.name} label={f.label} count={f.count}
                  onDownload={() => { downloadBundleFile(f.name, opts); flash(tr('Downloaded', '已下载') + ' ' + f.name); }} />
              ))}
            </div>
            <div className="mt-3 text-[12px] text-ink3 flex items-center gap-1.5">
              <Icon name="info" size={13} />
              {tr('“Download bundle” also writes a combined sicarrier-design-system.json.', '「下载整包」同时会生成合并的 sicarrier-design-system.json。')}
            </div>
          </AICard>

          {/* ---- MCP connection ---- */}
          <AICard icon="network" title={tr('Connect via MCP', '通过 MCP 接入')}
            desc={tr('Run the bundled server so an agent can query the system live (resolve tokens, look up components, lint code).', '运行随附的服务，让 Agent 实时查询系统（解析 token、查组件、校验代码）。')}>
            <div className="flex flex-col gap-3">
              <div>
                <div className="text-[11px] uppercase tracking-wide text-ink3 mb-1.5">{tr('1 · Install dependencies', '1 · 安装依赖')}</div>
                <AICodeBlock code={'npm i @modelcontextprotocol/sdk zod'} onCopy={() => flash(tr('Copied', '已复制'))} />
              </div>
              <div>
                <div className="text-[11px] uppercase tracking-wide text-ink3 mb-1.5">{tr('2 · Register the server', '2 · 注册服务')}</div>
                <AICodeBlock code={mcpSnippet} onCopy={() => flash(tr('Copied', '已复制'))} />
              </div>
              <div className="flex items-center gap-2 flex-wrap">
                <Button variant="secondary" icon="download" onClick={() => { downloadBundleFile('sicarrier-mcp.js', opts); flash(tr('Downloaded sicarrier-mcp.js', '已下载 sicarrier-mcp.js')); }}>
                  {tr('Download sicarrier-mcp.js', '下载 sicarrier-mcp.js')}
                </Button>
                <span className="text-[12px] text-ink3">{tr('Reads the bundle from SICARRIER_DIR. A hosted URL variant comes after server-side persistence.', '从 SICARRIER_DIR 读取导出包。托管 URL 版本将在支持服务端持久化后推出。')}</span>
              </div>
              <div className="flex flex-wrap gap-1.5 pt-0.5">
                {['resolve_token', 'get_component', 'search_components', 'get_copy', 'search_glossary', 'find_icon', 'lint_against_system'].map(t => (
                  <span key={t} className="inline-flex items-center h-[22px] px-2 rounded-[6px] bg-sunken border border-line font-mono text-[11px] text-ink2">{t}</span>
                ))}
              </div>
            </div>
          </AICard>

          {/* ---- What AI sees ---- */}
          <AICard icon="eye" title={tr('What AI sees', 'AI 看到的内容')}
            desc={tr('The exact AGENTS.md and tokens preview generated for the current scope.', '当前范围下生成的 AGENTS.md 与 token 预览。')}>
            <div className="rounded-[10px] border border-line bg-sunken px-4 py-3 max-h-[420px] overflow-y-auto ds-scroll">
              <MarkdownDoc md={agentsMd} />
            </div>
            <div className="text-[11px] uppercase tracking-wide text-ink3 mt-4 mb-1.5">{tr('tokens.json (preview)', 'tokens.json（预览）')}</div>
            <pre className="m-0 rounded-[10px] border border-line bg-sunken px-3.5 py-3 overflow-auto ds-scroll text-[11.5px] leading-relaxed font-mono text-ink2 max-h-[280px]">{tokensPreview}</pre>
          </AICard>

          {/* ---- Version stamp ---- */}
          <div className="flex items-center gap-3 px-1 pb-2 text-[12px] text-ink3 flex-wrap">
            <span className="inline-flex items-center gap-1.5"><Icon name="clock" size={13} />{tr('Bundle version', '版本')}: <span className="text-ink2 font-medium">{version.cycle}</span></span>
            {version.date && <span className="inline-flex items-center gap-1.5"><span className="w-1 h-1 rounded-full bg-ink3" />{tr('Latest release', '最近发版')} {version.date}</span>}
            {version.branch && <span className="inline-flex items-center gap-1.5"><Icon name="branch" size={13} /><span className="font-mono">{version.branch}</span></span>}
          </div>
        </div>
      </div>

      {toast && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[80] inline-flex items-center gap-2 h-10 px-4 rounded-[12px] bg-[#1D1D1F] text-white text-[13px] shadow-[0_8px_28px_rgba(0,0,0,0.25)]" style={{ animation: 'fadeIn 140ms ease' }}>
          <Icon name="check" size={15} />{toast}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AIPlatformPage, AISwitch });
