// ADM-PROC-12 · Shortlist farmers (AMOMS Module 1)
// Admin Web · Procurement Manager · P0 · 1440×900
// Components: C-108 Confirmation modal · C-004 Number input · C-106 Inline error · C-001 Button
// Registered as window.Pages.shortlist

const Ic12 = window.Icons;
const KES12 = (n) => "KSh " + (Number(n) || 0).toLocaleString("en-US");
const TARGET_12 = 28000;
const REQ_12 = "PR-2026-0184";

// Shortlisted candidates (offered sums to 30,500 — gives headroom for all states).
const CANDIDATES_12 = [
  { id: "F-2731", name: "Mary Wairimu",  offered: 6200, rate: 92, tier: "A", region: "Murang'a" },
  { id: "F-2812", name: "Esther Njeri",  offered: 5400, rate: 94, tier: "A", region: "Murang'a" },
  { id: "F-2776", name: "Grace Wambui",  offered: 4500, rate: 96, tier: "B", region: "Embu" },
  { id: "F-2841", name: "Wanjiru Kamau", offered: 3800, rate: 95, tier: "A", region: "Murang'a" },
  { id: "F-2688", name: "James Maina",   offered: 3100, rate: 98, tier: "B", region: "Nyeri" },
  { id: "F-2702", name: "Lucy Akinyi",   offered: 2900, rate: 93, tier: "A", region: "Murang'a" },
  { id: "F-2839", name: "Joseph Mwangi", offered: 2200, rate: 97, tier: "B", region: "Nyeri" },
  { id: "F-2655", name: "Patrick Njoroge", offered: 2400, rate: 99, tier: "B", region: "Murang'a" },
];

const SEED = {
  fully:  [6200, 5400, 4500, 3800, 3100, 2200, 2800, 0],
  under:  [6200, 5400, 4500, 3800, 2100, 0, 0, 0],
  over:   [6200, 5400, 4500, 3800, 3100, 2900, 2200, 2400],
  single: [6200],
};

const Shortlist = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const state = (tweaks && tweaks.shortlistState) || "fully";
  const single = state === "single";
  const farmers = single ? CANDIDATES_12.slice(0, 1) : CANDIDATES_12;

  const [alloc, setAlloc] = useState(() => SEED[state] || SEED.fully);
  const [reason, setReason] = useState("");
  useEffect(() => { setAlloc(SEED[state] || SEED.fully); }, [state]);

  const total = alloc.slice(0, farmers.length).reduce((s, v) => s + (Number(v) || 0), 0);
  const status = total > TARGET_12 ? "over" : total === TARGET_12 ? "fully" : "under";
  const pct = Math.min(100, Math.round((total / TARGET_12) * 100));
  const barColor = status === "over" ? "var(--destructive)" : status === "fully" ? "var(--success)" : "var(--warning)";

  const setOne = (i, v) => setAlloc(a => a.map((x, j) => j === i ? Math.max(0, Math.min(farmers[i].offered, Number(v.replace(/[^\d]/g, "")) || 0)) : x));

  const confirm = () => {
    if (status === "over") { toast({ title: "Over-allocated", desc: "Reduce assignments to the target.", tone: "danger" }); return; }
    toast({ title: "Shortlist confirmed", desc: `${total.toLocaleString("en-US")} kg allocated across ${alloc.slice(0, farmers.length).filter(v => v > 0).length} farmers` });
    go("ADM-PROC-13.html");
  };

  return (
    <div className="page" style={{ padding: 0 }}>
      <div className="sl-backdrop">
        <div className="sl-modal">
          <div className="sl-head">
            <div className="sl-head-title">
              <div className="sl-title">Confirm shortlist — <span className="mono">{REQ_12}</span></div>
              <div className="sl-sub">{single ? "One farmer — full target auto-assigned." : "Assign quantity to each farmer. The total must not exceed the target."}</div>
            </div>
            <button className="btn btn-ghost btn-icon" aria-label="Close" onClick={() => go("ADM-PROC-10.html")}><Ic12.X size={18} /></button>
          </div>

          <div className="sl-body">
            {farmers.map((f, i) => (
              <div key={f.id} className="sl-row">
                <Avatar initials={f.name.split(" ").map(x => x[0]).join("")} size="sm" />
                <div className="sl-row-main">
                  <div className="sl-row-name">{f.name}<Badge tone={f.tier === "A" ? "avocado" : "pulp"}>Tier {f.tier}</Badge></div>
                  <div className="sl-row-meta">{f.region} · offered {f.offered.toLocaleString("en-US")} kg @ {KES12(f.rate)}/kg</div>
                </div>
                {single ? (
                  <div style={{ textAlign: "right" }}>
                    <div style={{ fontSize: 14, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{f.offered.toLocaleString("en-US")} kg</div>
                    <div className="muted" style={{ fontSize: 11 }}>auto-assigned</div>
                  </div>
                ) : (
                  <div className={`sl-alloc${(alloc[i] || 0) > f.offered ? " err" : ""}`}>
                    <input value={alloc[i] || 0} onChange={(e) => setOne(i, e.target.value)} aria-label={`Assign to ${f.name}`} />
                    <span className="unit">kg</span>
                  </div>
                )}
              </div>
            ))}
          </div>

          <div className="sl-summary">
            <div className="row" style={{ justifyContent: "space-between" }}>
              <span className="muted" style={{ fontSize: 12.5 }}>Allocated vs target</span>
              <span style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{total.toLocaleString("en-US")} / {TARGET_12.toLocaleString("en-US")} kg</span>
            </div>
            <div className="sl-bar"><div style={{ width: pct + "%", background: barColor }} /></div>
            {status === "under" && <div className="sl-banner under"><Ic12.Info size={14} />{(TARGET_12 - total).toLocaleString("en-US")} kg below target — add another farmer or proceed with partial fulfilment.</div>}
            {status === "fully" && <div className="sl-banner fully"><Ic12.CheckCircle size={14} />Fully allocated to target.</div>}
            {status === "over" && <div className="sl-banner over"><Ic12.Warning size={14} />{(total - TARGET_12).toLocaleString("en-US")} kg over target — reduce an assignment to continue.</div>}

            <div className="field" style={{ marginTop: 14 }}>
              <label className="label">Reason for shortlist <span className="muted" style={{ fontWeight: 400 }}>(optional)</span></label>
              <textarea className="textarea" style={{ minHeight: 64 }} placeholder="e.g. Best rate-to-reliability mix; prioritised Murang'a groups." value={reason} onChange={(e) => setReason(e.target.value)} />
              <div className="field-hint">Stored on the audit log for this requirement.</div>
            </div>
          </div>

          <div className="sl-foot">
            <Button variant="outline" onClick={() => go("ADM-PROC-10.html")}>Cancel</Button>
            <Button variant="primary" icon={Ic12.Check} disabled={status === "over"} onClick={confirm}>Confirm shortlist</Button>
          </div>
        </div>
      </div>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { shortlist: Shortlist });
