/* global React, Ic, Chip, Sparkline, KPI, Panel */

function Analytics() {
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Analytics & Margin Insights</div>
          <div className="page-sub">YTD performance · Updated 13:02:18 · auto-refresh 5min</div>
        </div>
        <div className="page-actions">
          <div className="toggle-row">
            <button>7D</button><button className="on">30D</button><button>QTR</button><button>YTD</button>
          </div>
          <button className="btn ghost"><Ic.filter style={{ width: 12, height: 12 }} /> Slice</button>
          <button className="btn">Export CSV</button>
        </div>
      </div>

      <div className="grid cols-4 pad" style={{ paddingBottom: 0 }}>
        <KPI label="Revenue (30d)" value="$2.84M" delta="14.2%" spark={[180,200,220,240,260,250,275,290,300,310,320,335]} />
        <KPI label="Gross Margin" value="$508k" delta="0.8pt" spark={[42,44,45,46,47,48,48,49,50,49,51,50]} />
        <KPI label="Loads Booked" value="1,247" delta="11%" spark={[100,108,115,120,125,130,138,142,150,155,160,165]} />
        <KPI label="GM %" value="17.9%" delta="0.4pt" spark={[16,16,17,17,17,18,18,18,18,17,18,18]} />
      </div>

      <div className="grid cols-2 pad" style={{ paddingTop: 16 }}>
        {/* Margin trend chart */}
        <Panel title="GROSS MARGIN · 30 DAYS" actions={<span className="mono dim" style={{ fontSize: 10 }}>$2.84M REVENUE · $508K GM · 17.9%</span>}>
          <BigChart />
        </Panel>

        {/* AI savings */}
        <Panel title="AI VALUE CAPTURED · 30 DAYS">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <ValueRow label="Time saved (hours)" v="1,842" sub="≈ 23 FTE-weeks" />
            <ValueRow label="Detention recovered" v="$84,200" sub="412 claims auto-filed" />
            <ValueRow label="Better-priced bookings" v="$31,480" sub="vs. floor price" />
            <ValueRow label="No-show preventions" v="22" sub="$48,400 GM saved" />
            <ValueRow label="Touchless docs" v="94%" sub="↑ from 71%" />
            <ValueRow label="Calls handled by AI" v="6,418" sub="91% pickup, 84% resolve" />
          </div>
          <div style={{ marginTop: 14, padding: 12, background: "var(--accent-bg)", border: "1px solid var(--accent)", borderRadius: 4, fontSize: 12 }}>
            <span className="mono accent" style={{ fontSize: 10, letterSpacing: "0.12em", color: "var(--accent)" }}>NET AI IMPACT</span>
            <div style={{ marginTop: 4, display: "flex", alignItems: "baseline", gap: 8 }}>
              <span className="mono" style={{ fontSize: 26, fontWeight: 600 }}>$164,080</span>
              <span className="dim">incremental GM in last 30d</span>
            </div>
          </div>
        </Panel>
      </div>

      <div className="grid cols-3 pad" style={{ paddingTop: 0 }}>
        {/* Top lanes */}
        <Panel title="TOP LANES BY GM" flush>
          <table className="tbl">
            <thead><tr><th>Lane</th><th className="num">Loads</th><th className="num">$/mi</th><th className="num">GM %</th></tr></thead>
            <tbody>
              {[
                ["Atlanta, GA → Chicago, IL", 84, 2.98, 19.4],
                ["Dallas, TX → Newark, NJ", 72, 3.42, 18.6],
                ["LA, CA → Phoenix, AZ", 68, 2.18, 21.4],
                ["Houston, TX → Tampa, FL", 54, 2.52, 18.9],
                ["Seattle, WA → Denver, CO", 47, 2.34, 19.0],
                ["Charlotte, NC → Boston, MA", 41, 2.78, 16.8],
              ].map((r, i) => (
                <tr key={i}>
                  <td style={{ fontSize: 12 }}>{r[0]}</td>
                  <td className="num">{r[1]}</td>
                  <td className="num">${r[2]}</td>
                  <td className="num" style={{ color: r[3] > 19 ? "var(--ok)" : r[3] > 17 ? "var(--text)" : "var(--warn)" }}>{r[3]}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Panel>

        {/* Top customers */}
        <Panel title="TOP CUSTOMERS · GM %" flush>
          <table className="tbl">
            <thead><tr><th>Customer</th><th className="num">Loads</th><th className="num">Rev</th><th className="num">GM %</th></tr></thead>
            <tbody>
              {[
                ["Walmart", 217, "$612k", 17.2],
                ["Target",  148, "$408k", 18.4],
                ["Home Depot", 124, "$362k", 19.2],
                ["Costco",  98, "$284k", 17.8],
                ["Publix",  72, "$184k", 18.9],
                ["Meijer",  58, "$148k", 16.4],
              ].map((r, i) => (
                <tr key={i}>
                  <td>{r[0]}</td>
                  <td className="num">{r[1]}</td>
                  <td className="num">{r[2]}</td>
                  <td className="num">{r[3]}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Panel>

        {/* Top carriers */}
        <Panel title="TOP CARRIERS · ON-TIME" flush>
          <table className="tbl">
            <thead><tr><th>Carrier</th><th className="num">Loads</th><th className="num">OT%</th><th>Safety</th></tr></thead>
            <tbody>
              {[
                ["Western Mountain", 142, 98.4, "A"],
                ["BluePeak Carriers", 89, 96.1, "A"],
                ["Coastal Freight", 64, 94.3, "A"],
                ["Hidalgo Logistics", 51, 91.0, "A"],
                ["Eastern Star", 73, 89.6, "B"],
                ["Pinecone Hauling", 27, 82.4, "C"],
              ].map((r, i) => (
                <tr key={i}>
                  <td>{r[0]}</td>
                  <td className="num">{r[1]}</td>
                  <td className="num" style={{ color: r[2] > 95 ? "var(--ok)" : r[2] > 90 ? "var(--text)" : "var(--warn)" }}>{r[2]}%</td>
                  <td><Chip kind={r[3] === "A" ? "ok" : r[3] === "B" ? "warn" : "danger"}>{r[3]}</Chip></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Panel>
      </div>
    </div>
  );
}

function ValueRow({ label, v, sub }) {
  return (
    <div style={{ padding: 10, background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: 4 }}>
      <div className="kpi-label">{label}</div>
      <div className="mono" style={{ fontSize: 18 }}>{v}</div>
      <div className="dim" style={{ fontSize: 11 }}>{sub}</div>
    </div>
  );
}

function BigChart() {
  // synthesize 30-day series for revenue + gm
  const rev = Array.from({ length: 30 }, (_, i) => 60 + Math.sin(i * 0.6) * 8 + i * 1.5);
  const gm  = rev.map((v) => v * (0.16 + Math.sin(v * 0.1) * 0.02));
  const w = 700, h = 220, padL = 32, padR = 12, padT = 14, padB = 28;
  const maxV = Math.max(...rev) * 1.1;
  const maxGm = Math.max(...gm) * 1.1;
  const xs = (i) => padL + (i / (rev.length - 1)) * (w - padL - padR);
  const yr = (v) => padT + (1 - v / maxV) * (h - padT - padB);
  const yg = (v) => padT + (1 - v / maxGm) * (h - padT - padB);
  const path = (arr, y) => arr.map((v, i) => `${i === 0 ? "M" : "L"}${xs(i)},${y(v)}`).join(" ");

  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: 220 }}>
      {/* y grid */}
      {[0, 0.25, 0.5, 0.75, 1].map(p => (
        <g key={p}>
          <line x1={padL} y1={padT + p * (h - padT - padB)} x2={w - padR} y2={padT + p * (h - padT - padB)} stroke="var(--line)" />
          <text x={4} y={padT + p * (h - padT - padB) + 3} fontSize="9" fontFamily="var(--font-mono)" fill="var(--text-dim)">${Math.round(maxV * (1 - p))}k</text>
        </g>
      ))}
      <defs>
        <linearGradient id="rev-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="var(--blue)" stopOpacity="0.2" />
          <stop offset="1" stopColor="var(--blue)" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={`${path(rev, yr)} L${xs(rev.length-1)},${h - padB} L${padL},${h - padB} Z`} fill="url(#rev-grad)" />
      <path d={path(rev, yr)} stroke="var(--blue)" strokeWidth="1.5" fill="none" />
      <path d={path(gm, yg)}  stroke="var(--accent)" strokeWidth="1.5" fill="none" />
      {/* legend */}
      <g fontSize="10" fontFamily="var(--font-mono)">
        <rect x={w - 180} y={padT} width="8" height="2" fill="var(--blue)" />
        <text x={w - 165} y={padT + 4} fill="var(--text-mid)">REVENUE</text>
        <rect x={w - 90} y={padT} width="8" height="2" fill="var(--accent)" />
        <text x={w - 76} y={padT + 4} fill="var(--text-mid)">GROSS MARGIN</text>
      </g>
      {/* x labels */}
      {[0, 7, 14, 21, 28].map(i => (
        <text key={i} x={xs(i)} y={h - 10} fontSize="9" fontFamily="var(--font-mono)" fill="var(--text-dim)" textAnchor="middle">{`05/${(i+1).toString().padStart(2,"0")}`}</text>
      ))}
    </svg>
  );
}

window.Analytics = Analytics;
