/* ============================================
   ANALYTICS & AUDIT — Query volume + user feedback
   ============================================ */
function AnalyticsScreen({ onNavigate }) {
  // 30-day query volume data
  const queryData = [
    142, 168, 154, 189, 203, 87, 92,
    218, 234, 261, 245, 278, 102, 118,
    289, 312, 298, 334, 356, 142, 156,
    378, 402, 421, 398, 442, 188, 201,
    458, 487,
  ];

  const max = Math.max(...queryData);
  const W = 800, H = 220, P = 30;
  const stepX = (W - P * 2) / (queryData.length - 1);
  const points = queryData.map((v, i) => `${P + i * stepX},${H - P - (v / max) * (H - P * 2)}`).join(" ");

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Analytics &amp; Audit</h1>
          <p className="page-subtitle">Last 30 days · 7,842 total queries · 96.3% citation-grounded</p>
        </div>
        <div className="row">
          <div className="row gap-4" style={{ background: "var(--ink-100)", padding: 2, borderRadius: 6 }}>
            {["7d", "30d", "90d", "12m"].map(p => (
              <button key={p} style={{
                border: "none", background: p === "30d" ? "white" : "transparent",
                color: p === "30d" ? "var(--ink-900)" : "var(--ink-500)",
                padding: "5px 10px", borderRadius: 4, fontSize: 12, fontWeight: 600,
                boxShadow: p === "30d" ? "var(--shadow-sm)" : "none", cursor: "pointer",
              }}>{p}</button>
            ))}
          </div>
          <button className="btn btn--ghost"><Icons.Download size={14} /> Export audit log</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="grid-4" style={{ marginBottom: 16 }}>
        <StatCard label="Queries (30d)" value="7,842" sub="↑ 18% vs prev. period" icon={<Icons.Activity />} accent="var(--navy-700)" />
        <StatCard label="Unique users" value="184" sub="of 247 licensed seats" icon={<Icons.Users />} />
        <StatCard label="Median latency" value="1.18 s" sub="P95: 2.94 s" icon={<Icons.Pulse />} />
        <StatCard label="Citation rate" value="96.3%" sub="↑ 1.2 pts" icon={<Icons.Check />} accent="var(--status-ok)" />
      </div>

      {/* Query Volume chart */}
      <Card title="Query Volume" subtitle="Daily queries — last 30 days" right={
        <div className="row gap-8">
          <span className="row gap-4 text-xs muted"><span style={{ width: 10, height: 2, background: "var(--orange-500)" }}></span> Queries</span>
          <span className="row gap-4 text-xs muted"><span style={{ width: 10, height: 2, background: "var(--navy-500)", borderTop: "1px dashed var(--navy-500)" }}></span> 7d avg</span>
        </div>
      }>
        <div style={{ width: "100%", overflowX: "auto" }}>
          <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", minWidth: 600 }}>
            {/* gridlines */}
            {[0.25, 0.5, 0.75, 1].map(t => (
              <g key={t}>
                <line x1={P} y1={H - P - t * (H - P * 2)} x2={W - P} y2={H - P - t * (H - P * 2)} stroke="#EFF1F5" strokeWidth="1"/>
                <text x={P - 6} y={H - P - t * (H - P * 2) + 3} fontSize="9" fontFamily="IBM Plex Mono" fill="#98A2B3" textAnchor="end">{Math.round(max * t)}</text>
              </g>
            ))}
            {/* x axis labels */}
            {[0, 7, 14, 21, 28].map(i => (
              <text key={i} x={P + i * stepX} y={H - P + 14} fontSize="9" fontFamily="IBM Plex Mono" fill="#98A2B3" textAnchor="middle">D-{29 - i}</text>
            ))}
            {/* Area fill */}
            <polygon
              points={`${P},${H - P} ${points} ${W - P},${H - P}`}
              fill="url(#orangeGrad)"
              opacity="0.18"
            />
            <defs>
              <linearGradient id="orangeGrad" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor="#F26419"/>
                <stop offset="100%" stopColor="#F26419" stopOpacity="0"/>
              </linearGradient>
            </defs>
            {/* line */}
            <polyline points={points} fill="none" stroke="#F26419" strokeWidth="2" strokeLinejoin="round"/>
            {/* points */}
            {queryData.map((v, i) => (
              <circle key={i} cx={P + i * stepX} cy={H - P - (v / max) * (H - P * 2)} r={i === queryData.length - 1 ? 4 : 2} fill={i === queryData.length - 1 ? "#F26419" : "white"} stroke="#F26419" strokeWidth="1.5"/>
            ))}
            {/* Last value label */}
            <g transform={`translate(${P + (queryData.length - 1) * stepX - 50}, ${H - P - (queryData[queryData.length - 1] / max) * (H - P * 2) - 28})`}>
              <rect width="60" height="22" rx="3" fill="#0B2447"/>
              <text x="30" y="14" fontSize="11" fontFamily="IBM Plex Mono" fill="white" textAnchor="middle" fontWeight="700">{queryData[queryData.length - 1]}</text>
            </g>
          </svg>
        </div>
      </Card>

      <div className="grid-2" style={{ marginTop: 16 }}>
        {/* Top domains */}
        <Card title="Queries by Domain" subtitle="Last 30 days">
          {[
            { label: "CNC & Machining", v: 2810, pct: 35.8 },
            { label: "Electrical & PLC", v: 1820, pct: 23.2 },
            { label: "Hydraulics", v: 1124, pct: 14.3 },
            { label: "Safety & SOP", v: 892, pct: 11.4 },
            { label: "Pneumatics", v: 624, pct: 8.0 },
            { label: "Other", v: 572, pct: 7.3 },
          ].map(d => (
            <div key={d.label} style={{ marginBottom: 12 }}>
              <div className="row" style={{ marginBottom: 4 }}>
                <span className="text-sm" style={{ fontWeight: 600 }}>{d.label}</span>
                <span className="spacer" />
                <span className="text-xs muted mono">{d.v.toLocaleString()} · {d.pct}%</span>
              </div>
              <Progress value={d.pct * 2.5} kind={d.label.startsWith("CNC") ? undefined : "blue"} />
            </div>
          ))}
        </Card>

        {/* Top documents */}
        <Card title="Most Cited Documents" subtitle="Last 30 days">
          <table className="table">
            <thead>
              <tr><th>Document</th><th style={{ textAlign: "right" }}>Cites</th><th style={{ textAlign: "right" }}>Trend</th></tr>
            </thead>
            <tbody>
              {[
                ["CNC-Mazak-INTEGREX-i400 Maintenance", 1842, "↑ 12%"],
                ["Siemens S7-1500 PLC Programming", 1204, "↑ 8%"],
                ["Bosch Rexroth Hydraulic Systems Vol. III", 892, "→ 0%"],
                ["Plant Safety SOP — LOTO", 624, "↑ 22%"],
                ["ABB ACS580 VFD Programming", 412, "↓ 4%"],
              ].map(([n, c, t], i) => (
                <tr key={i}>
                  <td>
                    <div className="doc-name" style={{ fontSize: 12.5 }}>{n}</div>
                  </td>
                  <td className="mono" style={{ textAlign: "right", fontWeight: 600 }}>{c.toLocaleString()}</td>
                  <td className="mono text-xs" style={{ textAlign: "right", color: t.includes("↓") ? "var(--status-danger)" : t.includes("→") ? "var(--ink-500)" : "var(--status-ok)" }}>{t}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      {/* Feedback log */}
      <div style={{ marginTop: 16 }}>
        <Card title="User Feedback Log" subtitle="Real-time stream of thumbs up/down on AI responses" right={
          <div className="row">
            <span className="badge badge--complete"><span className="dot" />Helpful: 88.2%</span>
            <span className="badge badge--failed"><span className="dot" />Not helpful: 11.8%</span>
          </div>
        } bodyFlush>
          <table className="table">
            <thead>
              <tr>
                <th style={{ width: 30 }}></th>
                <th style={{ width: 140 }}>Timestamp</th>
                <th style={{ width: 140 }}>User</th>
                <th>Query</th>
                <th>Cited Document</th>
                <th style={{ width: 80 }}>Latency</th>
              </tr>
            </thead>
            <tbody>
              {[
                { up: true,  t: "14:23:18", u: "r.pratama", q: "Spindle bearing replacement on INTEGREX i400", doc: "DOC-CNC-204", lat: "1.04 s" },
                { up: true,  t: "14:20:02", u: "a.santoso", q: "PLC error E-741 on conveyor line 7", doc: "DOC-ELEC-091", lat: "0.92 s" },
                { up: false, t: "14:17:55", u: "m.indrawan", q: "How long does hydraulic seal Q-712 take to replace?", doc: "DOC-HYD-018", lat: "1.41 s" },
                { up: true,  t: "14:14:31", u: "s.permana", q: "VFD parameter set for ACS580 starter", doc: "DOC-ELEC-092", lat: "1.18 s" },
                { up: true,  t: "14:11:08", u: "r.pratama", q: "Coolant concentration for tool steel grades", doc: "DOC-LUBE-007", lat: "0.84 s" },
                { up: false, t: "14:08:42", u: "h.wijaya", q: "Welding rod humidity storage spec for E7018", doc: "DOC-WELD-006", lat: "2.21 s" },
                { up: true,  t: "14:05:11", u: "a.santoso", q: "LOTO procedure for grinding station 2", doc: "DOC-SAFETY-018", lat: "1.02 s" },
              ].map((f, i) => (
                <tr key={i}>
                  <td>
                    {f.up
                      ? <span style={{ color: "var(--status-ok)" }}><Icons.ThumbsUp size={16} /></span>
                      : <span style={{ color: "var(--status-danger)" }}><Icons.ThumbsDown size={16} /></span>}
                  </td>
                  <td className="mono text-xs muted">{f.t}</td>
                  <td className="mono text-xs">{f.u}</td>
                  <td style={{ fontSize: 13 }}>{f.q}</td>
                  <td><span className="mono text-xs" style={{ color: "var(--orange-700)", fontWeight: 600 }}>{f.doc}</span></td>
                  <td className="mono text-xs">{f.lat}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    </>
  );
}

window.AnalyticsScreen = AnalyticsScreen;
