// OPT-QC-14 · QC pass/fail analytics
const QcAnalytics = ({ t, go }) => {
  const { Btn, Kpi } = window.Op;
  const Ic = window.Icons, QD = window.QD;
  const state = t.analytics; // default | sparse | loading
  const A = QD.ANALYTICS;
  const loading = state === "loading";
  const sparse = state === "sparse";

  // ── Line chart (pass rate over time) ──
  const LineChart = ({ data, w = 460, h = 150 }) => {
    const pad = { l: 30, r: 8, t: 10, b: 20 };
    const min = 60, max = 100;
    const px = (i) => pad.l + (i / (data.length - 1)) * (w - pad.l - pad.r);
    const py = (v) => pad.t + (1 - (v - min) / (max - min)) * (h - pad.t - pad.b);
    const line = data.map((v, i) => `${i === 0 ? "M" : "L"}${px(i)},${py(v)}`).join(" ");
    const area = `${line} L${px(data.length - 1)},${h - pad.b} L${px(0)},${h - pad.b} Z`;
    return (
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: "auto" }}>
        {[60, 70, 80, 90, 100].map(g => <g key={g}><line x1={pad.l} x2={w - pad.r} y1={py(g)} y2={py(g)} stroke="var(--border)" strokeWidth="1"/><text x={pad.l - 6} y={py(g) + 3} textAnchor="end" fontSize="9" fill="var(--muted-foreground)">{g}</text></g>)}
        <path d={area} fill="oklch(from var(--avocado) l c h / 0.12)"/>
        <path d={line} fill="none" stroke="var(--avocado)" strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round"/>
        {data.map((v, i) => <circle key={i} cx={px(i)} cy={py(v)} r="2.5" fill="var(--avocado)"/>)}
      </svg>
    );
  };

  // ── Vertical bars (pass by variety) ──
  const VarBars = ({ data, h = 150 }) => (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 14, height: h, padding: "0 4px" }}>
      {data.map(d => (
        <div key={d.name} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 6, height: "100%", justifyContent: "flex-end" }}>
          <div style={{ fontSize: 12, fontWeight: 700 }}>{d.pass}%</div>
          <div style={{ width: "100%", maxWidth: 46, height: `${(d.pass / 100) * (h - 44)}px`, borderRadius: "6px 6px 0 0", background: d.pass >= 85 ? "var(--avocado)" : d.pass >= 78 ? "oklch(0.62 0.13 130)" : "var(--status-pending)" }}/>
          <div style={{ fontSize: 11, color: "var(--muted-foreground)", fontWeight: 600 }}>{d.name}</div>
          <div style={{ fontSize: 9.5, color: "var(--muted-foreground)" }}>n={d.n}</div>
        </div>
      ))}
    </div>
  );

  // ── Horizontal bars (top suppliers) ──
  const SupplierBars = ({ data }) => (
    <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
      {data.map(d => (
        <div key={d.name} style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ fontSize: 11.5, width: 96, textAlign: "right", color: "var(--muted-foreground)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.name}</span>
          <div style={{ flex: 1, height: 18, borderRadius: 5, background: "var(--muted)", overflow: "hidden" }}>
            <div style={{ width: `${d.pass}%`, height: "100%", borderRadius: 5, background: d.pass >= 85 ? "var(--success)" : d.pass >= 70 ? "var(--status-pending)" : "var(--destructive)" }}/>
          </div>
          <span style={{ fontSize: 11.5, fontWeight: 700, width: 32, fontVariantNumeric: "tabular-nums" }}>{d.pass}%</span>
        </div>
      ))}
    </div>
  );

  // ── Histogram (fills available height) ──
  const Histogram = ({ data, labels, accentFrom }) => {
    const m = Math.max(...data);
    return (
      <div style={{ display: "flex", alignItems: "stretch", gap: 3, flex: 1, minHeight: 96 }}>
        {data.map((v, i) => (
          <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
            <div style={{ flex: 1, width: "100%", display: "flex", alignItems: "flex-end", justifyContent: "center" }}>
              <div style={{ width: "100%", height: `${(v / m) * 100}%`, minHeight: 2, borderRadius: "3px 3px 0 0", background: i >= accentFrom[0] && i <= accentFrom[1] ? "var(--avocado)" : "var(--muted-foreground)", opacity: i >= accentFrom[0] && i <= accentFrom[1] ? 1 : 0.4 }}/>
            </div>
            <div style={{ fontSize: 8.5, color: "var(--muted-foreground)" }}>{labels[i]}</div>
          </div>
        ))}
      </div>
    );
  };

  const ChartCard = ({ title, sub, children, span }) => (
    <div className="op-card op-card-pad" style={{ gridColumn: span ? `span ${span}` : "auto", display: "flex", flexDirection: "column" }}>
      <div style={{ marginBottom: 14 }}><div style={{ fontSize: 14, fontWeight: 600 }}>{title}</div>{sub && <div className="op-muted" style={{ fontSize: 12, marginTop: 1 }}>{sub}</div>}</div>
      {sparse ? <div style={{ flex: 1, minHeight: 120, borderRadius: 10, background: "var(--surface)", border: "1px dashed var(--border)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--muted-foreground)", fontSize: 12.5 }}>Not enough data for this range</div>
        : loading ? <div className="op-skel" style={{ flex: 1, minHeight: 120, borderRadius: 10 }}/>
        : <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>{children}</div>}
    </div>
  );

  const trendIcon = { up: <Ic.ArrowUp size={14} style={{ color: "var(--success)" }}/>, down: <Ic.ArrowDown size={14} style={{ color: "var(--destructive)" }}/>, flat: <Ic.ArrowRight size={14} style={{ color: "var(--muted-foreground)" }}/> };

  return (
    <div className="op-body">
      <div className="op-pad">
        <div className="op-sec" style={{ marginBottom: 14 }}>
          <div><div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-0.015em" }}>QC analytics</div><div className="op-muted" style={{ fontSize: 13, marginTop: 2 }}>Trends per supplier, variety & season</div></div>
          <div style={{ display: "flex", gap: 10 }}>
            <button className="op-chip"><Ic.Calendar size={15}/> Last 90 days <Ic.ChevronDown size={14}/></button>
            <Btn variant="outline" size="sm" icon={Ic.Download}>Export</Btn>
          </div>
        </div>

        {/* KPI strip */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 12, marginBottom: 16 }}>
          <Kpi label="Inspections" icon={Ic.ClipboardList} value={loading ? "—" : A.kpis.inspections}/>
          <Kpi label="Pass rate" icon={Ic.CheckCircle} value={loading ? "—" : A.kpis.passPct} unit="%"/>
          <Kpi label="Reject rate" icon={Ic.XCircle} value={loading ? "—" : A.kpis.rejectPct} unit="%" warn/>
          <Kpi label="Hold rate" icon={Ic.Clock} value={loading ? "—" : A.kpis.holdPct} unit="%"/>
          <Kpi label="Avg DM" icon={Ic.Thermometer} value={loading ? "—" : A.kpis.avgDM} unit="%"/>
          <Kpi label="Avg FFA" icon={Ic.Drop} value={loading ? "—" : A.kpis.avgFFA} unit="%"/>
        </div>

        {/* Charts */}
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16, marginBottom: 16, alignItems: "start" }}>
          <ChartCard title="Pass rate over time" sub="Weekly · last 12 weeks"><LineChart data={A.passOverTime}/></ChartCard>
          <ChartCard title="Pass rate by variety" sub="By variety · this season"><VarBars data={A.byVariety}/></ChartCard>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16, marginBottom: 16, alignItems: "stretch" }}>
          <ChartCard title="Top suppliers" sub="By pass rate"><SupplierBars data={A.topSuppliers}/></ChartCard>
          <ChartCard title="DM distribution" sub="Matrix accept range highlighted"><Histogram data={A.dmHist} labels={["18","19","20","21","22","23","24","25","26"]} accentFrom={[3, 7]}/></ChartCard>
          <ChartCard title="FFA distribution" sub="Premium / accept highlighted"><Histogram data={A.ffaHist} labels={["0.2","0.4","0.6","0.8","1.0","1.2","1.4"]} accentFrom={[0, 4]}/></ChartCard>
        </div>

        {/* Supplier ranking table */}
        {!loading && !sparse && (
          <div className="op-tbl-wrap">
            <table className="op-tbl">
              <thead><tr><th>Supplier</th><th>Inspections</th><th>Pass rate</th><th>Mean DM</th><th>Mean FFA</th><th>Trend</th></tr></thead>
              <tbody>
                {A.suppliers.map((s, i) => (
                  <tr key={i} onClick={() => go("history")}>
                    <td style={{ fontWeight: 600 }}>{s.name}</td>
                    <td className="num">{s.n}</td>
                    <td className="num"><span style={{ fontWeight: 700, color: s.pass >= 85 ? "var(--success)" : s.pass >= 70 ? "var(--foreground)" : "var(--destructive)" }}>{s.pass}%</span></td>
                    <td className="num">{s.dm}%</td>
                    <td className="num">{s.ffa}%</td>
                    <td style={{ display: "flex", alignItems: "center", gap: 6 }}>{trendIcon[s.trend]}<span style={{ fontSize: 12, color: "var(--muted-foreground)", textTransform: "capitalize" }}>{s.trend}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  analytics: { chrome: "tabs", tab: "Analytics", render: (ctx) => <QcAnalytics {...ctx}/> },
});
