// Analytics overview view — org-level KPIs, distributions, leaderboards.

function Sparkline({ data, color = "var(--fg)", fill = false, height = 36, width = 120 }) {
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const W = width, H = height;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * W;
    const y = H - 2 - ((v - min) / range) * (H - 6);
    return [x, y];
  });
  const d = pts.map((p, i) => (i === 0 ? "M" : "L") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  const area = fill ? `${d} L ${W} ${H} L 0 ${H} Z` : null;
  return (
    <svg width={W} height={H} style={{ display: "block" }}>
      {area && <path d={area} fill={color} opacity="0.12" />}
      <path d={d} stroke={color} strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="2" fill={color} />
    </svg>
  );
}

function KPICard({ label, value, delta, sub, spark, sparkColor }) {
  const isUp = typeof delta === "number" ? delta > 0 : String(delta).startsWith("+");
  const isDown = typeof delta === "number" ? delta < 0 : String(delta).startsWith("−") || String(delta).startsWith("-");
  const cls = isUp ? "up" : isDown ? "down" : "flat";
  const sign = typeof delta === "number" ? (delta > 0 ? "+" : "") : "";
  return (
    <div className="card" style={{ padding: 18, display: "flex", flexDirection: "column", gap: 4 }}>
      <div style={{ display: "flex", alignItems: "flex-start" }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="kpi-label">{label}</div>
          <div className="kpi-value">{value}</div>
        </div>
        {spark && <Sparkline data={spark} color={sparkColor || "var(--fg-3)"} fill width={90} height={36} />}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 2 }}>
        <span className={`kpi-delta ${cls}`} style={{ display: "inline-flex", alignItems: "center", gap: 3 }}>
          {isUp && <Icon.ArrowUp size={9} />}
          {isDown && <Icon.ArrowDn size={9} />}
          {sign}{delta}
        </span>
        {sub && <span className="kpi-sub">{sub}</span>}
      </div>
    </div>
  );
}

function TypologyChart() {
  const max = Math.max(...TYPOLOGY_DIST.map(t => t.count));
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {TYPOLOGY_DIST.map((t, i) => (
        <div key={t.name} style={{ display: "grid", gridTemplateColumns: "140px 1fr 60px", gap: 12, alignItems: "center" }}>
          <span style={{ fontSize: 12.5 }}>{t.name}</span>
          <div style={{ position: "relative", height: 6, background: "var(--bg-3)", borderRadius: 3, overflow: "hidden" }}>
            <div style={{
              width: `${(t.count / max) * 100}%`,
              height: "100%",
              background: i === 0 ? "var(--accent)" : "var(--fg)",
              opacity: i === 0 ? 1 : 0.7 - i * 0.07,
            }} />
          </div>
          <div className="mono" style={{ fontSize: 11.5, textAlign: "right" }}>
            {t.count} <span className="muted" style={{ fontSize: 10.5 }}>· {t.pct}%</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function CorridorTable() {
  return (
    <table className="tbl" style={{ fontSize: 12 }}>
      <thead>
        <tr>
          <th>Corridor</th>
          <th>Risk</th>
          <th className="right">90d volume</th>
        </tr>
      </thead>
      <tbody>
        {CORRIDOR_RISK.map((c, i) => (
          <tr key={i}>
            <td>
              <span className="mono" style={{ fontSize: 11.5 }}>{c.from}</span>
              <Icon.ArrowR size={10} style={{ margin: "0 6px", color: "var(--fg-3)" }} />
              <span className="mono" style={{ fontSize: 11.5 }}>{c.to}</span>
            </td>
            <td><RiskBar score={c.risk} /></td>
            <td className="right mono" style={{ fontSize: 11.5 }}>{c.vol}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function Leaderboard() {
  const max = Math.max(...QUEUE_BY_ASSIGNEE.map(a => a.open));
  return (
    <table className="tbl" style={{ fontSize: 12 }}>
      <thead>
        <tr>
          <th>Analyst</th>
          <th>Workload</th>
          <th className="right" style={{ width: 50 }}>Open</th>
          <th className="right" style={{ width: 60 }}>SLA</th>
        </tr>
      </thead>
      <tbody>
        {QUEUE_BY_ASSIGNEE.map(a => (
          <tr key={a.who}>
            <td>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                <span style={{
                  width: 20, height: 20, borderRadius: "50%",
                  background: a.color, color: "#fff",
                  display: "grid", placeItems: "center",
                  fontSize: 9, fontWeight: 600,
                }}>{a.init}</span>
                <span>{a.who}</span>
              </span>
            </td>
            <td>
              <div style={{ height: 4, background: "var(--bg-3)", borderRadius: 2 }}>
                <div style={{ width: `${(a.open/max)*100}%`, height: "100%", background: a.color, borderRadius: 2 }} />
              </div>
            </td>
            <td className="right mono">{a.open}</td>
            <td className="right mono" style={{ color: a.sla > 0 ? "var(--risk-high)" : "var(--fg-3)" }}>
              {a.sla > 0 ? `${a.sla} risk` : "—"}
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function HourHeatmap() {
  // 7×24 heatmap of alert generation
  const heatmapData = [];
  for (let d = 0; d < 7; d++) {
    const row = [];
    for (let h = 0; h < 24; h++) {
      // Synthetic but plausible — peaks at business hours, especially Tue/Wed
      const business = (h >= 8 && h <= 18) ? 1 : 0.3;
      const weekend = (d === 5 || d === 6) ? 0.4 : 1;
      const peak = (d === 1 || d === 2 || d === 3) && (h >= 10 && h <= 14) ? 1.4 : 1;
      const noise = 0.5 + (Math.sin(d*7 + h*0.7) + 1) * 0.5;
      row.push(Math.round(business * weekend * peak * noise * 12));
    }
    heatmapData.push(row);
  }
  const max = Math.max(...heatmapData.flat());
  const days = ["M","T","W","T","F","S","S"];
  return (
    <div>
      <div style={{ display: "flex", gap: 2, paddingLeft: 22 }}>
        {Array.from({ length: 24 }).map((_, h) => (
          <div key={h} style={{ width: 18, fontSize: 9.5, color: "var(--fg-3)", textAlign: "center", fontFamily: "var(--font-mono)" }}>
            {h % 4 === 0 ? h.toString().padStart(2, "0") : ""}
          </div>
        ))}
      </div>
      {heatmapData.map((row, d) => (
        <div key={d} style={{ display: "flex", gap: 2, alignItems: "center", marginTop: 2 }}>
          <div style={{ width: 20, fontSize: 10.5, color: "var(--fg-3)", fontFamily: "var(--font-mono)" }}>{days[d]}</div>
          {row.map((v, h) => (
            <div key={h} title={`${days[d]} ${h}:00 · ${v} alerts`}
                 style={{
                   width: 18, height: 18,
                   background: `oklch(${95 - (v/max)*65}% ${0.04 + (v/max)*0.16} 252)`,
                   borderRadius: 3,
                 }} />
          ))}
        </div>
      ))}
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 10, fontSize: 10.5, color: "var(--fg-3)" }}>
        <span>Less</span>
        {[0, 0.25, 0.5, 0.75, 1].map((v, i) => (
          <div key={i} style={{
            width: 14, height: 10,
            background: `oklch(${95 - v*65}% ${0.04 + v*0.16} 252)`,
            borderRadius: 2,
          }} />
        ))}
        <span>More</span>
      </div>
    </div>
  );
}

function AnalyticsView({ data }) {
  const kpis = data?.kpis || window.KPIS || {};
  const summary = data?.summary;
  const k = (key, fallback) => kpis[key] || fallback;

  return (
    <div style={{ padding: 18, overflow: "auto", flex: 1 }}>
      <div style={{ display: "flex", alignItems: "flex-end", marginBottom: 16, gap: 8 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>Operations overview</h1>
          <div style={{ color: "var(--fg-3)", fontSize: 12.5, marginTop: 4 }}>
            FIU workload and detection performance · last 30 days
          </div>
        </div>
        <div style={{ flex: 1 }} />
        <select className="field" defaultValue="30d" style={{ width: 130 }}>
          <option value="24h">Last 24 hours</option>
          <option value="7d">Last 7 days</option>
          <option value="30d">Last 30 days</option>
          <option value="qtd">Quarter to date</option>
        </select>
      </div>

      {/* KPI grid */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 12, marginBottom: 16 }}>
        <KPICard label={k("alertsOpen", { label: "Open alerts" }).label} value={k("alertsOpen", { value: "187" }).value} delta={k("alertsOpen", { delta: "+12" }).delta} sub="open now"
                 spark={SPARK_ALERTS} sparkColor="var(--accent)" />
        <KPICard label={k("highRisk", { label: "High-risk" }).label} value={k("highRisk", { value: "34" }).value} delta={k("highRisk", { delta: "+4" }).delta} sub="of total open"
                 spark={[8,10,12,11,13,14,16,15,17,18,21,24,28,30,34]} sparkColor="var(--risk-high)" />
        <KPICard label={k("slaBreached", { label: "SLA breached" }).label} value={k("slaBreached", { value: "6" }).value} delta={k("slaBreached", { delta: "−2" }).delta} sub="vs. last week"
                 spark={[12,11,13,10,9,8,9,7,8,6,5,7,6,5,6]} sparkColor="var(--risk-med)" />
        <KPICard label={k("avgClose", { label: "Avg close time" }).label} value={k("avgClose", { value: "4h 12m" }).value} delta={k("avgClose", { delta: "−18%" }).delta} sub="rule engine"
                 spark={SPARK_CLOSE} sparkColor="var(--risk-low)" />
        <KPICard label={k("sarsFiled", { label: "SARs filed · MTD" }).label} value={k("sarsFiled", { value: "21" }).value} delta={k("sarsFiled", { delta: "+3" }).delta} sub="MTD"
                 spark={[1,2,3,5,7,9,11,12,14,15,17,18,19,20,21]} sparkColor="var(--fg)" />
        <KPICard label={k("falsePositive", { label: "False positive rate" }).label} value={k("falsePositive", { value: "62%" }).value} delta={k("falsePositive", { delta: "−4pp" }).delta} sub="target 60%"
                 spark={[72,71,70,69,69,68,67,66,66,65,65,64,63,63,62]} sparkColor="var(--risk-low)" />
      </div>

      {/* Two-col charts */}
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 12, marginBottom: 12 }}>
        <div className="card">
          <div className="card-hd">
            <h3>Alerts by typology</h3>
            <span className="spacer" />
            <span className="mono muted" style={{ fontSize: 11 }}>187 alerts · 8 categories</span>
          </div>
          <div className="card-body">
            <TypologyChart />
          </div>
        </div>
        <div className="card">
          <div className="card-hd">
            <h3>Corridor risk</h3>
            <span className="spacer" />
            <span className="mono muted" style={{ fontSize: 11 }}>top 6 by volume</span>
          </div>
          <CorridorTable />
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 12 }}>
        <div className="card">
          <div className="card-hd">
            <h3>Alert generation · 7d × 24h</h3>
            <span className="spacer" />
            <span className="mono muted" style={{ fontSize: 11 }}>UTC</span>
          </div>
          <div className="card-body" style={{ paddingTop: 8 }}>
            <HourHeatmap />
          </div>
        </div>
        <div className="card">
          <div className="card-hd">
            <h3>Team workload</h3>
          </div>
          <Leaderboard />
        </div>
      </div>

      {/* Detection performance table */}
      <div className="card">
        <div className="card-hd">
          <h3>Detection rules · performance · 30d</h3>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>Rule</th>
              <th>Typology</th>
              <th className="right">Fires</th>
              <th className="right">TP rate</th>
              <th className="right">FP rate</th>
              <th>Trend</th>
              <th style={{ width: 80 }}>Status</th>
            </tr>
          </thead>
          <tbody>
            <RulRow id="R-204" name="Multiple sub-threshold deposits" type="Structuring" fires={84} tp={71} fp={29} trend={[2,3,4,5,7,8,9,11,12,14]} status="healthy" />
            <RulRow id="R-118" name="OFAC SDN partial match" type="Sanctions" fires={12} tp={92} fp={8} trend={[1,1,2,1,2,1,2,1,1,2]} status="healthy" />
            <RulRow id="R-307" name="Fan-out beneficiary pattern" type="Mule" fires={41} tp={58} fp={42} trend={[3,4,4,5,5,4,5,5,6,6]} status="watch" />
            <RulRow id="R-422" name="Same-day reversal" type="Round-tripping" fires={28} tp={42} fp={58} trend={[2,3,2,3,3,3,3,3,4,4]} status="tune" />
            <RulRow id="R-312" name="90d velocity step-up" type="Velocity" fires={36} tp={51} fp={49} trend={[3,4,4,4,4,4,4,4,4,4]} status="healthy" />
            <RulRow id="R-225" name="High-risk corridor" type="Geographic" fires={31} tp={61} fp={39} trend={[3,3,3,3,3,3,3,3,3,4]} status="healthy" />
            <RulRow id="R-510" name="Cash deposits > 80%" type="Cash intensity" fires={19} tp={47} fp={53} trend={[2,2,2,2,2,2,2,2,2,2]} status="watch" />
            <RulRow id="R-704" name="MCC 7995 spend" type="Card · merchant" fires={6}  tp={22} fp={78} trend={[1,1,1,1,1,1,1,1,1,1]} status="tune" />
          </tbody>
        </table>
      </div>
    </div>
  );
}

function RulRow({ id, name, type, fires, tp, fp, trend, status }) {
  const sCls = status === "healthy" ? "pill low" : status === "watch" ? "pill med" : "pill high";
  return (
    <tr>
      <td>
        <span className="mono" style={{ fontWeight: 500 }}>{id}</span>
        <span style={{ marginLeft: 10, color: "var(--fg-2)" }}>{name}</span>
      </td>
      <td className="muted" style={{ fontSize: 12 }}>{type}</td>
      <td className="right mono">{fires}</td>
      <td className="right mono" style={{ color: "var(--risk-low)" }}>{tp}%</td>
      <td className="right mono" style={{ color: fp > 50 ? "var(--risk-high)" : fp > 40 ? "var(--risk-med)" : "var(--fg-2)" }}>{fp}%</td>
      <td><Sparkline data={trend} color="var(--fg-3)" width={80} height={20} /></td>
      <td><span className={sCls}>{status}</span></td>
    </tr>
  );
}

Object.assign(window, { AnalyticsView, Sparkline });
