/* global React, Icon */

// ─── S20 Conversation History ─────────────────────────
function S20_ConversationHistory() {
  const projects = [
    { path: "/Users/jay/projects/ccm-web", name: "ccm-web", count: 142, hasT: 98 },
    { path: "/Users/jay/projects/atlas-api", name: "atlas-api", count: 87, hasT: 51, active: true },
    { path: "/Users/jay/projects/marketing-site", name: "marketing-site", count: 38, hasT: 18 },
    { path: "/Users/jay/projects/design-tokens", name: "design-tokens", count: 24, hasT: 24 },
    { path: "/Users/jay/dotfiles", name: "dotfiles", count: 12, hasT: 4 },
    { path: "(other · 14 projects)", name: "other", count: 9769, hasT: 4095 },
  ];

  const entries = [
    { id: "a1", display: "fix the SSE backpressure issue when client lags behind", t: "14:42", date: "today", branch: "feat/replay", model: "sonnet-4-5", msgs: 18, dur: "01:14:08", tokens: "42k", tools: ["Bash","Read","Edit","Grep"], reply: "I'll trace the SSE handler. Looks like buffer fills when client poll delay > 200ms. Let me check the…", hasT: true, paste: false, branch_active: true },
    { id: "a2", display: "[Pasted text #1 +47 lines] · review this stream handler", t: "14:18", date: "today", branch: "feat/replay", model: "sonnet-4-5", msgs: 6, dur: "00:08:42", tokens: "12k", tools: ["Read"], reply: "A few concerns: 1) The Promise.all on line 23 doesn't propagate cancellation. 2) backpressure check…", hasT: true, paste: true, paste_lines: 47, paste_preview: "import { Hono } from 'hono'\nimport { stream } from 'hono/streaming'\nimport { randomUUID } from 'crypto'\n\nexport const app = new Hono()\n\napp.get('/events', async (c) => {\n  return stream(c, async (s) => {\n    const id = randomUUID()" },
    { id: "a3", display: "/model claude-opus-4-1", t: "13:42", date: "today", slash: true, hasT: true },
    { id: "a4", display: "implement the timeline replay route with scrubber primitive", t: "13:02", date: "today", branch: "feat/replay", model: "sonnet-4-5", msgs: 24, dur: "01:48:11", tokens: "82k", tools: ["Bash","Read","Edit","Write","Glob","Task"], reply: "Plan: 1. Scaffold /sessions/[id]/replay route 2. Extract Scrubber primitive 3. Wire SSE…", hasT: true, paste: false, active: true },
    { id: "a5", display: "/clear", t: "12:58", date: "today", slash: true, hasT: true },
    { id: "a6", display: "why is the cumulative-tokens chart re-rendering on every event?", t: "12:11", date: "today", branch: "feat/replay", model: "sonnet-4-5", msgs: 8, dur: "00:14:22", tokens: "18k", tools: ["Read","Grep"], reply: "The chart subscribes to the entire events array. Each new event mutates parent state, which trickles…", hasT: true, paste: false },
    { id: "a7", display: "[Pasted text #1 +12 lines] [Pasted text #2 +88 lines] · debug this drizzle migration error", t: "11:38", date: "today", branch: "main", model: "sonnet-4-5", msgs: 14, dur: "00:42:18", tokens: "31k", tools: ["Bash","Read","Edit"], reply: "The error is in your foreign-key constraint. Drizzle is trying to add the FK before the referenced…", hasT: true, paste: true, paste_lines: 100, paste_preview: "Error: relation \"sessions\" does not exist\n  at /Users/jay/projects/atlas-api/node_modules/postgres…" },
    { id: "a8", display: "add a 'critical' tier flag to hook_instances and update the installer to refuse removal of critical hooks unless --force", t: "10:24", date: "today", branch: "main", model: "sonnet-4-5", msgs: 11, dur: "00:32:08", tokens: "24k", tools: ["Read","Edit","Bash"], reply: "Done. Added the column with a check constraint, updated the installer in 3 places, and added a test…", hasT: false, paste: false },
    { id: "a9", display: "what's the fastest way to vacuum old events from sqlite without locking the table?", t: "Yesterday 18:42", date: "yesterday", branch: "main", model: "sonnet-4-5", msgs: 4, dur: "00:06:11", tokens: "8k", tools: ["WebFetch"], reply: "SQLite doesn't support online vacuum without a full table lock. Two options that avoid blocking…", hasT: true, paste: false },
    { id: "a10", display: "/help", t: "Yesterday 16:18", date: "yesterday", slash: true, hasT: true },
  ];

  const sel = entries[1];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="crumbs">workspace / <span>history</span></div>
          <h1>Conversation history</h1>
          <p>10,072 prompts across 17 projects · 4,290 with transcript (57%) · loaded from <span className="mono" style={{ color: "var(--ink-1)" }}>~/.claude/history.jsonl</span></p>
        </div>
        <div className="actions">
          <button className="btn"><Icon name="filter" size={12}/> Filter</button>
          <button className="btn"><Icon name="download" size={12}/> Export</button>
          <button className="btn primary"><Icon name="bookmark" size={12}/> Save query</button>
        </div>
      </div>

      {/* Stat strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 10, marginBottom: 14 }}>
        <div className="stat"><div className="stat-label">Total prompts</div><div className="stat-value">10,072</div><div className="stat-delta">since 2024-08-14</div></div>
        <div className="stat"><div className="stat-label">With transcript</div><div className="stat-value">4,290<span className="unit"> / 57%</span></div><div className="stat-delta">others expired</div></div>
        <div className="stat"><div className="stat-label">Tokens out</div><div className="stat-value">38.4<span className="unit">M</span></div><div className="stat-delta up">↑ 12% / 30d</div></div>
        <div className="stat"><div className="stat-label">Pasted blocks</div><div className="stat-value">2,184</div><div className="stat-delta">21.7% of entries</div></div>
        <div className="stat"><div className="stat-label">Slash commands</div><div className="stat-value">812</div><div className="stat-delta">/clear · /model · /help</div></div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "240px 1fr 380px", gap: 14 }}>
        {/* Project sidebar */}
        <div className="card">
          <div className="card-head"><h3>Projects</h3><span className="meta">17</span></div>
          <div className="card-body" style={{ padding: 0 }}>
            <div style={{ padding: "8px 10px", borderBottom: "1px solid var(--border-soft)" }}>
              <div className="input" style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <Icon name="search" size={11}/>
                <input placeholder="filter projects" style={{ background: "transparent", border: "none", outline: "none", color: "var(--ink-0)", fontSize: 12, flex: 1, fontFamily: "var(--font-mono)" }}/>
              </div>
            </div>
            <div style={{
              padding: "8px 12px",
              fontSize: 11, fontWeight: 500,
              background: !projects.find(p => p.active) ? "var(--bg-3)" : "transparent",
              borderLeft: !projects.find(p => p.active) ? "2px solid transparent" : "2px solid transparent",
              cursor: "pointer", display: "flex", justifyContent: "space-between"
            }}>
              <span>All projects</span>
              <span className="mono" style={{ color: "var(--ink-3)" }}>10,072</span>
            </div>
            {projects.map((p) => (
              <div key={p.path} style={{
                padding: "8px 12px",
                borderTop: "1px solid var(--border-soft)",
                background: p.active ? "var(--bg-3)" : "transparent",
                borderLeft: p.active ? "2px solid var(--accent)" : "2px solid transparent",
                cursor: "pointer"
              }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 6 }}>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 12, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
                    <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.path}</div>
                  </div>
                  <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-2)", whiteSpace: "nowrap" }}>{p.count.toLocaleString()}</span>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 6 }}>
                  <div className="bar" style={{ flex: 1, height: 3 }}>
                    <i style={{ width: `${(p.hasT / p.count) * 100}%`, background: "var(--ok)" }}/>
                  </div>
                  <span className="mono" style={{ fontSize: 9.5, color: "var(--ink-3)" }}>{p.hasT}t</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Entry list */}
        <div className="card">
          <div className="card-head" style={{ gap: 8 }}>
            <h3>Prompts · atlas-api <span className="pill"><span className="swatch"/>87</span></h3>
            <div style={{ flex: 1 }}/>
            <div className="input" style={{ display: "flex", alignItems: "center", gap: 6, padding: "4px 8px", minWidth: 220 }}>
              <Icon name="search" size={11}/>
              <input placeholder="search display + pasted contents" style={{ background: "transparent", border: "none", outline: "none", color: "var(--ink-0)", fontSize: 11.5, flex: 1, fontFamily: "var(--font-mono)" }}/>
              <span className="pill mono" style={{ fontSize: 9 }}>⌘K</span>
            </div>
            <div style={{ display: "flex", gap: 4 }}>
              <span className="pill accent"><span className="swatch"/>has transcript</span>
              <span className="pill"><span className="swatch"/>has paste</span>
              <span className="pill"><span className="swatch"/>slash</span>
            </div>
          </div>
          <div className="card-body" style={{ padding: 0, maxHeight: 600, overflow: "auto" }}>
            {/* Date header */}
            <div style={{ padding: "6px 14px", background: "var(--bg-1)", borderBottom: "1px solid var(--border-soft)", fontSize: 10, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-3)", fontFamily: "var(--font-mono)", position: "sticky", top: 0, zIndex: 1 }}>
              Today · 8 entries
            </div>
            {entries.filter(e => e.date === "today").map((e) => {
              const isSel = e.id === sel.id;
              return (
                <div key={e.id} style={{
                  padding: "10px 14px",
                  borderBottom: "1px solid var(--border-soft)",
                  background: isSel ? "var(--bg-3)" : (e.active ? "var(--accent-soft)" : "transparent"),
                  borderLeft: isSel ? "2px solid var(--accent)" : (e.active ? "2px solid var(--accent-line)" : "2px solid transparent"),
                  cursor: "pointer"
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                    <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)", minWidth: 42 }}>{e.t}</span>
                    {e.slash
                      ? <span className="pill"><span className="swatch"/>slash</span>
                      : e.hasT
                        ? <span className="pill ok"><span className="swatch"/>transcript</span>
                        : <span className="pill warn"><span className="swatch"/>expired</span>
                    }
                    {e.paste && <span className="pill accent"><Icon name="copy" size={9}/>+{e.paste_lines}L</span>}
                    {e.branch && <span className="pill mono"><Icon name="git" size={9}/>{e.branch}</span>}
                    {e.active && <span className="pill live"><span className="swatch"/>active</span>}
                    <div style={{ flex: 1 }}/>
                    {e.model && <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{e.model}</span>}
                  </div>
                  <div style={{
                    fontSize: e.slash ? 12 : 12.5,
                    fontFamily: e.slash ? "var(--font-mono)" : "var(--font-sans)",
                    color: e.slash ? "var(--accent)" : "var(--ink-0)",
                    fontWeight: e.slash ? 500 : 400,
                    lineHeight: 1.45,
                    marginBottom: e.hasT && !e.slash ? 6 : 0,
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    display: "-webkit-box",
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: "vertical"
                  }}>{e.display}</div>
                  {e.hasT && !e.slash && (
                    <div style={{ display: "flex", gap: 10, fontSize: 10.5, fontFamily: "var(--font-mono)", color: "var(--ink-3)", flexWrap: "wrap" }}>
                      <span>{e.msgs} msgs</span>
                      <span>{e.dur}</span>
                      <span>{e.tokens}</span>
                      {e.tools && <span style={{ display: "flex", gap: 3 }}>tools: {e.tools.slice(0, 3).map((t, i) => <span key={i} style={{ color: "var(--ink-2)" }}>{t}{i < Math.min(2, e.tools.length - 1) ? "·" : ""}</span>)}{e.tools.length > 3 && <span>+{e.tools.length - 3}</span>}</span>}
                    </div>
                  )}
                </div>
              );
            })}
            <div style={{ padding: "6px 14px", background: "var(--bg-1)", borderBottom: "1px solid var(--border-soft)", borderTop: "1px solid var(--border-soft)", fontSize: 10, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>
              Yesterday · 2 entries
            </div>
            {entries.filter(e => e.date === "yesterday").map((e) => (
              <div key={e.id} style={{ padding: "10px 14px", borderBottom: "1px solid var(--border-soft)", cursor: "pointer", borderLeft: "2px solid transparent" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                  <span className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)", minWidth: 88 }}>{e.t}</span>
                  {e.slash ? <span className="pill"><span className="swatch"/>slash</span> : <span className="pill ok"><span className="swatch"/>transcript</span>}
                  {e.branch && <span className="pill mono"><Icon name="git" size={9}/>{e.branch}</span>}
                  <div style={{ flex: 1 }}/>
                  {e.model && <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>{e.model}</span>}
                </div>
                <div style={{
                  fontSize: e.slash ? 12 : 12.5,
                  fontFamily: e.slash ? "var(--font-mono)" : "var(--font-sans)",
                  color: e.slash ? "var(--accent)" : "var(--ink-0)",
                  lineHeight: 1.45
                }}>{e.display}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Detail panel */}
        <div className="card">
          <div className="card-head" style={{ alignItems: "flex-start", flexDirection: "column", gap: 6 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6, width: "100%" }}>
              <h3 style={{ flex: 1 }}>Entry detail</h3>
              <button className="btn sm icon"><Icon name="ext" size={11}/></button>
              <button className="btn sm icon"><Icon name="copy" size={11}/></button>
            </div>
            <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)" }}>sessionId · 2c8f4a91-•••••</div>
          </div>
          <div className="card-body" style={{ padding: 0, maxHeight: 600, overflow: "auto" }}>
            {/* Meta grid */}
            <div style={{ padding: 14 }}>
              <dl className="kv">
                <dt>timestamp</dt><dd className="mono">{sel.t} · today</dd>
                <dt>project</dt><dd className="mono" style={{ fontSize: 10.5 }}>/Users/jay/projects/atlas-api</dd>
                <dt>branch</dt><dd><span className="pill mono"><Icon name="git" size={9}/>{sel.branch}</span></dd>
                <dt>model</dt><dd className="mono">{sel.model}</dd>
                <dt>messages</dt><dd className="mono">{sel.msgs} · {sel.dur}</dd>
                <dt>tokens out</dt><dd className="mono">{sel.tokens}</dd>
                <dt>tools used</dt>
                <dd style={{ display: "flex", flexWrap: "wrap", gap: 3 }}>
                  {sel.tools.map(t => <span key={t} className="pill mono" style={{ fontSize: 10 }}>{t}</span>)}
                </dd>
              </dl>
            </div>

            {/* Display */}
            <div style={{ padding: "12px 14px", borderTop: "1px solid var(--border-soft)" }}>
              <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-3)", marginBottom: 6 }}>display field</div>
              <div style={{ fontSize: 12, lineHeight: 1.5, color: "var(--ink-1)", padding: "8px 10px", background: "var(--bg-1)", border: "1px solid var(--border)", borderRadius: 4 }}>
                {sel.display}
              </div>
            </div>

            {/* Pasted contents */}
            {sel.paste && (
              <div style={{ padding: "12px 14px", borderTop: "1px solid var(--border-soft)" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
                  <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-3)" }}>pasted contents · #1</div>
                  <span className="pill"><span className="swatch"/>{sel.paste_lines} lines · text</span>
                </div>
                <div className="code" style={{ maxHeight: 140, overflow: "auto", fontSize: 10.5 }}>
                  {sel.paste_preview}
                </div>
                <button className="btn sm" style={{ width: "100%", marginTop: 6, justifyContent: "center" }}><Icon name="ext" size={11}/> View full · {sel.paste_lines} lines</button>
              </div>
            )}

            {/* First reply preview */}
            {sel.hasT && sel.reply && (
              <div style={{ padding: "12px 14px", borderTop: "1px solid var(--border-soft)" }}>
                <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-3)", marginBottom: 6 }}>first reply · 200 chars</div>
                <div style={{ fontSize: 11.5, lineHeight: 1.55, color: "var(--ink-1)", padding: "8px 10px", background: "var(--bg-1)", borderLeft: "2px solid var(--accent)", borderRadius: "0 3px 3px 0", fontStyle: "italic" }}>
                  {sel.reply}
                </div>
              </div>
            )}

            {/* Transcript path */}
            <div style={{ padding: "12px 14px", borderTop: "1px solid var(--border-soft)" }}>
              <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--ink-3)", marginBottom: 6 }}>transcript file</div>
              <div className="code" style={{ fontSize: 10, padding: "6px 8px" }}>
                ~/.claude/projects/-Users-jay-projects-atlas-api/2c8f4a91-•••••.jsonl
              </div>
              <div style={{ display: "flex", gap: 4, marginTop: 6 }}>
                <button className="btn sm" style={{ flex: 1, justifyContent: "center" }}><Icon name="play" size={10}/> Open replay</button>
                <button className="btn sm" style={{ flex: 1, justifyContent: "center" }}><Icon name="folder" size={10}/> Reveal</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.S20_ConversationHistory = S20_ConversationHistory;
