// ADM-PROC-01 · Procurement dashboard (AMOMS Module 1)
// Admin Web · Procurement Manager · P0 · 1440×900
// Components: C-101 Top app bar · C-103 Side nav · C-110 KPI card · C-201 Data table
//             C-007 Date-range picker · C-105 Empty state · C-001 Button
// Registered as window.Pages.procurement so the app shell (app.jsx) renders it.

const MD = window.MD;
const Ic = window.Icons;
const KES = (n) => "KSh " + n.toLocaleString("en-US");

// Cross-screen navigation (each screen is its own HTML file in this folder).
const procGo = (file) => { window.location.href = file; };

// ─── KPI tile (C-110) — clickable, supports delta / warning accent / tooltip / icon ───
const ProcKpi = ({ label, value, unit, sub, delta, deltaDir = "up", accent, hint, icon, onClick }) => (
  <Card
    className={`kpi proc-kpi${onClick ? " clickable" : ""}${accent === "warning" ? " kpi-accent-warn" : ""}`}
    onClick={onClick}
    role={onClick ? "button" : undefined}
    tabIndex={onClick ? 0 : undefined}
  >
    <div className="proc-kpi-main">
      <div className="kpi-label">
        {label}
        {hint && <span className="proc-hint" title={hint} aria-label={hint}><Ic.Info size={13} /></span>}
      </div>
      <div className="kpi-value" style={accent === "warning" ? { color: "var(--status-pending-fg)" } : undefined}>
        {value}{unit && <small>{unit}</small>}
      </div>
      {delta != null ? (
        <div className={`kpi-delta ${deltaDir}`}>
          {deltaDir === "up" ? <Ic.ArrowUp size={12} /> : <Ic.ArrowDown size={12} />}{delta}
        </div>
      ) : (sub && <div className="muted" style={{ fontSize: 12 }}>{sub}</div>)}
    </div>
    {icon && <span className="proc-kpi-icon" aria-hidden="true">{React.createElement(icon, { size: 19 })}</span>}
  </Card>
);

const ProcKpiSkeleton = () => (
  <Card className="kpi">
    <div className="sk sk-line" style={{ width: "55%" }} />
    <div className="sk sk-line lg" style={{ width: "40%", marginTop: 6 }} />
    <div className="sk sk-line" style={{ width: "30%", marginTop: 8 }} />
  </Card>
);

// ─── Date-range picker (C-007) ───
const PROC_RANGES = ["Today", "Last 7 days", "Last 30 days", "This quarter", "Custom range…"];
const DateRangePicker = ({ value, onChange }) => {
  const [open, setOpen] = useState(false);
  return (
    <div className="proc-menu-wrap">
      <button className="btn btn-outline" onClick={() => setOpen(o => !o)}>
        <Ic.Calendar size={15} />{value}<Ic.ChevronDown size={14} style={{ opacity: 0.6 }} />
      </button>
      {open && (
        <>
          <div className="proc-menu-scrim" onClick={() => setOpen(false)} />
          <div className="proc-menu" style={{ minWidth: 180 }}>
            {PROC_RANGES.map(r => (
              <button key={r} className={`proc-menu-item${r === value ? " active" : ""}`}
                      onClick={() => { onChange(r); setOpen(false); }}>
                {r === value && <Ic.Check size={14} />}
                <span style={{ marginLeft: r === value ? 0 : 22 }}>{r}</span>
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
};

// ─── Kebab menu (Bulk create / View slot calendar) ───
const ProcKebab = () => {
  const [open, setOpen] = useState(false);
  return (
    <div className="proc-menu-wrap">
      <button className="btn btn-outline btn-icon" aria-label="More actions" onClick={() => setOpen(o => !o)}>
        <Ic.More size={16} />
      </button>
      {open && (
        <>
          <div className="proc-menu-scrim" onClick={() => setOpen(false)} />
          <div className="proc-menu" style={{ right: 0, minWidth: 210 }}>
            <button className="proc-menu-item" onClick={() => procGo("ADM-PROC-04.html")}>
              <Ic.Layers size={15} /><span>Bulk create requirements</span>
            </button>
            <button className="proc-menu-item" onClick={() => procGo("ADM-PROC-16.html")}>
              <Ic.Calendar size={15} /><span>View slot calendar</span>
            </button>
          </div>
        </>
      )}
    </div>
  );
};

// ─── Helpers ───
const PROC_TODAY = new Date(2026, 4, 12);
const daysUntil = (iso) => Math.round((new Date(iso) - PROC_TODAY) / 864e5);
const deadlineLabel = (iso) => {
  const d = daysUntil(iso);
  if (d < 0) return { text: `${Math.abs(d)}d overdue`, tone: "overdue" };
  if (d === 0) return { text: "Due today", tone: "due" };
  if (d <= 2) return { text: `in ${d}d`, tone: "soon" };
  return { text: `in ${d}d`, tone: "ok" };
};
const VARIETY_TONE = { Hass: "avocado", Fuerte: "pulp", Pinkerton: "soil", Mixed: "secondary", Local: "secondary" };

// ─── Active requirements table (C-201) ───
const ActiveRequirementsTable = ({ rows, empty }) => (
  <Card>
    <CardHead
      title="Active requirements"
      desc="Broadcasted or in delivery — newest first"
      action={<Button size="sm" variant="ghost" icon={Ic.ArrowRight} onClick={() => procGo("ADM-PROC-02.html")}>View all</Button>}
    />
    <div className="card-body flush">
      <div className="tbl-wrap">
        <table className="tbl">
          <thead>
            <tr>
              <th>Requirement</th><th>Product</th><th className="num">Qty</th>
              <th>Status</th><th className="num">Responses</th><th>Deadline</th><th className="actions"></th>
            </tr>
          </thead>
          <tbody>
            {empty ? (
              <tr>
                <td colSpan={7}>
                  <div className="proc-inline-empty">
                    <Ic.Calendar size={20} />
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 13.5 }}>No requirements in this period</div>
                      <div className="muted" style={{ fontSize: 12.5 }}>Adjust the date range to see more.</div>
                    </div>
                  </div>
                </td>
              </tr>
            ) : rows.map(r => {
              const dl = deadlineLabel(r.deadline);
              return (
                <tr key={r.id} className="proc-row" onClick={() => procGo("ADM-PROC-05.html")}>
                  <td>
                    <div className="mono" style={{ fontSize: 12.5, fontWeight: 600 }}>{r.id}</div>
                    <div className="muted" style={{ fontSize: 12, marginTop: 2, whiteSpace: "normal", maxWidth: 240 }}>{r.title}</div>
                  </td>
                  <td><Badge tone={VARIETY_TONE[r.variety] || "outline"}>{r.variety}</Badge></td>
                  <td className="num" style={{ fontWeight: 600 }}>{r.qty.toLocaleString("en-US")}<span className="muted" style={{ fontWeight: 400 }}> kg</span></td>
                  <td><StatusBadge status={r.status} /></td>
                  <td className="num">
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, justifyContent: "flex-end" }}>
                      <Ic.User size={12} style={{ color: "var(--muted-foreground)" }} />{r.responses}
                    </span>
                  </td>
                  <td>
                    <div style={{ fontSize: 12.5 }}>{r.deadline.slice(5)}</div>
                    <div className={`proc-dl proc-dl-${dl.tone}`}>{dl.text}</div>
                  </td>
                  <td className="actions">
                    <button className="btn btn-ghost btn-icon btn-sm" aria-label="Open" onClick={(e) => { e.stopPropagation(); procGo("ADM-PROC-05.html"); }}>
                      <Ic.ChevronRight size={16} />
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  </Card>
);

const TableSkeleton = () => (
  <Card>
    <CardHead title="Active requirements" />
    <div className="card-body">
      {[0, 1, 2, 3, 4].map(i => (
        <div key={i} style={{ display: "flex", gap: 16, padding: "12px 0", borderTop: i ? "1px solid var(--border)" : "none" }}>
          <div className="sk sk-line" style={{ width: "26%" }} />
          <div className="sk sk-line" style={{ width: "14%" }} />
          <div className="sk sk-line" style={{ width: "14%" }} />
          <div className="sk sk-line" style={{ width: "16%" }} />
          <div className="sk sk-line" style={{ width: "12%" }} />
        </div>
      ))}
    </div>
  </Card>
);

// ─── Pending your action ───
const PENDING = [
  { tone: "success", icon: Ic.CheckCircle, title: "PR-2026-0182 ready to award", desc: "3 farmers shortlisted · 18,500 kg Hass", cta: "Approve", to: "ADM-PROC-13.html" },
  { tone: "warning", icon: Ic.Star,        title: "Review shortlist — PR-2026-0184", desc: "14 responses · target 28,000 kg", cta: "Review", to: "ADM-PROC-10.html" },
  { tone: "info",    icon: Ic.Clock,       title: "Reschedule request from Mary Wairimu", desc: "PR-2026-0181 · move delivery to 16 May", cta: "Open", to: "ADM-PROC-15.html" },
  { tone: "soil",    icon: Ic.Layers,      title: "Bulk draft awaiting approval", desc: "4 requirements · Week 3 plan", cta: "Open", to: "ADM-PROC-04.html" },
];
const PendingActions = ({ empty }) => (
  <Card style={{ display: "flex", flexDirection: "column" }}>
    <CardHead title="Pending your action" desc="Items assigned to you for review or approval" />
    <div className="card-body flush" style={{ flex: 1 }}>
      {empty ? (
        <div className="proc-inline-empty" style={{ padding: "28px 20px" }}>
          <Ic.CheckCircle size={20} style={{ color: "var(--success)" }} />
          <div>
            <div style={{ fontWeight: 600, fontSize: 13.5 }}>You're all caught up</div>
            <div className="muted" style={{ fontSize: 12.5 }}>Nothing waiting on you right now.</div>
          </div>
        </div>
      ) : PENDING.map((p, i) => (
        <div key={i} className="proc-pending" onClick={() => procGo(p.to)}>
          <span className={`proc-pending-ic tone-${p.tone}`}><p.icon size={15} /></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.35 }}>{p.title}</div>
            <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{p.desc}</div>
          </div>
          <button className="btn btn-outline btn-xs" onClick={(e) => { e.stopPropagation(); procGo(p.to); }}>{p.cta}</button>
        </div>
      ))}
    </div>
  </Card>
);

// ─── Recent broadcast activity (collapsible) ───
const ACTIVITY = [
  { tone: "info",    icon: Ic.Bolt,        text: <><b>PR-2026-0184</b> broadcast to <b>142 farmers</b> via App, SMS & WhatsApp</>, time: "2h ago" },
  { tone: "avocado", icon: Ic.User,        text: <>Esther Njeri responded — 5,400 kg @ KSh 94/kg</>, time: "1h ago" },
  { tone: "avocado", icon: Ic.User,        text: <>Mary Wairimu responded — 6,200 kg @ KSh 92/kg</>, time: "1h ago" },
  { tone: "success", icon: Ic.CheckCircle, text: <><b>PR-2026-0182</b> awarded to 3 farmers · KSh 92/kg avg</>, time: "3h ago" },
  { tone: "soil",    icon: Ic.Truck,       text: <><b>PR-2026-0181</b> moved to in-delivery — 22,000 kg mixed</>, time: "5h ago" },
];
const ActivityFeed = () => {
  const [open, setOpen] = useState(true);
  return (
    <Card>
      <button className="proc-collapse-head" onClick={() => setOpen(o => !o)} aria-expanded={open}>
        <div className="head-text">
          <div className="card-title">Recent broadcast activity</div>
          <div className="card-desc">Broadcasts and farmer responses across the plant</div>
        </div>
        <Ic.ChevronDown size={18} style={{ transition: "transform .2s", transform: open ? "rotate(180deg)" : "none", color: "var(--muted-foreground)" }} />
      </button>
      {open && (
        <div className="card-body" style={{ paddingTop: 4 }}>
          <div className="proc-feed">
            {ACTIVITY.map((a, i) => (
              <div key={i} className="proc-feed-item">
                <span className={`proc-feed-ic tone-${a.tone}`}><a.icon size={14} /></span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, lineHeight: 1.4 }}>{a.text}</div>
                  <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>{a.time}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </Card>
  );
};

// ─── First-run / empty hero (C-105) ───
const FirstRunHero = () => (
  <Card>
    <div style={{ padding: "56px 24px", textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
      <div style={{ width: 64, height: 64, borderRadius: 16, background: "var(--avocado-soft)", color: "var(--avocado-fg)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
        <Ic.Procurement size={30} />
      </div>
      <div>
        <div style={{ fontSize: 19, fontWeight: 600, letterSpacing: "-0.02em" }}>Create your first requirement</div>
        <div className="muted" style={{ fontSize: 13.5, maxWidth: 420, margin: "6px auto 0", lineHeight: 1.5 }}>
          Broadcast a sourcing requirement to your farmer groups and start receiving responses. Your pipeline health will appear here once you do.
        </div>
      </div>
      <div className="row" style={{ marginTop: 4 }}>
        <Button variant="primary" icon={Ic.Plus} onClick={() => procGo("ADM-PROC-03.html")}>Create requirement</Button>
        <Button variant="outline" icon={Ic.Layers} onClick={() => procGo("ADM-PROC-04.html")}>Bulk create</Button>
      </div>
    </div>
  </Card>
);

// ─── Page ───
const ProcurementDashboard = ({ tweaks }) => {
  const state = (tweaks && tweaks.procState) || "default";
  const [range, setRange] = useState("Last 30 days");

  const loading = state === "loading";
  const empty = state === "empty";
  const noResults = state === "noresults";

  const activeRows = useMemo(() => MD.REQUIREMENTS.filter(r => r.status !== "closed"), []);

  const z = noResults;
  const kpis = { open: z ? 0 : 12, awaiting: z ? 0 : 14, confirmed: z ? 0 : 8, avg: z ? "—" : "6.4" };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Procurement</h1>
          <div className="page-sub">Pipeline health and items needing your attention</div>
        </div>
        <div className="page-actions">
          <DateRangePicker value={range} onChange={setRange} />
          <ProcKebab />
          <Button variant="primary" icon={Ic.Plus} onClick={() => procGo("ADM-PROC-03.html")}>Create requirement</Button>
        </div>
      </div>

      {empty ? (
        <FirstRunHero />
      ) : (
        <>
          {/* Row 1 — KPI strip (4 cards full width) */}
          <div className="grid-4" style={{ marginBottom: 16 }}>
            {loading ? (
              <><ProcKpiSkeleton /><ProcKpiSkeleton /><ProcKpiSkeleton /><ProcKpiSkeleton /></>
            ) : (
              <>
                <ProcKpi label="Open requirements" value={kpis.open} icon={Ic.ClipboardList}
                         sub="Click to view filtered list" onClick={() => procGo("ADM-PROC-02.html")} />
                <ProcKpi label="Responses awaiting review" value={kpis.awaiting} icon={Ic.Eye}
                         accent={kpis.awaiting > 10 ? "warning" : undefined}
                         sub={kpis.awaiting > 10 ? "Above review threshold" : "Within threshold"}
                         onClick={() => procGo("ADM-PROC-02.html")} />
                <ProcKpi label="Confirmed orders this period" value={kpis.confirmed} icon={Ic.CheckCircle}
                         delta={z ? null : "14% vs prior"} deltaDir="up" />
                <ProcKpi label="Avg response time" value={kpis.avg} unit={z ? "" : "h"} icon={Ic.Clock}
                         hint="Average time from broadcast to first farmer response." />
              </>
            )}
          </div>

          {/* Row 2 — two columns 60 / 40 */}
          <div className="proc-two-col" style={{ marginBottom: 16 }}>
            {loading ? <TableSkeleton /> : <ActiveRequirementsTable rows={activeRows} empty={noResults} />}
            <PendingActions empty={noResults} />
          </div>

          {/* Row 3 — collapsible activity feed */}
          {!loading && <ActivityFeed />}
        </>
      )}
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { procurement: ProcurementDashboard });
