/* global React */
const { useState: useStateOps, useEffect: useEffectOps, useRef: useRefOps } = React;

/* Per-segment live "command surface" — mirrors the real Lanexa dashboard:
   KPI tiles with colored icon chips, a revenue-style sparkline, a live
   activity feed that ticks in, and a load-pipeline strip. */
const OPS = {
  carriers: {
    accent: "#3B82F6",
    view: "Dispatch Board",
    chart: { label: "Revenue Overview · CAD", axis: ["Feb", "Mar", "Apr"], draw: "M8,108 C70,96 120,40 200,46 C260,50 300,86 392,30", proj: "M200,46 C260,50 300,70 392,52" },
    kpis: [
      { chip: "#3B82F6", glyph: "▣", label: "Active Loads", to: 14, sub: "2 pending · 4 delivered" },
      { chip: "#22C55E", glyph: "$", label: "Revenue (Paid)", to: 30819, money: true, sub: "$41.9K outstanding" },
      { chip: "#A855F7", glyph: "◍", label: "Drivers", to: 7, suffix: " active", sub: "2 HOS warnings", warn: true },
      { chip: "#F59E0B", glyph: "▤", label: "Fleet", to: 8, suffix: " in use", sub: "1 available" },
    ],
    pipe: [["Dispatched", 5], ["At Pickup", 3], ["In Transit", 4], ["Delivered", 2]],
    feed: [
      { dot: "#22C55E", text: "WhatsApp → Harjot: Load LD-206 assigned", t: "now" },
      { dot: "#F59E0B", text: "Doc attached · LoadSummary-LD-206.pdf", t: "2m" },
      { dot: "#3B82F6", text: "LD-2026-0171 · AT_PICKUP → DISPATCHED", t: "14m" },
      { dot: "#0EA5E9", text: "LD-0162 cross-border MX → CA completed", t: "1h" },
      { dot: "#A855F7", text: "Gurpreet S. accepted Brampton → Buffalo", t: "1h" },
    ],
  },
  brokers: {
    accent: "#0EA5E9",
    view: "Load Board",
    chart: { label: "Margin Overview · CAD", axis: ["Feb", "Mar", "Apr"], draw: "M8,112 C70,104 120,60 200,52 C260,46 300,40 392,24", proj: "M200,52 C260,48 300,42 392,34" },
    kpis: [
      { chip: "#0EA5E9", glyph: "▦", label: "Open Posts", to: 23, sub: "8 quoted · 5 covering" },
      { chip: "#22C55E", glyph: "%", label: "Auto-Covered", to: 68, suffix: "%", sub: "vs 41% last month" },
      { chip: "#A855F7", glyph: "◈", label: "Avg Margin", to: 19, suffix: "%", sub: "$312 / load" },
      { chip: "#F59E0B", glyph: "◉", label: "Carriers", to: 142, sub: "31 preferred" },
    ],
    pipe: [["Posted", 8], ["Quoted", 6], ["Covered", 5], ["Tracking", 4]],
    feed: [
      { dot: "#22C55E", text: "DAT match · Carrier scored 96 — auto-tendered", t: "now" },
      { dot: "#0EA5E9", text: "Loadlink post LB-8841 covered in 4m", t: "3m" },
      { dot: "#F59E0B", text: "Rate con → invoice synced to QuickBooks", t: "11m" },
      { dot: "#A855F7", text: "Carrier scorecard updated · 3 flagged", t: "40m" },
      { dot: "#3B82F6", text: "Track link opened by shipper · ETA on time", t: "1h" },
    ],
  },
  "3pls": {
    accent: "#A855F7",
    view: "Network Console",
    chart: { label: "Consolidated P&L · CAD", axis: ["Feb", "Mar", "Apr"], draw: "M8,110 C70,100 120,70 200,58 C260,48 300,52 392,28", proj: "M200,58 C260,50 300,44 392,36" },
    kpis: [
      { chip: "#A855F7", glyph: "⬡", label: "Entities", to: 4, sub: "consolidated books" },
      { chip: "#3B82F6", glyph: "◍", label: "Agents", to: 18, sub: "per-agent P&L live" },
      { chip: "#22C55E", glyph: "$", label: "Net Revenue", to: 184200, money: true, sub: "+12% MoM" },
      { chip: "#0EA5E9", glyph: "⟳", label: "Cash Cycle", to: 21, suffix: " days", sub: "−9 vs legacy" },
    ],
    pipe: [["Booked", 7], ["Brokered", 5], ["Asset", 3], ["Settled", 6]],
    feed: [
      { dot: "#A855F7", text: "Entity GTA-Reefer Inc. closed month-end", t: "now" },
      { dot: "#22C55E", text: "Agent commission run · 18 statements", t: "5m" },
      { dot: "#3B82F6", text: "EDI 214 sent · no console touched", t: "22m" },
      { dot: "#0EA5E9", text: "Shipper portal: 14 legacy logins retired", t: "1h" },
      { dot: "#F59E0B", text: "Multi-entity statement auto-emailed", t: "2h" },
    ],
  },
  shippers: {
    accent: "#22C55E",
    view: "Shipper Portal",
    chart: { label: "Freight Spend · CAD", axis: ["Feb", "Mar", "Apr"], draw: "M8,40 C70,52 120,84 200,78 C260,74 300,96 392,104", proj: "M200,78 C260,82 300,92 392,98" },
    kpis: [
      { chip: "#22C55E", glyph: "◉", label: "Carrier Roster", to: 64, sub: "all compliance-checked" },
      { chip: "#3B82F6", glyph: "✓", label: "Tender Accept", to: 97, suffix: "%", sub: "first-tender" },
      { chip: "#F59E0B", glyph: "$", label: "Spend / Mo", to: 412000, money: true, sub: "−12% YoY" },
      { chip: "#A855F7", glyph: "◎", label: "On-Time", to: 96, suffix: "%", sub: "visibility 4×" },
    ],
    pipe: [["Tendered", 6], ["Accepted", 6], ["In Transit", 4], ["POD", 5]],
    feed: [
      { dot: "#22C55E", text: "Routing guide auto-tendered to primary", t: "now" },
      { dot: "#3B82F6", text: "Carrier COI lapsing in 6d · auto-blocked", t: "8m" },
      { dot: "#F59E0B", text: "Detention billed transparently · $240", t: "26m" },
      { dot: "#A855F7", text: "Quarterly review packet built · Q1", t: "1h" },
      { dot: "#0EA5E9", text: "Lane spend report exported · 14 lanes", t: "3h" },
    ],
  },
};

function fmt(v, cfg) {
  if (cfg.money) {
    if (v >= 1000) return "$" + Math.round(v / 1000) + "K";
    return "$" + Math.round(v);
  }
  return Math.round(v).toLocaleString("en-CA") + (cfg.suffix || "");
}

function OpsKpi({ cfg, segKey }) {
  const [val, setVal] = useStateOps(cfg.to);
  useEffectOps(() => {
    setVal(0);
    const steps = 34;
    let i = 0;
    const id = setInterval(() => {
      i++;
      const p = i / steps;
      const e = 1 - Math.pow(1 - p, 3);
      setVal(cfg.to * e);
      if (i >= steps) { setVal(cfg.to); clearInterval(id); }
    }, 32);
    return () => clearInterval(id);
  }, [cfg.to, segKey]);
  return (
    <div className="ops__kpi">
      <div className="ops__kpi-top">
        <div className="ops__chip" style={{ background: cfg.chip }}>{cfg.glyph}</div>
        <div className="ops__kpi-label">{cfg.label}</div>
      </div>
      <div className="ops__kpi-val">{fmt(val, cfg)}</div>
      <div className={`ops__kpi-sub ${cfg.warn ? "warn" : ""}`}>{cfg.warn ? "⚠ " : ""}{cfg.sub}</div>
    </div>
  );
}

function OpsFeed({ items, segKey }) {
  const [shown, setShown] = useStateOps(2);
  useEffectOps(() => {
    setShown(2);
    const id = setInterval(() => setShown((s) => (s >= items.length ? 2 : s + 1)), 1600);
    return () => clearInterval(id);
  }, [segKey]);
  return (
    <div className="ops__feed">
      {items.slice(0, shown).map((f, i) => (
        <div className="ops__feed-item" key={`${segKey}-${i}`}>
          <i style={{ background: f.dot }} />
          <div className="ops__feed-text">{f.text}</div>
          <div className="ops__feed-time">{f.t}</div>
        </div>
      ))}
    </div>
  );
}

function OpsConsole({ segment }) {
  const cfg = OPS[segment] || OPS.carriers;
  return (
    <div className="ops" style={{ "--ops-accent": cfg.accent }} key={segment}>
      <div className="ops__bar">
        <div className="ops__dots"><i /><i /><i /></div>
        <div className="ops__view">Lanexa · {cfg.view}</div>
        <div className="ops__live"><i /> Live</div>
      </div>

      <div className="ops__kpis">
        {cfg.kpis.map((k, i) => <OpsKpi key={`${segment}-${i}`} cfg={k} segKey={segment} />)}
      </div>

      <div className="ops__body">
        <div className="ops__panel ops__chart-wrap">
          <div className="ops__h"><span className="spk">↗</span> {cfg.chart.label}</div>
          <svg className="ops__chart-svg" viewBox="0 0 400 130" preserveAspectRatio="none">
            <defs>
              <linearGradient id={`og-${segment}`} x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor={cfg.accent} stopOpacity="0.35" />
                <stop offset="100%" stopColor={cfg.accent} stopOpacity="0" />
              </linearGradient>
            </defs>
            <line x1="8" y1="118" x2="392" y2="118" stroke="rgba(255,255,255,0.08)" />
            <path d={`${cfg.chart.draw} L392,118 L8,118 Z`} fill={`url(#og-${segment})`} stroke="none" />
            <path className="ops__chart-draw" key={`d-${segment}`} d={cfg.chart.draw} />
            <path className="ops__chart-proj" d={cfg.chart.proj} />
            {cfg.chart.axis.map((a, i) => (
              <text key={a} className="ops__chart-axis" x={20 + i * 180} y="128">{a} 2026</text>
            ))}
          </svg>
        </div>
        <div className="ops__panel">
          <div className="ops__h"><span className="spk">◴</span> Recent Activity</div>
          <OpsFeed items={cfg.feed} segKey={segment} />
        </div>
      </div>

      <div className="ops__pipe">
        {cfg.pipe.map(([name, n], i) => (
          <div className="ops__stage" key={`${segment}-${name}`}>
            <div className="ops__stage-name">{name}</div>
            <div className="ops__stage-count">{n}</div>
            <div className="ops__stage-bar" key={`b-${segment}-${i}`} style={{ width: `${Math.min(100, n * 16)}%`, animationDelay: `${i * 0.1}s` }} />
          </div>
        ))}
      </div>
    </div>
  );
}

/* ===== Single-pane stack — Dispatch hero visual =====
   Visualizes "six tools collapsed into one board": faded back panes
   (Compliance, Billing, Tracking, Driver App) stacked in 3D behind a
   sharp, glowing front "Dispatch Board" with a cinematic scan sweep. */
function DispatchStage() {
  const backPanes = ["Compliance", "Billing", "Tracking", "Driver App"];
  const rows = [
    { lane: "Brampton → Buffalo", st: "In transit", c: "#F59E0B" },
    { lane: "Mississauga → Detroit", st: "Assigned", c: "#3B82F6" },
    { lane: "Oakville → Cleveland", st: "At pickup", c: "#22C55E" },
  ];
  return (
    <div className="pane-stack">
      <div className="pane-stack__grid" />
      <div className="pane-stack__beam" style={{ width: "32%", top: "30%", left: "6%", transform: "rotate(20deg)" }} />
      <div className="pane-stack__beam" style={{ width: "28%", top: "62%", left: "8%", transform: "rotate(-14deg)", animationDelay: "0.6s" }} />
      <div className="pane-stack__beam" style={{ width: "24%", top: "46%", left: "4%", transform: "rotate(3deg)", animationDelay: "1.2s" }} />
      <div className="pane-stack__scene">
        {backPanes.map((p, i) => {
          const depth = (backPanes.length - i);
          return (
            <div
              key={p}
              className="pane-card back"
              style={{
                transform: `translateZ(${-depth * 46}px) translate(${depth * 13}px, ${-depth * 13}px)`,
                opacity: 0.32 + i * 0.12,
              }}
            >
              <span className="pane-card__tab">{p}</span>
            </div>
          );
        })}
        <div className="pane-card pane-front" style={{ transform: "translateZ(8px)" }}>
          <span className="pane-card__tab pane-front__tab">Dispatch Board</span>
          <div className="pane-front__scan" />
          <div className="pane-front__bar">
            <i style={{ background: "#FF5F57" }} /><i style={{ background: "#FEBC2E" }} /><i style={{ background: "#28C840" }} />
            <span className="pane-front__title">One board · live</span>
          </div>
          {rows.map((r, i) => (
            <div className="pane-front__row" key={i} style={{ "--row-accent": r.c }}>
              <span className="dot" />
              <span className="lane">{r.lane}</span>
              <span className="st">{r.st}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OpsConsole, DispatchStage });
