// ADM-PROC-09 · Broadcast status (AMOMS Module 1)
// Admin Web · Procurement Officer · P1 · 1440×900
// Components: C-110 KPI card · C-201 Data table · C-014 Status pill · C-001 Button
// Registered as window.Pages.broadcastStatus

const Ic9 = window.Icons;
const REQ_09 = "PR-2026-0184";

// Build per-farmer-per-channel delivery rows.
const CHAN_ICON = { App: Ic9.Mobile, SMS: Ic9.Phone, WhatsApp: Ic9.Mail };
const STATUS_TONE = { delivered: "approved", read: "avocado", sent: "info", failed: "rejected", queued: "pending" };
const ERRORS = ["Invalid phone number", "Handset unreachable", "Number not on WhatsApp"];

const ROWS_09 = (() => {
  const rows = [];
  window.MD.FARMERS.forEach((f, i) => {
    const region = f.village.includes(",") ? f.village.split(",")[1].trim() : f.village;
    const base = ["App", "SMS", "WhatsApp"];
    base.forEach((ch, j) => {
      if (ch === "WhatsApp" && i % 4 === 3) return; // not all on WhatsApp
      let status = "delivered";
      const seed = (i * 3 + j) % 11;
      if (seed === 0) status = "failed";
      else if (ch !== "SMS" && seed % 3 === 1) status = "read";
      else if (seed === 4) status = "sent";
      rows.push({
        farmer: f.name, init: f.name.split(" ").map(x => x[0]).join(""), region, channel: ch, status,
        sentAt: "09:42", deliveredAt: status === "failed" ? "—" : "09:42",
        readAt: ch === "SMS" ? null : (status === "read" ? "10:0" + (j + 2) : "—"),
        error: status === "failed" ? ERRORS[i % ERRORS.length] : null,
      });
    });
  });
  return rows;
})();

const StatusSkeleton9 = () => (
  <div className="page">
    <div className="sk lg" style={{ width: 260, marginBottom: 18 }} />
    <div className="grid-4" style={{ marginBottom: 16 }}>{[0, 1, 2, 3].map(i => <Card key={i} className="kpi"><div className="sk" style={{ width: "50%" }} /><div className="sk lg" style={{ width: "35%", marginTop: 8 }} /></Card>)}</div>
    <Card><div className="card-body">{[80, 70, 75, 60, 65].map((w, i) => <div key={i} className="sk" style={{ width: w + "%", marginBottom: 12 }} />)}</div></Card>
  </div>
);

const BroadcastStatus = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const state = (tweaks && tweaks.bcastStatusState) || "complete";

  const [chan, setChan] = useState("All");
  const [stat, setStat] = useState("All");
  const [rows, setRows] = useState(ROWS_09);

  if (state === "loading") return <StatusSkeleton9 />;

  const sending = state === "sending";
  const showFailures = state === "failures";
  const effectiveRows = showFailures ? rows : rows.map(r => r.status === "failed" && !showFailures ? r : r);

  const counts = rows.reduce((a, r) => { a.sent++; if (r.status === "failed") a.failed++; else a.delivered++; if (r.status === "read") a.read++; return a; }, { sent: 0, delivered: 0, read: 0, failed: 0 });
  const failedPct = Math.round((counts.failed / counts.sent) * 100);

  const filtered = rows.filter(r => (chan === "All" || r.channel === chan) && (stat === "All" || r.status === stat));
  const hasFailures = rows.some(r => r.status === "failed");

  const retryAll = () => { setRows(rs => rs.map(r => r.status === "failed" ? { ...r, status: "queued", error: null, deliveredAt: "retrying" } : r)); toast({ title: `Re-queued ${counts.failed} failed messages` }); };
  const retryOne = (idx) => { setRows(rs => rs.map((r, i) => i === idx ? { ...r, status: "queued", error: null, deliveredAt: "retrying" } : r)); toast({ title: "Message re-queued" }); };

  return (
    <div className="page">
      <div className="bs-head">
        <button className="btn btn-ghost btn-icon" aria-label="Back" onClick={() => go("ADM-PROC-05.html")}><Ic9.ChevronLeft size={18} /></button>
        <div style={{ flex: 1 }}>
          <h1 className="bs-title">Broadcast status — <span className="mono" style={{ fontWeight: 600 }}>{REQ_09}</span></h1>
          <div className="bs-sub">Per-farmer delivery across App, SMS &amp; WhatsApp</div>
        </div>
        <Button variant="outline" icon={Ic9.Download} onClick={() => toast({ title: "Exported delivery report (CSV)" })}>Export</Button>
      </div>

      {sending && (
        <div className="bs-sendbar">
          <Ic9.Bolt size={16} style={{ color: "var(--info)" }} />
          <div style={{ fontSize: 13, fontWeight: 500 }}>Sending in progress…</div>
          <div className="bar"><div style={{ width: "64%" }} /></div>
          <span className="muted" style={{ fontSize: 12, fontVariantNumeric: "tabular-nums" }}>243 / 377 processed</span>
        </div>
      )}

      {/* KPIs */}
      <div className="grid-4" style={{ marginBottom: 16 }}>
        <Card className="kpi"><div className="kpi-label"><Ic9.Bolt size={14} />Sent</div><div className="kpi-value">{counts.sent}</div></Card>
        <Card className="kpi"><div className="kpi-label"><Ic9.CheckCircle size={14} />Delivered</div><div className="kpi-value">{counts.delivered}</div></Card>
        <Card className="kpi"><div className="kpi-label"><Ic9.Eye size={14} />Read</div><div className="kpi-value">{counts.read}<small className="muted" style={{ fontWeight: 400 }}> App+WA</small></div></Card>
        <Card className="kpi" style={failedPct > 5 ? { borderColor: "oklch(from var(--destructive) l c h / 0.45)" } : undefined}>
          <div className="kpi-label"><Ic9.Warning size={14} />Failed</div>
          <div className="kpi-value" style={failedPct > 5 ? { color: "var(--destructive)" } : undefined}>{counts.failed}<small style={{ fontWeight: 400 }}> · {failedPct}%</small></div>
        </Card>
      </div>

      {/* Filters */}
      <div className="proc-chips" style={{ marginBottom: 14 }}>
        <span className="muted" style={{ fontSize: 12, marginRight: 2 }}>Channel</span>
        {["All", "App", "SMS", "WhatsApp"].map(c => <button key={c} className={`proc-chip${chan === c ? " on" : ""}`} onClick={() => setChan(c)}>{c}</button>)}
        <span style={{ width: 8 }} />
        <span className="muted" style={{ fontSize: 12, marginRight: 2 }}>Status</span>
        {["All", "delivered", "read", "sent", "failed"].map(s => <button key={s} className={`proc-chip${stat === s ? " on" : ""}`} onClick={() => setStat(s)} style={{ textTransform: "capitalize" }}>{s}</button>)}
      </div>

      <Card>
        <CardHead title={`${filtered.length} deliveries`} desc={hasFailures ? `${counts.failed} failed — retry below` : "All messages processed"}
          action={hasFailures && <Button size="sm" variant="primary" icon={Ic9.Bolt} onClick={retryAll}>Retry failed</Button>} />
        <div className="card-body flush">
          <div className="tbl-wrap">
            <table className="tbl">
              <thead><tr><th>Farmer</th><th>Region</th><th>Channel</th><th>Status</th><th>Sent</th><th>Delivered</th><th>Read</th><th>Error</th><th className="actions"></th></tr></thead>
              <tbody>
                {filtered.map((r, i) => {
                  const CI = CHAN_ICON[r.channel];
                  const origIdx = rows.indexOf(r);
                  return (
                    <tr key={i}>
                      <td><span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><Avatar initials={r.init} size="sm" /><span style={{ fontWeight: 500 }}>{r.farmer}</span></span></td>
                      <td className="muted">{r.region}</td>
                      <td><span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><CI size={13} />{r.channel}</span></td>
                      <td><StatusBadge status={r.status === "read" ? "approved" : r.status === "delivered" ? "approved" : r.status === "failed" ? "rejected" : r.status === "queued" ? "pending" : "info"} /></td>
                      <td className="mono" style={{ fontSize: 12 }}>{r.sentAt}</td>
                      <td className="mono" style={{ fontSize: 12 }}>{r.deliveredAt}</td>
                      <td className="mono" style={{ fontSize: 12 }}>{r.readAt === null ? <span className="bs-na">—</span> : r.readAt}</td>
                      <td>{r.error ? <span className="bs-err">{r.error}</span> : <span className="bs-na">—</span>}</td>
                      <td className="actions">{r.status === "failed" && <button className="btn btn-ghost btn-icon btn-sm" aria-label="Retry" onClick={() => retryOne(origIdx)}><Ic9.Bolt size={14} /></button>}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </Card>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { broadcastStatus: BroadcastStatus });
