// ADM-PROC-20 · Farmer master — list  (Addendum Update A)
// Admin Web · Procurement Manager / Officer · P0 · 1440×900
// Central supplier directory: types, groups/tags, sortable table, bulk actions,
// right-rail preview, Leads/Archived tabs. Registered as window.Pages.farmerList.
// States (Tweak fmListState): default · empty · noresults · multiselect · loading

const F20 = window.FM;
const Ic20 = window.Icons;
const D20 = window.AMDATE;

const TypePill = ({ type }) => {
  const t = F20.TYPES[type] || F20.TYPES.farmer;
  return <Badge tone={t.tone}>{t.label}</Badge>;
};
const TierBadge20 = ({ tier }) => {
  const tone = tier === "A" ? "success" : tier === "B" ? "info" : tier === "C" ? "secondary" : "outline";
  return <Badge tone={tone}>{tier === "Unrated" ? "Unrated" : "Tier " + tier}</Badge>;
};
const RRBar = ({ v }) => (
  <span className="fm-rr"><span className="bar"><i style={{ width: v + "%" }}/></span><span className="n">{v ? v + "%" : "—"}</span></span>
);

const FarmerListRow = ({ f, sel, onToggle, onOpen, onKebab }) => (
  <tr className="proc-row" onClick={() => onOpen(f)}>
    <td onClick={(e) => { e.stopPropagation(); onToggle(f.id); }} style={{ width: 34 }}>
      <span className={`proc-check ${sel ? "on" : ""}`}><Ic20.Check size={11}/></span>
    </td>
    <td>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
        <Avatar initials={F20.initials(f.name)} size="sm"/>
        <span>
          <span style={{ fontWeight: 600, fontSize: 13 }}>{f.name}</span>
          {f.type === "middleman" && f.sources.length > 0 && <span className="muted" style={{ fontSize: 11, marginLeft: 6 }}>· {f.sources.length} source farmers</span>}
          <span className="muted mono" style={{ display: "block", fontSize: 11 }}>{f.id}{f.altName ? " · " + f.altName : ""}</span>
        </span>
      </span>
    </td>
    <td><TypePill type={f.type}/></td>
    <td className="mono" style={{ fontSize: 12 }}>{f.phone}</td>
    <td>{f.region}</td>
    <td>{f.groups.length ? <span className="fm-chipn"><span className="dotg"/>{f.groups.length} group{f.groups.length > 1 ? "s" : ""}</span> : <span className="muted">—</span>}</td>
    <td className="num"><RRBar v={f.responseRate}/></td>
    <td className="mono" style={{ fontSize: 12 }}>{f.lastDelivery ? D20(f.lastDelivery) : "—"}</td>
    <td><TierBadge20 tier={f.tier}/></td>
    <td className="actions" onClick={(e) => e.stopPropagation()}>
      <IconButton variant="ghost" size="sm" icon={Ic20.More} onClick={() => onKebab(f)}/>
    </td>
  </tr>
);

const FarmerListSkeleton = () => (
  <Card><div className="card-body flush"><div className="tbl-wrap"><table className="tbl">
    <thead><tr><th style={{ width: 34 }}></th><th>Farmer</th><th>Type</th><th>Phone</th><th>Region</th><th>Groups</th><th>Response</th><th>Last delivery</th><th>Tier</th><th></th></tr></thead>
    <tbody>{Array.from({ length: 7 }).map((_, i) => (
      <tr key={i}><td></td><td colSpan={9}><div className="sk lg" style={{ width: `${90 - i * 6}%` }}/></td></tr>
    ))}</tbody>
  </table></div></div></Card>
);

const FarmerList = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const state = tweaks?.fmListState || "default";
  const forceEmpty = state === "empty";
  const forceNoResults = state === "noresults";
  const loading = state === "loading";

  const all = F20.FARMERS;
  const [tab, setTab] = useState("all");
  const [search, setSearch] = useState(forceNoResults ? "zzzzz" : "");
  const [typeF, setTypeF] = useState("all");
  const [groupF, setGroupF] = useState("all");
  const [sort, setSort] = useState({ key: "name", dir: "asc" });
  const [sel, setSel] = useState(() => (state === "multiselect" ? all.slice(0, 3).map(f => f.id) : []));
  const [preview, setPreview] = useState(null);

  const active = all.filter(f => !f.lead && !f.archived);
  const leads = all.filter(f => f.lead);
  const archived = all.filter(f => f.archived);
  const pool = forceEmpty ? [] : tab === "leads" ? leads : tab === "archived" ? archived : active;

  const filtered = useMemo(() => {
    let out = pool.filter(f => {
      if (typeF !== "all" && f.type !== typeF) return false;
      if (groupF !== "all" && !f.groups.includes(groupF)) return false;
      if (search) { const q = search.toLowerCase(); if (!`${f.name} ${f.id} ${f.region} ${f.phone} ${f.altName || ""}`.toLowerCase().includes(q)) return false; }
      return true;
    });
    return window.sortRows(out, sort, ["lastDelivery"]);
  }, [pool, typeF, groupF, search, sort]);

  const toggle = (id) => setSel(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
  const allSelected = filtered.length > 0 && filtered.every(f => sel.includes(f.id));
  const toggleAll = () => setSel(allSelected ? [] : filtered.map(f => f.id));
  const kebab = (f) => toast({ title: f.name, desc: "Quick actions: Edit · Add to group · Add tag · Archive" });
  const openFarmer = (f) => { setPreview(f); };

  const clearFilters = () => { setSearch(""); setTypeF("all"); setGroupF("all"); };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Farmers</h1>
          <p className="page-sub">Your supplier directory — farmers, middlemen, cooperatives and agents. The core of broadcast targeting.</p>
        </div>
        <div className="page-actions">
          <Button variant="ghost" icon={Ic20.Download} onClick={() => toast({ title: "Export queued", desc: `${filtered.length} records · current filter set` })}>Export</Button>
          <Button variant="outline" icon={Ic20.Upload} onClick={() => go("ADM-PROC-23.html")}>Bulk import</Button>
          <Button variant="primary" icon={Ic20.Plus} onClick={() => go("ADM-PROC-22.html")}>Add farmer</Button>
        </div>
      </div>

      {/* Summary */}
      <div className="fm-stats">
        <div className="fm-stat"><div className="k"><Ic20.Users size={14}/>Total suppliers</div><div className="v">{active.length}</div></div>
        <div className="fm-stat"><div className="k"><Ic20.Layers size={14}/>Groups</div><div className="v">{F20.GROUPS.length}</div></div>
        <div className="fm-stat"><div className="k"><Ic20.Bolt size={14}/>Leads (pipeline)</div><div className="v">{leads.length}<small>from outreach</small></div></div>
        <div className="fm-stat"><div className="k"><Ic20.CheckCircle size={14}/>Tier A</div><div className="v">{active.filter(f => f.tier === "A").length}</div></div>
      </div>

      {/* Tabs */}
      <div className="fm-tabs">
        <button className={`fm-tab ${tab === "all" ? "on" : ""}`} onClick={() => setTab("all")}>All <span className="fm-tab-n">{active.length}</span></button>
        <button className={`fm-tab ${tab === "leads" ? "on" : ""}`} onClick={() => setTab("leads")}>Leads (pipeline) <span className="fm-tab-n">{leads.length}</span></button>
        <button className={`fm-tab ${tab === "archived" ? "on" : ""}`} onClick={() => setTab("archived")}>Archived <span className="fm-tab-n">{archived.length}</span></button>
      </div>

      {tab === "leads" && (
        <div className="fm-banner info"><Ic20.Bolt size={16} className="bi"/><div>These farmers were captured by the outreach team (Module 9) and are <b>read-only</b> here. Promote a lead to an active farmer to enable broadcasts.</div></div>
      )}

      {/* Toolbar */}
      <div className="fm-toolbar" style={{ display: "flex", gap: 10, marginBottom: 14, flexWrap: "wrap", alignItems: "center" }}>
        <div className="proc-search" style={{ maxWidth: 340 }}>
          <Ic20.Search size={15}/>
          <input className="input" placeholder="Search name, phone, ID…" value={search === "zzzzz" ? "" : search} onChange={(e) => setSearch(e.target.value)}/>
        </div>
        <select className="input" style={{ width: "auto", minWidth: 150 }} value={typeF} onChange={(e) => setTypeF(e.target.value)}>
          <option value="all">All types</option>
          {F20.TYPE_LIST.map(t => <option key={t.key} value={t.key}>{t.label}</option>)}
        </select>
        <select className="input" style={{ width: "auto", minWidth: 160 }} value={groupF} onChange={(e) => setGroupF(e.target.value)}>
          <option value="all">All groups</option>
          {F20.GROUPS.map(g => <option key={g.id} value={g.id}>{g.name}</option>)}
        </select>
        <Button variant="ghost" size="sm" icon={Ic20.Layers} onClick={() => go("ADM-PROC-24.html")}>Manage groups</Button>
        <div className="muted" style={{ marginLeft: "auto", fontSize: 12.5 }}>{filtered.length} of {pool.length}</div>
      </div>

      {/* Bulk bar */}
      {sel.length > 0 && (
        <div className="proc-bulkbar">
          <span className="bb-count">{sel.length} selected</span>
          <div className="bb-spacer"/>
          <button className="bb-btn" onClick={() => toast({ title: "Add to group", desc: `${sel.length} farmers` })}><Ic20.Layers size={13}/>Add to group</button>
          <button className="bb-btn" onClick={() => toast({ title: "Add tag", desc: `${sel.length} farmers` })}><Ic20.Tag size={13}/>Add tag</button>
          <button className="bb-btn" onClick={() => toast({ title: "Export subset", desc: `${sel.length} farmers` })}><Ic20.Download size={13}/>Export</button>
          <button className="bb-btn danger" onClick={() => { toast({ title: "Archived", desc: `${sel.length} farmers · reversible` }); setSel([]); }}><Ic20.Box size={13}/>Archive</button>
        </div>
      )}

      {loading ? <FarmerListSkeleton/> : (
        <div className={`fm-split ${preview ? "rail" : ""}`}>
          <Card>
            <div className="card-body flush">
              <div className="tbl-wrap">
                <table className="tbl">
                  <thead>
                    <tr>
                      <th style={{ width: 34 }} onClick={toggleAll}><span className={`proc-check ${allSelected ? "on" : ""}`}><Ic20.Check size={11}/></span></th>
                      <SortableTh label="Farmer" col="name" sort={sort} setSort={setSort}/>
                      <SortableTh label="Type" col="type" sort={sort} setSort={setSort}/>
                      <th>Phone</th>
                      <SortableTh label="Region" col="region" sort={sort} setSort={setSort}/>
                      <th>Groups</th>
                      <SortableTh label="Response" col="responseRate" sort={sort} setSort={setSort} num/>
                      <SortableTh label="Last delivery" col="lastDelivery" sort={sort} setSort={setSort}/>
                      <SortableTh label="Tier" col="tier" sort={sort} setSort={setSort}/>
                      <th className="actions"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {filtered.length === 0 ? (
                      <tr><td colSpan={10}>
                        {forceEmpty || pool.length === 0 ? (
                          <div className="proc-inline-empty" style={{ flexDirection: "column", gap: 10, padding: "56px 20px" }}>
                            <div style={{ width: 48, height: 48, borderRadius: 12, background: "var(--muted)", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--muted-foreground)" }}><Ic20.Users size={22}/></div>
                            <div style={{ textAlign: "center" }}>
                              <div style={{ fontWeight: 600, fontSize: 14 }}>No farmers yet</div>
                              <div className="muted" style={{ fontSize: 12.5, maxWidth: 380, marginTop: 3 }}>Add one manually, bulk-import a CSV, or wait for the outreach team to capture leads.</div>
                            </div>
                            <div className="row" style={{ gap: 8, marginTop: 4 }}>
                              <Button size="sm" variant="outline" icon={Ic20.Upload} onClick={() => go("ADM-PROC-23.html")}>Bulk import</Button>
                              <Button size="sm" variant="primary" icon={Ic20.Plus} onClick={() => go("ADM-PROC-22.html")}>Add farmer</Button>
                            </div>
                          </div>
                        ) : (
                          <div className="proc-inline-empty" style={{ justifyContent: "center" }}>
                            <Ic20.Search size={20}/>
                            <div><div style={{ fontWeight: 600, fontSize: 13.5 }}>No farmers match</div><div className="muted" style={{ fontSize: 12.5 }}>Clear filters or adjust your criteria.</div></div>
                            <Button size="sm" variant="outline" onClick={clearFilters} style={{ marginLeft: 8 }}>Clear</Button>
                          </div>
                        )}
                      </td></tr>
                    ) : filtered.map(f => (
                      <FarmerListRow key={f.id} f={f} sel={sel.includes(f.id)} onToggle={toggle} onOpen={openFarmer} onKebab={kebab}/>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </Card>

          {preview && (
            <Card className="fm-preview">
              <div className="card-body">
                <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
                  <div className="row" style={{ gap: 10, alignItems: "center" }}>
                    <Avatar initials={F20.initials(preview.name)}/>
                    <div><div style={{ fontWeight: 600, fontSize: 14 }}>{preview.name}</div><div className="muted mono" style={{ fontSize: 11 }}>{preview.id}</div></div>
                  </div>
                  <IconButton variant="ghost" size="sm" icon={Ic20.X} onClick={() => setPreview(null)}/>
                </div>
                <div className="row" style={{ gap: 6, margin: "12px 0" }}><TypePill type={preview.type}/><TierBadge20 tier={preview.tier}/></div>
                <div className="fm-kpis" style={{ marginBottom: 14 }}>
                  <div className="fm-kpi"><div className="k">Lifetime kg</div><div className="v">{preview.lifetime ? (preview.lifetime / 1000).toFixed(0) + "k" : "—"}</div></div>
                  <div className="fm-kpi"><div className="k">Response</div><div className="v">{preview.responseRate}<small>%</small></div></div>
                  <div className="fm-kpi"><div className="k">Avg QC</div><div className="v">{preview.avgQc}<small>%</small></div></div>
                </div>
                <div className="muted" style={{ fontSize: 11.5, textTransform: "uppercase", letterSpacing: "0.04em", fontWeight: 600, marginBottom: 8 }}>Recent activity</div>
                <div style={{ fontSize: 12.5, color: "var(--muted-foreground)", lineHeight: 1.6 }}>
                  Last delivery {preview.lastDelivery ? D20(preview.lastDelivery) : "—"}<br/>{preview.region} · {preview.variety}<br/>{preview.groups.length} group(s), {preview.tags.length} tag(s)
                </div>
                <Button variant="primary" size="sm" icon={Ic20.ArrowRight} style={{ marginTop: 14, width: "100%" }} onClick={() => go("ADM-PROC-21.html")}>Open full profile</Button>
              </div>
            </Card>
          )}
        </div>
      )}
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { farmerList: FarmerList });
