// Models — local transcription & grammar model catalogs (faithful to the app).
function ModelsScreen() {
  const { Button, Badge } = window.ROKKORDesignSystem_4e99ef;
  const { PageHead } = window.RokkorScreens;
  const { Section, Inset, Notice } = window.RokkorKit;
  const I = window.RokkorIcons;
  const [engine, setEngine] = React.useState("elite");

  // Bench chip row
  const Bench = ({ measured, items, sub }) => (
    <Inset style={{ marginTop: 14 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, font: "600 13px/1 var(--font-sans)", color: "var(--ink-900)", marginBottom: 10 }}><I.Chart size={15} /> Benchmarks</div>
      {items ? (
        <>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
            <Badge tone={measured ? "success" : "neutral"} dot={measured}>{measured ? "Measured here" : "Cited"}</Badge>
            {items.map(([k, v]) => (
              <span key={k} style={{ font: "12px/1 var(--font-mono)", color: "var(--ink-700, var(--ink-800))", background: "var(--paper-200)", border: "1px solid var(--border)", borderRadius: "var(--radius-sm)", padding: "5px 9px" }}>{k} <b>{v}</b></span>
            ))}
          </div>
          {sub ? <div style={{ font: "12px/1.4 var(--font-mono)", color: "var(--ink-500)", marginTop: 9 }}>{sub}</div> : null}
        </>
      ) : (
        <div style={{ display: "flex", alignItems: "center", gap: 7, font: "400 12.5px/1.4 var(--font-sans)", color: "var(--ink-500)" }}><I.Help size={14} /> Not benchmarked here yet — run the benchmark to get a measured number.</div>
      )}
    </Inset>
  );

  // Grammar model card
  const GModel = ({ name, badge, badgeTone, size, accel, file, path, note, action, best, bench }) => (
    <Inset style={{ padding: "18px 20px" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
            <span style={{ font: "600 16px/1.3 var(--font-sans)", color: "var(--ink-900)" }}>{name}</span>
            {badge ? <Badge tone={badgeTone || "success"} dot>{badge}</Badge> : null}
          </div>
          {best ? <div style={{ marginTop: 8 }}><Badge tone="gold"><span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><I.Sparkle size={12} /> {best}</span></Badge></div> : null}
          <div style={{ font: "12px/1.4 var(--font-mono)", color: "var(--ink-500)", marginTop: 9 }}>{size} &nbsp; {accel} &nbsp; {file}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 6, font: "11.5px/1.4 var(--font-mono)", color: "var(--ink-500)", marginTop: 6 }}><I.Folder size={13} /> {path}</div>
          {note ? <div style={{ font: "400 12.5px/1.5 var(--font-sans)", color: "var(--ink-500)", marginTop: 8 }}>{note}</div> : null}
          {bench}
        </div>
        <div style={{ display: "flex", gap: 8, flex: "none" }}>{action}</div>
      </div>
    </Inset>
  );

  return (
    <div style={{ maxWidth: "var(--content-max)" }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
        <PageHead title="Models" subtitle="Local transcription and grammar model catalogs." />
        <div style={{ marginTop: 30 }}><Button variant="outline" icon={<I.Refresh size={15} />}>Refresh</Button></div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
        {/* TRANSCRIPTION ENGINE */}
        <Section icon={I.Cpu} title="Transcription Engine" desc="Active model choice is persisted locally.">
          <Inset>
            <div style={{ display: "flex", alignItems: "center", gap: 8, font: "600 13px/1 var(--font-sans)", color: "var(--ink-900)", marginBottom: 10 }}><I.Cpu size={15} /> Detected hardware</div>
            <div style={{ font: "12.5px/1.7 var(--font-mono)", color: "var(--ink-600)" }}>
              GPU: NVIDIA GeForce RTX 3090 · 24 GB<br />
              CPU: 16 cores · x86_64<br />
              STT engine · EP requested: cpu (compiled: cpu) — falls back to CPU if it can't bind
            </div>
          </Inset>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 14 }}>
            {[["standard", "Standard", "English only — fastest, on-device (Parakeet-v3)"], ["elite", "Elite", "14 languages, fully offline — higher accuracy, GPU (Nemotron)"]].map(([id, title, desc]) => {
              const sel = engine === id;
              return (
                <button key={id} onClick={() => setEngine(id)} style={{ textAlign: "left", cursor: "pointer", padding: "16px 18px", borderRadius: "var(--radius-lg)", border: `1px solid ${sel ? "var(--oxblood-500)" : "var(--border)"}`, background: sel ? "var(--oxblood-100)" : "var(--paper-50)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                    <span style={{ width: 16, height: 16, borderRadius: "50%", border: `2px solid ${sel ? "var(--oxblood-600)" : "var(--ink-400)"}`, display: "flex", alignItems: "center", justifyContent: "center" }}>{sel ? <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--oxblood-600)" }} /> : null}</span>
                    <span style={{ font: "600 15px/1 var(--font-sans)", color: "var(--ink-900)" }}>{title}</span>
                  </div>
                  <div style={{ font: "400 13px/1.4 var(--font-sans)", color: "var(--ink-600)", marginTop: 8 }}>{desc}</div>
                </button>
              );
            })}
          </div>
          <div style={{ font: "400 13px/1.5 var(--font-sans)", color: "var(--oxblood-600)", marginTop: 14 }}>Elite needs the NeMo runtime — see <code>sidecar/elite_streaming</code> setup.</div>
          <div style={{ font: "400 13px/1.5 var(--font-sans)", color: "var(--ink-500)", marginTop: 10 }}>English: Standard or Elite. 13 other languages: Elite engine only.</div>
          <div style={{ font: "400 13px/1 var(--font-sans)", color: "var(--ink-600)", marginTop: 14 }}>▸ Advanced — sidecar details</div>
          <div style={{ font: "400 13px/1 var(--font-sans)", color: "var(--ink-500)", margin: "16px 0 10px" }}>Standard model choice — active when Engine = Standard</div>
          <GModel
            name="Parakeet V3 (int8) - Recommended fast/accurate" badge="Active" badgeTone="info"
            size="480 MB" accel="cpu/metal" file="directory parakeet-v3-int8"
            path="C:\\Users\\ProfessorX\\AppData\\Local\\ROKKOR\\models\\parakeet-v3-int8"
            note="Required: encoder-model.int8.onnx, decoder_joint-model.int8.onnx, nemo128.onnx, vocab.txt"
            action={<><Button variant="outline" size="sm">Selected</Button><Button variant="ghost" size="sm" icon={<I.Download size={14} />}>Ready</Button></>}
            bench={<Bench measured items={[["WER", "0.026"], ["RTFx", "8.05x"]]} sub={"N = 300   librispeech_test_clean   2026-06-05   RTX 3090 24GB; DirectML EP   accel: directml"} />}
          />
          <div style={{ marginTop: 12 }}><Button variant="outline" size="sm" icon={<I.Chart size={15} />}>Run benchmark</Button></div>
        </Section>

        {/* GRAMMAR / STYLE MODEL */}
        <Section icon={I.Cpu} title="Grammar / Style Model" desc="Catalog grammar models are downloaded and registered with the local Ollama backend, then used for real LLM grammar (low-latency GPU path).">
          <Notice tone="info" style={{ marginBottom: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, font: "600 14px/1.3 var(--font-sans)", marginBottom: 6 }}><I.Check size={15} /> rokkor-catalog-grmr-v3-llama3-2-3b-q4-k-m (Ollama, active)</div>
            The active grammar model runs on the live Ollama backend (GPU, low latency). Selecting a catalog <code>.gguf</code> entry below downloads it and registers it with Ollama (under a derived tag) before switching — it does not fall back to rules.
          </Notice>

          {/* Personal grammar corpus */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "8px 0 12px" }}>
            <span style={{ display: "flex", alignItems: "center", gap: 8, font: "600 16px/1 var(--font-sans)", color: "var(--ink-900)" }}><I.Sparkle size={16} /> Personal grammar corpus</span>
            <Button variant="outline" size="sm" icon={<I.Refresh size={14} />}>Force refresh</Button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
            {[["1,860", "Training pairs"], ["342", "Corrections"], ["6/14/2026", "Last refresh"]].map(([v, l]) => (
              <Inset key={l} style={{ textAlign: "center", padding: "18px 14px" }}><div style={{ font: "600 28px/1 var(--font-serif)", color: "var(--ink-900)" }}>{v}</div><div style={{ font: "400 12.5px/1.3 var(--font-sans)", color: "var(--ink-500)", marginTop: 8 }}>{l}</div></Inset>
            ))}
          </div>
          <div style={{ display: "flex", gap: 7, font: "400 12.5px/1.5 var(--font-sans)", color: "var(--ink-500)", marginTop: 12 }}><I.Help size={14} /> <span><b>Force refresh</b> rebuilds the <code>rokkor-grammar</code> model from your corrections so punctuation, capitalization and word fixes match your voice over time. It takes roughly 40-90 minutes on a capable GPU and runs in the background. This improves GRAMMAR / post-processing only — it does <b>not</b> retrain the acoustic speech-to-text model.</span></div>

          {/* Version history */}
          <div style={{ display: "flex", alignItems: "center", gap: 8, font: "600 16px/1 var(--font-sans)", color: "var(--ink-900)", margin: "22px 0 12px" }}><I.Clock size={16} /> Version history</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {[
              ["rokkor-grammar v3", true, "Jun 14, 2026, 01:08 AM   1,860 pairs   342 corrections   trained on your corpus"],
              ["rokkor-grammar v2", false, "May 2, 2026, 11:42 PM   1,124 pairs   233 corrections"],
              ["rokkor-grammar v1", false, "Mar 18, 2026, 09:15 PM   486 pairs   97 corrections"],
              ["base", false, "Feb 9, 2026, 08:33 AM   0 pairs   0 corrections   factory base (no personal training)"],
            ].map(([name, active, meta], i) => (
              <Inset key={i}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
                  <div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}><span style={{ font: "600 14px/1 var(--font-mono)", color: "var(--ink-900)" }}>{name}</span>{active ? <Badge tone="info" dot>Active</Badge> : null}</div>
                    <div style={{ font: "12px/1.4 var(--font-mono)", color: "var(--ink-500)", marginTop: 7 }}>{meta}</div>
                  </div>
                  <Button variant="outline" size="sm" icon={<I.Refresh size={14} />} disabled={active}>{active ? "Active" : "Revert"}</Button>
                </div>
              </Inset>
            ))}
          </div>
          <Notice tone="danger" style={{ marginTop: 14, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
            <span><b style={{ color: "var(--oxblood-700)", display: "block", marginBottom: 3 }}>Revert to factory model</b>Remove my training and restore the original untrained grammar model.</span>
            <span style={{ flex: "none" }}><Button variant="outline" size="sm" icon={<I.Refresh size={14} />}>Revert to factory model</Button></span>
          </Notice>

          {/* Catalog grammar models */}
          <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 18 }}>
            <GModel name="FlowScribe Qwen2.5 0.5B (Q4_K_M) - fast default grammar" badge="Ready" size="420 MB" accel="cpu/metal/vulkan" file="file flowscribe-qwen2.5-0.5b-v2-Q4_K_M.gguf" path="C:\\Users\\ProfessorX\\AppData\\Local\\ROKKOR\\models\\flowscribe-qwen2.5-0.5b-v2-Q4_K_M.gguf" note={'"Use" downloads this model and registers it with the local Ollama backend for real LLM grammar (requires the Ollama backend running).'} action={<><Button variant="outline" size="sm">Use</Button><Button variant="ghost" size="sm" icon={<I.Download size={14} />}>Ready</Button></>} bench={<Bench measured items={[["GLEU", "0.613"], ["Latency (warm)", "178 ms"]]} sub="N = 100   jfleg_dev_100   2026-06-05" />} />
            <GModel name="GRMR V3 Llama 3.2 3B (Q4_K_M) - high quality, high VRAM" badge="Active" badgeTone="info" best="Measured best (GLEU 0.732)" size="1900 MB" accel="cpu/metal/vulkan" file="file grmr-v3-llama3.2-3b-q4_k_m.gguf" path="C:\\Users\\ProfessorX\\AppData\\Local\\ROKKOR\\models\\grmr-v3-llama3.2-3b-q4_k_m.gguf" note="Highest measured grammar quality on this project's benchmark (GLEU 0.732). Selecting it routes through the local Ollama backend (GPU)." action={<><Button variant="outline" size="sm">Selected</Button><Button variant="ghost" size="sm" icon={<I.Download size={14} />}>Ready</Button></>} bench={<Bench measured items={[["GLEU", "0.732"], ["Latency (warm)", "274 ms"]]} sub="N = 100   jfleg_dev_100   2026-06-05" />} />
            <GModel name="Qwen3 1.7B (Q4_K_M, no-think) - multilingual grammar default" badge="Ready" size="1056 MB" accel="cpu/metal/vulkan" file="file qwen3-1.7b-instruct-q4_k_m.gguf" path="C:\\Users\\ProfessorX\\AppData\\Local\\ROKKOR\\models\\qwen3-1.7b-instruct-q4_k_m.gguf" note={'"Use" downloads this model and registers it with the local Ollama backend for real LLM grammar (requires the Ollama backend running).'} action={<><Button variant="outline" size="sm">Use</Button><Button variant="ghost" size="sm" icon={<I.Download size={14} />}>Ready</Button></>} bench={<Bench />} />
            <GModel name="Gemma 3 4B-it (Q4_K_M) - CJK grammar (ja); Gemma license" badge="Ready" size="2375 MB" accel="cpu/metal/vulkan" file="file gemma-3-4b-it-q4_k_m.gguf" path="C:\\Users\\ProfessorX\\AppData\\Local\\ROKKOR\\models\\gemma-3-4b-it-q4_k_m.gguf" note={'"Use" downloads this model and registers it with the local Ollama backend for real LLM grammar (requires the Ollama backend running).'} action={<><Button variant="outline" size="sm">Use</Button><Button variant="ghost" size="sm" icon={<I.Download size={14} />}>Ready</Button></>} bench={<Bench />} />
            <GModel name="IBM Granite 3.3 2B Instruct (Q4_K_M) - grammar/style" badge="Ready" size="1473 MB" accel="cpu/metal/vulkan" file="file granite-3.3-2b-instruct-q4_k_m.gguf" path="C:\\Users\\ProfessorX\\AppData\\Local\\ROKKOR\\models\\granite-3.3-2b-instruct-q4_k_m.gguf" note={'"Use" downloads this model and registers it with the local Ollama backend for real LLM grammar (requires the Ollama backend running).'} action={<><Button variant="outline" size="sm">Use</Button><Button variant="ghost" size="sm" icon={<I.Download size={14} />}>Ready</Button></>} bench={<Bench />} />
          </div>
        </Section>

        {/* VOICE ACTIVITY (VAD) */}
        <Section icon={I.Cpu} title="Voice Activity (VAD)" desc="Optional helper model for trimming leading/trailing silence before transcription (faster decode, fewer hallucinated tokens on silence). Enable the trim under Settings → Trim silence before transcription after downloading.">
          <GModel name="Silero VAD v4 - silence trimming (optional)" badge="Ready" size="2 MB" accel="cpu" file="file silero_vad_v4.onnx" path="C:\\Users\\ProfessorX\\AppData\\Local\\ROKKOR\\models\\silero_vad_v4.onnx" note='Helper model only — there is no "active" selection here. Turn on silence trimming under Settings once this is downloaded.' action={<Button variant="ghost" size="sm" icon={<I.Download size={14} />}>Ready</Button>} />
        </Section>
      </div>
    </div>
  );
}

window.RokkorScreens = Object.assign(window.RokkorScreens || {}, { ModelsScreen });
