/* ============================================
   DOCUMENT INSPECTOR — 3-panel debug view
   Text chunks · Markdown tables · AI image summaries
   ============================================ */
const INSPECTOR_CHUNKS = [
  { id: "chk_8f3a92ce", section: "§4.2 Spindle Bearing Replacement", page: 142, tokens: 412, similarity: 0.913, text: "For radial runout exceeding 10 µm at the spindle nose under 1,500 RPM no-load condition, perform bearing replacement per §4.3. Verification must occur after spindle has equalized to ambient temperature (within 2°C) for a minimum of 4 hours following last operation. Use calibrated dial indicator with 0.5 µm resolution mounted to magnetic base on the tool turret. Record three readings 120° apart and report the maximum value." },
  { id: "chk_4d1a07b2", section: "§4.3 Tolerance specifications", page: 145, tokens: 286, similarity: 0.871, text: "Front bearing pair: NSK 7014CTYNDULP4 (back-to-back DB configuration). Apply preload of 280 ± 15 N via lock nut torqued to 42 N·m. Use calibrated dial gauge to confirm bearing seat before final torque application. Rear bearing: 7012CTYNDULP4 (tandem DT) with 200 ± 10 N preload at 38 N·m." },
  { id: "chk_e92c1844", section: "§4.3.1 Torque specifications", page: 146, tokens: 198, similarity: 0.802, text: "Lock nut torque: 42 N·m ± 2 N·m. Always apply torque in three increments: 50%, 75%, 100% of final value with 30 second hold at each step. Final value to be confirmed by witness signature in the work order." },
  { id: "chk_771b03fa", section: "§4.4 Run-in procedure", page: 148, tokens: 524, similarity: 0.764, text: "Post-installation run-in: 1,000 RPM for 20 minutes, then 3,000 RPM for 20 minutes, then 6,000 RPM for 20 minutes. Monitor temperature at front and rear bearing housings — must not exceed 55°C above ambient. Vibration RMS must stabilize below 1.4 mm/s within first 10 minutes at each step." },
];

const INSPECTOR_TABLES = [
  {
    id: "tbl_a4f1",
    title: "Table 4-3 · Bearing Preload Specifications",
    page: 145,
    cols: ["Position", "Part Number", "Configuration", "Preload (N)", "Torque (N·m)"],
    rows: [
      ["Front", "NSK 7014CTYNDULP4", "DF (back-to-back)", "280 ± 15", "42"],
      ["Rear", "NSK 7012CTYNDULP4", "DT (tandem)", "200 ± 10", "38"],
      ["Thrust", "NSK 51112-P4", "Single", "150 ± 8", "28"],
    ],
  },
  {
    id: "tbl_b1e2",
    title: "Table 4-4 · Run-in Schedule",
    page: 148,
    cols: ["Stage", "RPM", "Duration (min)", "Max Temp (°C)", "Max Vib (mm/s)"],
    rows: [
      ["1", "1,000", "20", "55", "1.4"],
      ["2", "3,000", "20", "55", "1.4"],
      ["3", "6,000", "20", "55", "1.4"],
    ],
  },
];

const INSPECTOR_IMAGES = [
  {
    id: "img_p142_01",
    page: 142,
    caption: "Spindle assembly exploded view",
    summary: "Exploded technical illustration of the INTEGREX i400 spindle assembly. Shows the main shaft (center), front bearing pair in DF back-to-back configuration (labeled A), rear bearing in DT tandem configuration (labeled B), and the lock nut on the right end (labeled C). Three callout labels reference the torque specification of 42 N·m on the lock nut. Scale bar indicates 50 mm reference.",
    tokens: 82,
    confidence: 0.94,
  },
  {
    id: "img_p145_02",
    page: 145,
    caption: "Bearing preload measurement setup",
    summary: "Photograph of a dial indicator mounted to a magnetic base on the tool turret, with the probe contacting the spindle nose. The indicator shows a reading near zero on a 0.5 µm resolution scale. Background shows the spindle housing and the front bearing cover with M6 socket head cap screws visible.",
    tokens: 64,
    confidence: 0.88,
  },
  {
    id: "img_p148_03",
    page: 148,
    caption: "Vibration & temperature monitoring during run-in",
    summary: "Chart from the maintenance manual showing expected vibration RMS (mm/s) and bearing housing temperature (°C above ambient) trajectories during the 60-minute run-in procedure. Three step changes correspond to the 1,000 / 3,000 / 6,000 RPM stages. Acceptance bands shaded.",
    tokens: 71,
    confidence: 0.91,
  },
];

function InspectorScreen({ onNavigate }) {
  const [tab, setTab] = useState("chunks");
  const [activeChunk, setActiveChunk] = useState(0);
  const [activeImg, setActiveImg] = useState(0);

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Document Inspector</h1>
          <p className="page-subtitle">
            <span className="mono" style={{ color: "var(--navy-700)", fontWeight: 600 }}>DOC-CNC-204</span>
            <span className="muted"> · CNC-Mazak-INTEGREX-i400 — Maintenance v7.2 · indexed 2026-03-04</span>
          </p>
        </div>
        <div className="row">
          <button className="btn btn--ghost"><Icons.Download size={14} /> Source PDF</button>
          <button className="btn btn--ghost"><Icons.Refresh size={14} /> Re-process</button>
          <button className="btn btn--secondary" onClick={() => onNavigate("knowledge")}>Back to manuals</button>
        </div>
      </div>

      {/* Document summary strip */}
      <Card bodyFlush style={{ marginBottom: 16 }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)" }}>
          <Stat label="Pages" value="312" sub="OCR clean: 308/312" />
          <Stat label="Text Chunks" value="1,842" sub="avg 384 tokens" />
          <Stat label="Tables" value="47" sub="2 require review" />
          <Stat label="Images" value="218" sub="AI-summarized 218/218" />
          <Stat label="Embedding model" value="emb-3-lg" sub="dim 1536" />
          <Stat label="Pipeline cost" value="$3.42" sub="one-time" accent="var(--orange-600)" />
        </div>
      </Card>

      {/* Tabs */}
      <Card bodyFlush>
        <div style={{ padding: "0 16px", borderBottom: "1px solid var(--ink-200)", display: "flex", gap: 4 }}>
          {[
            { k: "chunks", label: "Text Chunks", icon: <Icons.File size={14} />, count: INSPECTOR_CHUNKS.length },
            { k: "tables", label: "Markdown Tables", icon: <Icons.Database size={14} />, count: INSPECTOR_TABLES.length },
            { k: "images", label: "AI Image Summaries", icon: <Icons.Image size={14} />, count: INSPECTOR_IMAGES.length },
          ].map(t => (
            <button
              key={t.k}
              onClick={() => setTab(t.k)}
              style={{
                background: "none", border: "none", padding: "12px 14px",
                color: tab === t.k ? "var(--orange-700)" : "var(--ink-600)",
                fontWeight: 600, fontSize: 13,
                cursor: "pointer",
                borderBottom: tab === t.k ? "2px solid var(--orange-500)" : "2px solid transparent",
                marginBottom: -1,
                display: "flex", gap: 6, alignItems: "center",
              }}
            >
              {t.icon}{t.label}
              <span className="badge badge--neutral" style={{ fontSize: 10.5 }}>{t.count}</span>
            </button>
          ))}
        </div>

        {/* CHUNKS */}
        {tab === "chunks" && (
          <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", minHeight: 480 }}>
            {/* Nested list */}
            <div style={{ borderRight: "1px solid var(--ink-200)", padding: 8, overflowY: "auto", maxHeight: 600 }}>
              {INSPECTOR_CHUNKS.map((c, i) => (
                <button
                  key={c.id}
                  onClick={() => setActiveChunk(i)}
                  style={{
                    width: "100%", textAlign: "left",
                    padding: "10px 12px",
                    border: "1px solid",
                    borderColor: i === activeChunk ? "var(--orange-500)" : "transparent",
                    background: i === activeChunk ? "var(--orange-50)" : "transparent",
                    borderRadius: 6,
                    cursor: "pointer",
                    marginBottom: 4,
                    display: "block",
                  }}
                >
                  <div className="row" style={{ marginBottom: 4 }}>
                    <span className="mono text-xs" style={{ color: i === activeChunk ? "var(--orange-700)" : "var(--ink-500)", fontWeight: 600 }}>{c.id}</span>
                    <span className="spacer" />
                    <span className="mono text-xs muted">p.{c.page}</span>
                  </div>
                  <div className="text-sm" style={{ fontWeight: 600, color: "var(--ink-900)", marginBottom: 2 }}>{c.section}</div>
                  <div className="row gap-6">
                    <span className="text-xs muted mono">{c.tokens} tok</span>
                    <span className="text-xs" style={{ color: "var(--status-ok)", fontFamily: "var(--font-mono)", fontWeight: 600 }}>· {c.similarity.toFixed(3)}</span>
                  </div>
                </button>
              ))}
            </div>

            <div style={{ padding: 22, overflowY: "auto" }}>
              {(() => {
                const c = INSPECTOR_CHUNKS[activeChunk];
                return (
                  <>
                    <div className="row" style={{ marginBottom: 14 }}>
                      <div>
                        <div className="mono text-xs" style={{ color: "var(--orange-700)", fontWeight: 600, letterSpacing: "0.04em" }}>{c.id}</div>
                        <h3 style={{ margin: "4px 0 0", fontSize: 16, fontWeight: 600 }}>{c.section}</h3>
                      </div>
                      <span className="spacer" />
                      <Badge kind="blue">page {c.page}</Badge>
                      <Badge kind="neutral">{c.tokens} tokens</Badge>
                    </div>

                    <div style={{
                      padding: 16,
                      background: "var(--ink-50)",
                      border: "1px solid var(--ink-200)",
                      borderRadius: 6,
                      fontFamily: "var(--font-mono)",
                      fontSize: 12.5,
                      lineHeight: 1.7,
                      color: "var(--ink-800)",
                      whiteSpace: "pre-wrap",
                    }}>{c.text}</div>

                    <div className="grid-3" style={{ marginTop: 16, gap: 12 }}>
                      <MetaTile label="Embedding norm" value="1.000" mono />
                      <MetaTile label="Dimension" value="1536" mono />
                      <MetaTile label="Index shard" value="qdr-shard-04" mono />
                    </div>

                    <div style={{ marginTop: 16, padding: 12, border: "1px dashed var(--ink-300)", borderRadius: 6, background: "white" }}>
                      <div className="row gap-6" style={{ marginBottom: 8 }}>
                        <Icons.Pulse size={14} />
                        <span className="text-xs mono fw-600" style={{ color: "var(--ink-700)" }}>RAW EMBEDDING (first 12 of 1536)</span>
                      </div>
                      <div className="mono text-xs" style={{ color: "var(--ink-600)", wordBreak: "break-all" }}>
                        [-0.0142, 0.0331, -0.0218, 0.0094, 0.0561, -0.0073, 0.0244, -0.0156, 0.0382, 0.0119, -0.0497, 0.0204, …]
                      </div>
                    </div>
                  </>
                );
              })()}
            </div>
          </div>
        )}

        {/* TABLES */}
        {tab === "tables" && (
          <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 20 }}>
            {INSPECTOR_TABLES.map(t => (
              <div key={t.id}>
                <div className="row" style={{ marginBottom: 10 }}>
                  <div>
                    <div className="mono text-xs" style={{ color: "var(--orange-700)", fontWeight: 600 }}>{t.id}</div>
                    <h3 style={{ margin: "2px 0 0", fontSize: 15, fontWeight: 600 }}>{t.title}</h3>
                  </div>
                  <span className="spacer" />
                  <Badge kind="blue">page {t.page}</Badge>
                  <button className="btn btn--ghost btn--sm"><Icons.Download size={12} /> CSV</button>
                </div>
                <div style={{ border: "1px solid var(--ink-200)", borderRadius: 6, overflow: "hidden" }}>
                  <table className="table">
                    <thead>
                      <tr>{t.cols.map(c => <th key={c}>{c}</th>)}</tr>
                    </thead>
                    <tbody>
                      {t.rows.map((r, i) => (
                        <tr key={i}>{r.map((cell, j) => (
                          <td key={j} className={j > 0 ? "mono" : ""} style={j === 0 ? { fontWeight: 600 } : null}>{cell}</td>
                        ))}</tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* IMAGES */}
        {tab === "images" && (
          <div style={{ padding: 22, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
            {INSPECTOR_IMAGES.map((img, i) => (
              <div
                key={img.id}
                onClick={() => setActiveImg(i)}
                style={{
                  border: "1px solid",
                  borderColor: activeImg === i ? "var(--orange-500)" : "var(--ink-200)",
                  borderRadius: 6,
                  overflow: "hidden",
                  cursor: "pointer",
                  background: "white",
                }}
              >
                {/* thumbnail placeholder */}
                <div style={{
                  height: 140,
                  background: `repeating-linear-gradient(45deg, var(--ink-100), var(--ink-100) 8px, var(--ink-50) 8px, var(--ink-50) 16px)`,
                  display: "grid", placeItems: "center",
                  position: "relative",
                  borderBottom: "1px solid var(--ink-200)",
                }}>
                  <div style={{ background: "white", padding: "6px 12px", borderRadius: 4, border: "1px solid var(--ink-200)" }}>
                    <span className="mono text-xs" style={{ color: "var(--ink-500)" }}>FIG · p.{img.page}</span>
                  </div>
                  <div style={{ position: "absolute", top: 8, right: 8 }}>
                    <Badge kind="orange">{(img.confidence * 100).toFixed(0)}% conf</Badge>
                  </div>
                </div>
                <div style={{ padding: 12 }}>
                  <div className="mono text-xs" style={{ color: "var(--orange-700)", fontWeight: 600, marginBottom: 4 }}>{img.id}</div>
                  <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 6 }}>{img.caption}</div>
                  <div className="text-xs" style={{ color: "var(--ink-600)", lineHeight: 1.55, display: "-webkit-box", WebkitLineClamp: 4, WebkitBoxOrient: "vertical", overflow: "hidden" }}>
                    <span className="muted">AI summary: </span>{img.summary}
                  </div>
                  <div className="text-xs muted mono" style={{ marginTop: 6 }}>{img.tokens} tokens · vision-1.0</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>
    </>
  );
}

function MetaTile({ label, value, mono }) {
  return (
    <div style={{ padding: 10, border: "1px solid var(--ink-200)", borderRadius: 6, background: "white" }}>
      <div className="text-xs muted" style={{ marginBottom: 2 }}>{label}</div>
      <div className={mono ? "mono" : ""} style={{ fontSize: 13, fontWeight: 600 }}>{value}</div>
    </div>
  );
}

window.InspectorScreen = InspectorScreen;
