// Recent updates table + KPI row
const UPD_CLIENTS = window.NEXUS_DATA.CLIENTS;
const UPD_USERS   = window.NEXUS_DATA.USERS;
const UPD_ROWS    = window.NEXUS_DATA.RECENT_UPDATES;

const STATUS_LABEL = {
  requested: "Requested",
  quoted:    "Quoted",
  sourcing:  "Sourcing",
  ordered:   "Ordered",
  shipped:   "Shipped",
  received:  "Received",
  delivered: "Delivered",
  cancelled: "Cancelled",
};

function StatusPill({ s }) {
  return (
    <span className={`pill ${s}`}>
      <span className="dot"></span>
      {STATUS_LABEL[s] || s}
    </span>
  );
}

function DeltaCell({ from, to, note }) {
  // Status transitions render as pills; metadata changes get a small tag
  if (from && to && STATUS_LABEL[from] && STATUS_LABEL[to] && from !== to) {
    return (
      <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
        <StatusPill s={from}/>
        <span style={{ color: "var(--ink-4)", fontFamily: "Geist Mono, monospace", fontSize: 11 }}>→</span>
        <StatusPill s={to}/>
      </span>
    );
  }
  if (from && to && from === to && STATUS_LABEL[to]) {
    return (
      <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
        <StatusPill s={to}/>
        <span style={{ color: "var(--ink-4)", fontSize: 11 }}>· no change</span>
      </span>
    );
  }
  // metadata change
  const tagMap = {
    cost: "Cost",
    note: "Note",
    follow: "Follow-up",
    cond: "Condition",
  };
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      <span style={{
        fontFamily: "Geist Mono, monospace",
        fontSize: 10.5,
        textTransform: "uppercase",
        letterSpacing: ".06em",
        padding: "1px 6px",
        border: "1px dashed var(--line-strong)",
        borderRadius: 3,
        color: "var(--ink-2)",
        background: "var(--panel-2)",
      }}>{tagMap[to] || to}</span>
      <span style={{ color: "var(--ink-2)", fontSize: 12.5 }}>updated</span>
    </span>
  );
}

function KPIRow() {
  const kpis = [
    { label: "In-flight parts",    value: "84",      delta: "+6 today",   tone: "up" },
    { label: "Quotes awaiting",    value: "12",      delta: "3 expiring", tone: "warn" },
    { label: "Open requests",      value: "5",       delta: "21 parts",   tone: "neutral" },
    { label: "Pipeline (USD)",     value: "187,250", delta: "+12,300 vs yest", tone: "up" },
  ];
  // Tiny sparkline (8 bars) for each
  const bars = [
    [3,4,2,5,4,6,5,7],
    [5,6,4,5,4,6,6,5],
    [2,3,3,4,4,5,4,5],
    [4,3,5,4,6,5,7,8],
  ];
  return (
    <div className="kpi-row">
      {kpis.map((k, i) => (
        <div key={i} className="kpi">
          <div className="kpi-label">{k.label}</div>
          <div className="kpi-value">{k.value}</div>
          <div className="kpi-delta">
            <span className={k.tone === "up" ? "up" : k.tone === "warn" ? "down" : ""}>
              {k.tone === "up" ? "▲" : k.tone === "warn" ? "●" : "—"}
            </span>
            {k.delta}
          </div>
          <svg className="kpi-spark" width="76" height="22" viewBox="0 0 76 22">
            {bars[i].map((b, bi) => (
              <rect key={bi} x={bi * 9 + 1} y={22 - b * 2.4} width="6" height={b * 2.4}
                fill={bi === bars[i].length - 1 ? "var(--accent)" : "var(--line-strong)"} rx="1"/>
            ))}
          </svg>
        </div>
      ))}
    </div>
  );
}

function RecentUpdates() {
  const [filter, setFilter] = useState("all"); // all | status | meta | auto

  const filtered = useMemo(() => {
    return UPD_ROWS.filter(u => {
      if (filter === "all") return true;
      if (filter === "status") return STATUS_LABEL[u.to];
      if (filter === "meta")   return !STATUS_LABEL[u.to];
      if (filter === "auto")   return u.who === "sys";
      return true;
    });
  }, [filter]);

  // Group by basket and inject a basket divider row at each change
  const rows = [];
  let lastBasket = null;
  let basketCount = 0;
  let pendingDividerIdx = -1;

  filtered.forEach((u, i) => {
    if (u.basket !== lastBasket) {
      // close out previous count
      if (pendingDividerIdx !== -1) rows[pendingDividerIdx].count = basketCount;
      rows.push({ kind: "divider", basket: u.basket, abs: u.abs, t: u.t, count: 0 });
      pendingDividerIdx = rows.length - 1;
      basketCount = 0;
      lastBasket = u.basket;
    }
    basketCount++;
    rows.push({ kind: "row", ...u });
  });
  if (pendingDividerIdx !== -1) rows[pendingDividerIdx].count = basketCount;

  return (
    <div>
      <div className="section-head" style={{ marginBottom: 12 }}>
        <div className="section-title">Recent updates</div>
        <div className="section-sub">past 24h · {UPD_ROWS.length} events across {new Set(UPD_ROWS.map(u => u.basket)).size} baskets</div>
        <div className="section-actions">
          <div className="tabs">
            <button className={`tab ${filter === "all" ? "active" : ""}`} onClick={() => setFilter("all")}>All</button>
            <button className={`tab ${filter === "status" ? "active" : ""}`} onClick={() => setFilter("status")}>Status</button>
            <button className={`tab ${filter === "meta" ? "active" : ""}`} onClick={() => setFilter("meta")}>Metadata</button>
            <button className={`tab ${filter === "auto" ? "active" : ""}`} onClick={() => setFilter("auto")}>Auto-basket</button>
          </div>
          <button className="btn"><Icon.Filter/> Filter</button>
          <button className="btn"><Icon.Download/> Export</button>
        </div>
      </div>

      <div className="updates">
        <table className="updates-table">
          <thead>
            <tr>
              <th style={{ width: 110 }}>Time</th>
              <th style={{ width: 140 }}>NX No.</th>
              <th style={{ width: 180 }}>Part Number</th>
              <th style={{ width: 140 }}>Request / Client</th>
              <th>Update</th>
              <th style={{ width: 160 }}>Note</th>
              <th style={{ width: 130 }}>By</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => {
              if (r.kind === "divider") {
                return (
                  <tr key={"d" + i} className="basket-divider">
                    <td colSpan="7">
                      <div className="basket-label">
                        <span className="tag">BASKET</span>
                        <span className="mono">{r.basket} PST</span>
                        <span className="count">· {r.count} change{r.count === 1 ? "" : "s"}</span>
                        <span className="time">{r.t}</span>
                      </div>
                    </td>
                  </tr>
                );
              }
              const client = UPD_CLIENTS[r.client];
              const user = UPD_USERS[r.who];
              return (
                <tr key={i}>
                  <td className="time-cell">
                    <span className="ago">{r.t}</span>
                    <span className="abs">{r.abs}</span>
                  </td>
                  <td><a className="nx-link">{r.nx}</a></td>
                  <td className="pn">{r.pn}</td>
                  <td>
                    <div className="req">{r.req}</div>
                    <div style={{ color: client.color, fontSize: 12, fontWeight: 500 }}>{client.short}</div>
                  </td>
                  <td><DeltaCell from={r.from} to={r.to}/></td>
                  <td style={{ color: "var(--ink-2)", fontSize: 12.5 }}>{r.note}</td>
                  <td>
                    <div className="who">
                      <span className="mini" style={{ background: user.color }}>{user.short}</span>
                      <span style={{ color: "var(--ink)", fontSize: 12.5 }}>{user.name}</span>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <div className="updates-foot">
          <div>Showing <span className="mono">{filtered.length}</span> of <span className="mono">{UPD_ROWS.length}</span> updates from the last 24 hours</div>
          <div className="links">
            <a>View full audit log →</a>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RecentUpdates, KPIRow, StatusPill });
