// ───────────────────────────────────────────────────────────────
// Busco Ops — Clients, Couriers, Alerts screens · v2
// ───────────────────────────────────────────────────────────────

// ── CLIENTS ──────────────────────────────────────────────────
function ClientsScreen({ onToast }) {
  const CLIENT_ROWS = useStore((s) => s.clients);
  const [period, setPeriod] = useState("Monthly");
  const [view, setViewState] = useState(() => buscoPref.get("busco-clients-view", "cards"));
  const setView = (v) => { setViewState(v); buscoPref.set("busco-clients-view", v); };
  const [openId, setOpenId] = useState(null);
  const [filters, setFilters] = useState({ city: [], status: [] });
  const [drawer, setDrawer] = useState(null);      // { mode:'add'|'edit', client? }
  const [removeTarget, setRemoveTarget] = useState(null);
  const cityOptions = [...new Set(CLIENT_ROWS.flatMap(c => c.cities.map(x => x.name)))];
  const flagged = CLIENT_ROWS.filter(c => c.offloaded > 0 && c.rate < 75);
  const open = CLIENT_ROWS.find(c => c.id === openId);
  const target = CLIENT_ROWS.length;
  const meeting = target - flagged.length;

  // Period window for the table: Daily = today, Weekly = last 7 days,
  // Monthly = last 30 days. (KPIs above and the banner stay all-time.)
  const sinceIso = (() => {
    const d = new Date();
    if (period === "Weekly") d.setDate(d.getDate() - 6);
    if (period === "Monthly") d.setDate(d.getDate() - 29);
    return d.toISOString().slice(0, 10);
  })();
  const pstats = {};
  for (const e of (window.ENTRIES || [])) {
    if (e.date < sinceIso) continue;
    const s = pstats[e.client] || (pstats[e.client] = { offloaded: 0, delivered: 0, returned: 0, ppd: 0, cod: 0, codValue: 0 });
    s.offloaded += e.offloaded; s.delivered += e.delivered; s.returned += e.returned;
    s.ppd += e.ppd; s.cod += e.cod; s.codValue += e.codAmount;
  }
  const rows = CLIENT_ROWS.map(c => {
    const s = pstats[c.name] || { offloaded: 0, delivered: 0, returned: 0, ppd: 0, cod: 0, codValue: 0 };
    return { ...c, ...s, rate: s.offloaded > 0 ? Math.round((s.delivered / s.offloaded) * 100) : 0 };
  }).filter(c => {
    if (filters.city.length && !c.cities.some(x => filters.city.includes(x.name))) return false;
    if (filters.status.includes("Below target") && c.rate >= 75) return false;
    if (filters.status.includes("On target") && c.rate < 75) return false;
    return true;
  });

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {flagged.length > 0 && (
        <div className="banner warn">
          <Icon name="alert" size={16} color="var(--warn-700)" />
          <div>
            <b>{flagged.length} of {target} clients below the 75% target.</b>{" "}
            <span style={{ color: "var(--muted)" }}>{flagged.map(c => c.name).join(" · ")} — review courier assignments.</span>
          </div>
        </div>
      )}

      <div className="kpi-row">
        <KPI label="Active clients"     value={CLIENT_ROWS.length}                                    sub="across all KSA cities" icon="building" tint="var(--b50)" accent="var(--b600)" />
        <KPI label="Meeting target"     value={`${meeting}/${target}`}                                sub="rate ≥ 75%"            icon="check" tint="var(--good-50)" accent="var(--good-700)" tone={meeting === target ? "good" : ""} />
        <KPI label="Avg delivery rate"  value={`${CLIENT_ROWS.length ? Math.round(CLIENT_ROWS.reduce((a, c) => a + c.rate, 0) / CLIENT_ROWS.length) : 0}%`} sub="weighted across all clients" icon="trend" tint="var(--good-50)" accent="var(--good-700)" />
        <KPI label="Total returned"     value={fmtNum(CLIENT_ROWS.reduce((a, c) => a + c.returned, 0))} sub="parcels · all time"    icon="trend-down" tint="var(--warn-50)" accent="var(--warn-700)" />
      </div>

      <div className="sec" data-tour="clients">
        <h2>{window.t("All clients")} <span className="ct">{rows.length}{rows.length !== CLIENT_ROWS.length && <span className="muted" style={{ fontWeight: 400 }}> {window.t("of")} {CLIENT_ROWS.length}</span>}</span></h2>
        <div className="sec-right">
          <Segmented options={["Daily", "Weekly", "Monthly"]} value={period} onChange={setPeriod} />
          <div className="segmented">
            <button className={view === "table" ? "on" : ""} onClick={() => setView("table")}><Icon name="list" size={12} /></button>
            <button className={view === "cards" ? "on" : ""} onClick={() => setView("cards")}><Icon name="grid" size={12} /></button>
          </div>
          <FilterPopover
            groups={[
              { key: "city", label: "City", options: cityOptions },
              { key: "status", label: "Status", options: ["Below target", "On target"] }
            ]}
            value={filters}
            onChange={setFilters}
            onClear={() => setFilters({ city: [], status: [] })}
          />
          <ExportMenu onToast={onToast}
            getRows={() => ({
              rows: rows.map((c) => ({
                Client: c.name,
                Cities: (c.cities || []).map((x) => x.name).join(" | "),
                Currency: window.buscoClientCountry(c) === "bahrain" ? "BHD" : "SAR",
                "PPD rate": c.revenue_per_ppd, "COD rate": c.revenue_per_cod,
                "Payment terms (days)": c.payment_terms_days,
                Offloaded: c.offloaded, Delivered: c.delivered, Returned: c.returned,
                "Rate %": c.offloaded > 0 ? c.rate : "",
              })),
              filename: `busco-clients-${new Date().toISOString().slice(0, 10)}`,
            })} />
          <button className="btn primary sm" data-tour="add-client" onClick={() => setDrawer({ mode: "add" })}>
            <Icon name="plus" size={12} color="#fff" /> {window.t("Add client")}
          </button>
        </div>
      </div>

      {view === "table" ? (
        <div className="tbl-wrap">
          <table className="data">
            <thead>
              <tr>
                <th style={{ width: 32 }}>#</th>
                <th>{window.t("Client")}</th>
                <th>{window.t("Cities")}</th>
                <th className="num">{window.t("Off")}</th>
                <th className="num">{window.t("Del")}</th>
                <th className="num">{window.t("Ret")}</th>
                <th className="num">{window.t("PPD")}</th>
                <th>{window.t("Trend")}</th>
                <th style={{ width: 200 }}>{window.t("Rate")}</th>
                <th style={{ width: 78 }}></th>
              </tr>
            </thead>
            <tbody>
              {rows.map((c, i) => (
                <tr key={c.id} className={c.rate < 75 ? "row-bad" : ""} style={{ cursor: "pointer" }} onClick={() => setOpenId(c.id)}>
                  <td className="mono muted">{i + 1}</td>
                  <td className="strong">{c.name}</td>
                  <td className="muted" style={{ fontSize: 11.5 }}>{c.cities.map(x => x.name).join(", ")}</td>
                  <td className="num">{fmtNum(c.offloaded)}</td>
                  <td className="num" style={{ color: "var(--good-700)" }}>{fmtNum(c.delivered)}</td>
                  <td className="num" style={{ color: c.rate < 75 ? "var(--crit-700)" : "var(--text)" }}>{fmtNum(c.returned)}</td>
                  <td className="num">{fmtNum(c.ppd)}</td>
                  <td><Sparkline values={CLIENT_SPARKS[c.id] || [c.rate]} /></td>
                  <td><RateCell r={c.rate} /></td>
                  <td onClick={(e) => e.stopPropagation()}>
                    <div style={{ display: "flex", gap: 4 }}>
                      <button className="btn ghost sm" title="Edit" onClick={() => setDrawer({ mode: "edit", client: c })}><Icon name="edit" size={12} /></button>
                      <button className="btn ghost sm" title="Delete" onClick={() => setRemoveTarget(c)}><Icon name="trash" size={12} color="var(--crit)" /></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 14 }}>
          {rows.map(c => (
            <div key={c.id} className={"client-card " + (c.rate < 75 ? "bad" : "")} onClick={() => setOpenId(c.id)}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 700 }}>{c.name}</div>
                  <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{c.cities.map(x => x.name).join(" · ")}</div>
                </div>
                <RateBadge r={c.rate} size="lg" />
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginTop: 12 }}>
                <div className="tile"><div className="tl">{window.t("Off")}</div><div className="tv">{fmtNum(c.offloaded)}</div></div>
                <div className="tile"><div className="tl">{window.t("Del")}</div><div className="tv" style={{ color: "var(--good-700)" }}>{fmtNum(c.delivered)}</div></div>
                <div className="tile"><div className="tl">{window.t("Ret")}</div><div className="tv" style={{ color: c.rate < 75 ? "var(--crit-700)" : "var(--text)" }}>{fmtNum(c.returned)}</div></div>
              </div>
              <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--border-soft)", display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12 }}>
                <div>
                  <div className="label-tiny">6-mo trend</div>
                  <div style={{ marginTop: 6 }}><Sparkline values={CLIENT_SPARKS[c.id] || [c.rate]} /></div>
                </div>
                <div style={{ display: "flex", gap: 4 }} onClick={(e) => e.stopPropagation()}>
                  <button className="btn ghost sm" title={window.t("Edit")} onClick={() => setDrawer({ mode: "edit", client: c })}><Icon name="edit" size={12} /></button>
                  <button className="btn ghost sm" title={window.t("Delete")} onClick={() => setRemoveTarget(c)}><Icon name="trash" size={12} color="var(--crit)" /></button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {open && <ClientDetailModal client={open} onClose={() => setOpenId(null)} />}
      {drawer &&
        <ClientDrawer
          mode={drawer.mode}
          client={drawer.client}
          onClose={() => setDrawer(null)}
          onToast={onToast}
        />
      }
      {removeTarget &&
        <ConfirmModal
          title={`Delete ${removeTarget.name}?`}
          body={`This client and its rate configuration will be removed from the dashboard. Historical log entries are not affected.`}
          confirmLabel="Delete client"
          tone="danger"
          onConfirm={() => { Store.deleteClient(removeTarget.id); onToast(`${removeTarget.name} deleted`, "danger"); }}
          onClose={() => setRemoveTarget(null)}
        />
      }
    </div>
  );
}

function ClientDrawer({ mode = "add", client, onClose, onToast }) {
  const editing = mode === "edit";
  const [name, setName] = useState(client?.name || "");
  const [cities, setCities] = useState(client ? client.cities.map((c) => c.name) : []);
  // Warehouses per city, edited as a comma-separated string. Initialised from
  // the client's saved warehouses so editing never wipes them.
  const [whMap, setWhMap] = useState(() => {
    const m = {};
    if (client) for (const c of client.cities) m[c.name] = (c.warehouses || []).join(", ");
    return m;
  });
  const [ppd, setPpd] = useState(client?.revenue_per_ppd ?? 10);
  const [cod, setCod] = useState(client?.revenue_per_cod ?? 13);
  const [fee, setFee] = useState(client?.cod_collection_pct ?? 1.5);
  const [terms, setTerms] = useState(client?.payment_terms_days ?? 30);
  const [aliases, setAliases] = useState((client?.aliases || []).join(", "));
  const [reportType, setReportType] = useState(client?.report_type || "");
  const [country, setCountry] = useState(client?.country || "");
  const [billTo, setBillTo] = useState(client?.bill_to || "");
  const cityChoices = [...new Set(["Riyadh", "Jeddah", "Dammam", "Khobar", "Madinah", "Mecca", "Tabuk", "Manama", "Riffa", "Muharraq", ...cities])];
  useEffect(() => { const esc = (e) => e.key === "Escape" && onClose(); document.addEventListener("keydown", esc); return () => document.removeEventListener("keydown", esc); }, [onClose]);

  const [saving, setSaving] = useState(false);
  const save = async () => {
    const cityObjs = cities.map((n) => ({
      name: n,
      warehouses: (whMap[n] || "").split(",").map((s) => s.trim()).filter(Boolean),
    }));
    const payload = {
      name, cities: cityObjs, ppd, cod, fee, terms,
      aliases: aliases.split(",").map((s) => s.trim()).filter(Boolean),
      reportType: reportType || null,
      country: country || null,
      billTo: billTo || null,
    };
    // Await the write so a failed save surfaces instead of silently showing a
    // success toast and closing while nothing was actually saved.
    setSaving(true);
    try {
      if (editing) { await Store.updateClient(client.id, payload); onToast && onToast(`${name} updated`); }
      else { await Store.addClient(payload); onToast && onToast(`Client “${name}” added`); }
      onClose();
    } catch (e) {
      onToast && onToast(`Couldn’t save ${name}: ${e.message}`, "danger");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="slide-panel" onClick={(e) => e.stopPropagation()}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>{editing ? window.t("Edit client") : window.t("Add client")}</h3>
            <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{editing ? `Update ${client.name}’s account & rates` : "Onboard a new client to the dashboard"}</div>
          </div>
          <button className="close-x" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 14, overflowY: "auto", flex: 1 }}>
          <div className="field">
            <label>{window.t("Client name")}</label>
            <input autoFocus value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Ajex KSA…" />
          </div>
          <div className="field">
            <label>{window.t("Aliases")} <span className="muted" style={{ textTransform: "none", fontWeight: 400 }}>{window.t("opt")}</span></label>
            <input value={aliases} onChange={e => setAliases(e.target.value)} placeholder={window.t("e.g. Ajex BH, AJEX Bahrain — comma-separated")} />
            <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 4 }}>{window.t("Other names this client appears under in reports — they'll be recognised when importing.")}</div>
          </div>
          <div className="field-row c2">
            <div className="field">
              <label>{window.t("Report type")}</label>
              <select value={reportType} onChange={e => setReportType(e.target.value)}>
                <option value="">{window.t("None / generic")}</option>
                <option value="ajex-ksa">Ajex KSA</option>
                <option value="ajex-bh">Ajex (BH)</option>
              </select>
            </div>
            <div className="field">
              <label>{window.t("Country")}</label>
              <select value={country} onChange={e => setCountry(e.target.value)}>
                <option value="">{window.t("Auto (from cities)")}</option>
                <option value="ksa">KSA</option>
                <option value="bahrain">Bahrain</option>
              </select>
            </div>
          </div>
          <div className="field">
            <label>{window.t("Invoice — Bill To")} <span className="muted" style={{ textTransform: "none", fontWeight: 400 }}>{window.t("opt")}</span></label>
            <textarea rows={4} value={billTo} onChange={e => setBillTo(e.target.value)}
              placeholder={"AJ FOR LOGISTICS SERVICES LLC\nCR No: 1010639740\n6960, RIYADH 3541, KSA OLIA WADI ASUMAN\nKINGDOM OF SAUDI ARABIA"} />
            <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 4 }}>{window.t("Printed exactly as written in the BILL TO section of invoices (legal name, CR no, address).")}</div>
          </div>
          <div className="field">
            <label>{window.t("Cities served")}</label>
            <PillRow options={cityChoices} value={cities} onChange={setCities} multi />
          </div>
          {cities.length > 0 &&
            <div className="field">
              <label>{window.t("Warehouses per city")}</label>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {cities.map((cn) => (
                  <div key={cn} style={{ display: "grid", gridTemplateColumns: "90px 1fr", gap: 8, alignItems: "center" }}>
                    <span style={{ fontSize: 12, fontWeight: 600 }}>{cn}</span>
                    <input value={whMap[cn] || ""} onChange={(e) => setWhMap((m) => ({ ...m, [cn]: e.target.value }))}
                           placeholder={window.t("e.g. North Hub, South Hub")} />
                  </div>
                ))}
              </div>
              <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 5 }}>{window.t("Separate multiple warehouses with commas.")}</div>
            </div>
          }
          <div className="field-row c2">
            <div className="field"><label>{window.t("PPD rate")} ({country === "bahrain" ? "BHD" : "SAR"})</label><input className="mono" type="number" value={ppd} onChange={e => setPpd(e.target.value)} /></div>
            <div className="field"><label>{window.t("COD rate")} ({country === "bahrain" ? "BHD" : "SAR"})</label><input className="mono" type="number" value={cod} onChange={e => setCod(e.target.value)} /></div>
          </div>
          <div className="field">
            <label>{window.t("Payment terms (days)")}</label>
            <input className="mono" type="number" value={terms} onChange={e => setTerms(e.target.value)} />
          </div>
        </div>
        <div style={{ padding: 18, borderTop: "1px solid var(--border)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn" onClick={onClose}>{window.t("Cancel")}</button>
          <button className="btn primary" disabled={!name || cities.length === 0 || saving} onClick={save}>{saving ? "Saving…" : (editing ? "Save changes" : "Save client")}</button>
        </div>
      </div>
    </div>
  );
}

// ── Client Detail Modal ──────────────────────────────────────
function ClientDetailModal({ client, onClose }) {
  const trend = CLIENT_TRENDS[client.id];
  const cities = CITY_BREAKDOWN[client.id];
  const ppdCodSplit = [
    { name: "PPD", value: client.ppd, fill: "var(--info-600)" },
    { name: "COD", value: client.cod, fill: "var(--warn)" },
  ];
  const cityShare = cities.map((c, i) => ({
    name: c.city, value: c.del,
    fill: ["#E55A37", "#10B981", "#F59E0B", "#2563EB", "#8B5CF6"][i],
  }));

  const insights = [];
  if (client.rate < 75) insights.push({ tone: "bad", text: `Rate is ${client.rate}% — ${75 - client.rate}pp below target. Review courier assignments and failed delivery root causes.` });
  if (client.returned / Math.max(client.delivered, 1) > 0.3) insights.push({ tone: "warn", text: "High return rate. Investigate address accuracy and customer availability windows." });
  if (client.rate >= 90) insights.push({ tone: "good", text: "Excellent performance. Benchmark this client's process across the fleet." });
  const latest = trend.at(-1).r, first = trend[0].r;
  if (latest > first + 5) insights.push({ tone: "good", text: "Recent trend improving. Current strategy working." });
  if (latest < first - 5) insights.push({ tone: "bad", text: "Recent performance declining. Escalate to operations." });
  if (insights.length === 0) insights.push({ tone: "neutral", text: "Performance stable across the last 6 periods. No anomalies detected." });

  return (
    <Modal
      onClose={onClose}
      title={
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ width: 36, height: 36, borderRadius: "var(--r-sm)", background: "var(--b50)", color: "var(--b700)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 12, border: "1px solid var(--b100)" }}>
            {client.name.split(" ").map(s => s[0]).slice(0, 2).join("")}
          </div>
          <div>
            <div style={{ fontSize: 15, fontWeight: 600 }}>{client.name}</div>
            <div style={{ fontSize: 11.5, color: "var(--muted)" }}>
              {client.cities.map(x => x.name).join(" · ")} · {client.cities.reduce((a, x) => a + x.warehouses.length, 0)} warehouses
            </div>
          </div>
          <RateBadge r={client.rate} size="lg" />
        </div>
      }
    >
      {/* 6 KPI chips */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 10, marginBottom: 18 }}>
        {[
          { l: "Offloaded", v: fmtNum(client.offloaded), c: "var(--text)" },
          { l: "Delivered", v: fmtNum(client.delivered), c: "var(--good-700)" },
          { l: "Returned",  v: fmtNum(client.returned),  c: client.rate < 75 ? "var(--crit-700)" : "var(--text)" },
          { l: "PPD",       v: fmtNum(client.ppd),       c: "var(--info-700)" },
          { l: "COD",       v: fmtNum(client.cod),       c: "var(--warn-700)" },
          { l: "COD SAR",   v: fmtSAR(client.codValue),  c: "var(--text)" },
        ].map((k, i) => (
          <div key={i} className="tile">
            <div className="tl">{k.l}</div>
            <div className="tv" style={{ color: k.c, fontSize: 17 }}>{k.v}</div>
          </div>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="card">
          <div className="card-head">
            <div className="ch-l"><h3>{window.t("Delivery rate trend")}</h3><div className="ch-sub">{window.t("75% target (dashed)")}</div></div>
          </div>
          <div className="card-body" style={{ paddingTop: 6 }}>
            <div style={{ height: 210 }}>
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={trend} margin={{ top: 8, right: 8, left: -20, bottom: 0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="var(--border-soft)" vertical={false} />
                  <XAxis dataKey="p" tick={tickStyle} axisLine={false} tickLine={false} />
                  <YAxis tick={tickStyle} axisLine={false} tickLine={false} domain={[60, 100]} width={36} />
                  <Tooltip contentStyle={tipStyle} />
                  <ReferenceLine y={75} stroke="var(--crit)" strokeDasharray="4 4" />
                  <Line type="monotone" dataKey="r" stroke="var(--b500)" strokeWidth={2.5} dot={{ r: 3, fill: "var(--b500)" }} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="card-head">
            <div className="ch-l"><h3>{window.t("PPD vs COD volume")}</h3><div className="ch-sub">{window.t("Last 6 months")}</div></div>
          </div>
          <div className="card-body" style={{ paddingTop: 6 }}>
            <div style={{ height: 210 }}>
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={trend} margin={{ top: 8, right: 8, left: -20, bottom: 0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="var(--border-soft)" vertical={false} />
                  <XAxis dataKey="p" tick={tickStyle} axisLine={false} tickLine={false} />
                  <YAxis tick={tickStyle} axisLine={false} tickLine={false} width={36} />
                  <Tooltip contentStyle={tipStyle} />
                  <Bar dataKey="ppd" name="PPD" fill="var(--info-600)" radius={[3, 3, 0, 0]} />
                  <Bar dataKey="cod" name="COD" fill="var(--warn)" radius={[3, 3, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14, marginTop: 14 }}>
        <div className="tbl-wrap">
          <div className="tbl-head"><h3>{window.t("Performance by city")}</h3></div>
          <table className="data">
            <thead>
              <tr>
                <th>{window.t("City")}</th>
                <th className="num">{window.t("Off")}</th>
                <th className="num">{window.t("Del")}</th>
                <th className="num">{window.t("Ret")}</th>
                <th className="num">{window.t("PPD")}</th>
                <th className="num">{window.t("COD")}</th>
                <th>Rate</th>
              </tr>
            </thead>
            <tbody>
              {cities.map(row => {
                const r = rate(row.del, row.off);
                return (
                  <tr key={row.city} className={r < 75 ? "row-bad" : ""}>
                    <td className="strong">{row.city}</td>
                    <td className="num">{fmtNum(row.off)}</td>
                    <td className="num">{fmtNum(row.del)}</td>
                    <td className="num">{fmtNum(row.ret)}</td>
                    <td className="num">{fmtNum(row.ppd)}</td>
                    <td className="num">{fmtNum(row.cod)}</td>
                    <td><RateBadge r={r} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <PieCard title="PPD vs COD split" data={ppdCodSplit} total={client.ppd + client.cod} />
          <PieCard title="Deliveries by city" data={cityShare} total={cityShare.reduce((a, x) => a + x.value, 0)} />
        </div>
      </div>

      <div className="card" style={{ marginTop: 14 }}>
        <div className="card-head">
          <div className="ch-l"><h3>{window.t("Insights & recommendations")}</h3><div className="ch-sub">{window.t("Rules-based observations")}</div></div>
        </div>
        <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {insights.map((ins, i) => {
            const tones = {
              good:    { bg: "var(--good-50)", color: "var(--good-700)", bd: "var(--good-100)", ic: "check-circle" },
              warn:    { bg: "var(--warn-50)", color: "var(--warn-700)", bd: "var(--warn-100)", ic: "alert-circle" },
              bad:     { bg: "var(--crit-50)", color: "var(--crit-700)", bd: "var(--crit-100)", ic: "alert" },
              neutral: { bg: "var(--surface-2)", color: "var(--text-2)", bd: "var(--border)", ic: "info" },
            }[ins.tone];
            return (
              <div key={i} style={{ display: "flex", gap: 10, padding: "10px 14px", background: tones.bg, border: `1px solid ${tones.bd}`, borderRadius: "var(--r-sm)", color: tones.color, fontSize: 12.5 }}>
                <Icon name={tones.ic} size={15} color={tones.color} />
                <span>{ins.text}</span>
              </div>
            );
          })}
        </div>
      </div>
    </Modal>
  );
}

function PieCard({ title, data, total }) {
  return (
    <div className="card">
      <div className="card-head"><h3>{title}</h3></div>
      <div className="card-body" style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{ width: 96, height: 96, flexShrink: 0 }}>
          <ResponsiveContainer width="100%" height="100%">
            <PieChart>
              <Pie data={data} dataKey="value" innerRadius={24} outerRadius={44} paddingAngle={2}>
                {data.map((e, i) => <Cell key={i} fill={e.fill} />)}
              </Pie>
              <Tooltip contentStyle={tipStyle} />
            </PieChart>
          </ResponsiveContainer>
        </div>
        <div style={{ fontSize: 11.5, flex: 1 }}>
          {data.map((p, i) => {
            const pct = Math.round((p.value / Math.max(total, 1)) * 100);
            return (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 5, justifyContent: "space-between" }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                  <span className="dot" style={{ background: p.fill }} /> {p.name}
                </span>
                <span className="mono muted">{pct}%</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── COURIERS ─────────────────────────────────────────────────
function CouriersScreen({ onToast }) {
  const COURIER_ROWS = useStore((s) => s.couriers);
  const [period, setPeriod] = useState("Monthly");
  const [search, setSearch] = useState("");
  const [filters, setFilters] = useState({ client: [], zone: [], contract: [] });
  const [sortBy, setSortBy] = useState("rate-desc");
  const [selected, setSelected] = useState([]);            // courier ids for bulk delete
  const [chartKind, setChartKind] = useState("line");
  const [drawer, setDrawer] = useState(null);              // { mode:'add'|'edit', courier? }
  const [removeTargets, setRemoveTargets] = useState(null); // array of couriers

  const zonesOf = (c) => (c.zones && c.zones.length) ? c.zones : (c.zone ? [c.zone] : []);
  const clientFilterOptions = [...new Set(COURIER_ROWS.flatMap((c) => c.clients || []))];
  const zoneFilterOptions = [...new Set(COURIER_ROWS.flatMap(zonesOf))];

  const SORTERS = {
    "rate-desc": (a, b) => b.rate - a.rate,
    "rate-asc": (a, b) => a.rate - b.rate,
    "name": (a, b) => a.name.localeCompare(b.name),
    "id": (a, b) => String(a.courier_code || "").localeCompare(String(b.courier_code || "")),
    "delivered-desc": (a, b) => b.delivered - a.delivered,
    "offloaded-desc": (a, b) => b.offloaded - a.offloaded,
  };

  const filtered = COURIER_ROWS.filter(c => {
    const q = search.toLowerCase();
    if (q && !c.name.toLowerCase().includes(q)
          && !String(c.zone || "").toLowerCase().includes(q)
          && !String(c.courier_code || "").toLowerCase().includes(q)) return false;
    if (filters.client.length && !(c.clients || []).some((x) => filters.client.includes(x))) return false;
    if (filters.zone.length && !zonesOf(c).some((z) => filters.zone.includes(z))) return false;
    if (filters.contract.length && !filters.contract.includes(c.contract_type === "salary" ? "Salaried" : "Freelancer")) return false;
    return true;
  }).sort(SORTERS[sortBy] || SORTERS["rate-desc"]);

  const toggleSelect = (id) => setSelected((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);
  const allSelected = filtered.length > 0 && filtered.every((c) => selected.includes(c.id));
  const toggleAll = () => setSelected(allSelected ? [] : filtered.map((c) => c.id));

  const tierCounts = COURIER_ROWS.reduce((a, c) => {
    a[c.tier.key] = (a[c.tier.key] || 0) + 1; return a;
  }, {});
  const ratedCouriers = COURIER_ROWS.filter((c) => c.offloaded > 0);   // exclude no-data couriers from the fleet average
  const avgRate = ratedCouriers.length ? Math.round(ratedCouriers.reduce((a, c) => a + c.rate, 0) / ratedCouriers.length) : 0;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div className="banner" style={{ background: "var(--info-50)", borderColor: "var(--info-100)", color: "var(--info-700)" }}>
        <Icon name="info" size={15} color="var(--info-700)" />
        <div style={{ fontSize: 12.5 }}>
          {window.t("Courier numbers come from the client courier reports uploaded on the Overview page. Direct per-courier entry is planned.")}
        </div>
      </div>
      <div className="kpi-row">
        <KPI label="Active couriers"   value={COURIER_ROWS.length}                        sub={`${COURIER_ROWS.filter(c => c.registered).length} registered · ${COURIER_ROWS.filter(c => !c.registered).length} unregistered`} icon="truck" tint="var(--b50)" accent="var(--b600)" />
        <KPI label="Avg delivery rate" value={`${avgRate}%`}                              sub="weighted across fleet" icon="trend" tint="var(--good-50)" accent="var(--good-700)" tone={avgRate >= 75 ? "good" : ""} />
        <KPI label="Elite / Star"      value={`${(tierCounts.elite || 0) + (tierCounts.star || 0)}`} sub={`${tierCounts.elite || 0} Elite · ${tierCounts.star || 0} Star`} icon="trophy" tint="var(--warn-50)" accent="var(--warn-700)" />
        <KPI label="Needs support"     value={tierCounts.needs || 0}                       sub="below 70% rate · escalate" icon="alert" tint="var(--crit-50)" accent="var(--crit-700)" tone={(tierCounts.needs || 0) > 0 ? "bad" : ""} />
      </div>

      <div className="sec" data-tour="couriers">
        <h2>{window.t("Directory")} <span className="ct">{filtered.length}</span></h2>
        <div className="sec-right">
          <div className="global-search" style={{ width: 240, marginLeft: 0, padding: "5px 10px" }}>
            <Icon name="search" size={12} color="var(--muted-2)" />
            <input placeholder={window.t("Name, ID or zone…")} value={search} onChange={e => setSearch(e.target.value)} />
            {search &&
              <button className="search-clear" title={window.t("Clear")} onClick={() => setSearch("")} aria-label={window.t("Clear")}>
                <Icon name="x" size={12} color="var(--muted-2)" />
              </button>}
          </div>
          <FilterPopover
            groups={[
              { key: "client",   label: "Client",   options: clientFilterOptions },
              { key: "zone",     label: "Zone",     options: zoneFilterOptions },
              { key: "contract", label: "Contract", options: ["Salaried", "Freelancer"] },
            ]}
            value={filters}
            onChange={setFilters}
            onClear={() => setFilters({ client: [], zone: [], contract: [] })}
          />
          <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}
            style={{ border: "1px solid var(--border)", borderRadius: "var(--r-sm)", padding: "6px 9px", fontSize: 12, background: "var(--surface)", color: "var(--text)" }}>
            <option value="rate-desc">{window.t("Rate · high → low")}</option>
            <option value="rate-asc">{window.t("Rate · low → high")}</option>
            <option value="name">{window.t("Name A–Z")}</option>
            <option value="id">{window.t("Busco ID")}</option>
            <option value="delivered-desc">{window.t("Delivered · high → low")}</option>
            <option value="offloaded-desc">{window.t("Offloaded · high → low")}</option>
          </select>
          {selected.length > 0 &&
            <button className="btn sm" style={{ borderColor: "var(--crit-100)", color: "var(--crit-700)", background: "var(--crit-50)" }}
              onClick={() => setRemoveTargets(COURIER_ROWS.filter((c) => selected.includes(c.id)))}>
              <Icon name="trash" size={12} color="var(--crit-700)" /> {window.t("Delete")} ({selected.length})
            </button>
          }
          <ExportMenu onToast={onToast}
            getRows={() => ({
              rows: filtered.map((c) => ({
                "Busco ID": c.courier_code || "",
                Courier: c.name, Phone: c.phone || "",
                Zones: zonesOf(c).join(", "),
                Contract: c.contract_type === "salary" ? "Salaried" : "Freelancer",
                Clients: (c.clients || []).join(", "),
                Offloaded: c.offloaded, Delivered: c.delivered, Returned: c.returned,
                "Rate %": c.offloaded > 0 ? c.rate : "",
                Tier: c.tier.label,
              })),
              filename: `busco-couriers-${new Date().toISOString().slice(0, 10)}`,
            })} />
          <button className="btn primary sm" data-tour="add-courier" onClick={() => setDrawer({ mode: "add" })}>
            <Icon name="plus" size={12} color="#fff" /> {window.t("Add courier")}
          </button>
        </div>
      </div>

      <div className="tbl-wrap">
        <table className="data">
          <thead>
            <tr>
              <th style={{ width: 30 }}><input type="checkbox" checked={allSelected} onChange={toggleAll} style={{ cursor: "pointer" }} /></th>
              <th style={{ width: 32 }}>#</th>
              <th>{window.t("Courier")}</th>
              <th>{window.t("Phone")}</th>
              <th>{window.t("Zone")}</th>
              <th>{window.t("Contract")}</th>
              <th className="num">{window.t("Rate")}</th>
              <th className="num">{window.t("Off")}</th>
              <th className="num">{window.t("Del")}</th>
              <th className="num">{window.t("Ret")}</th>
              <th>{window.t("Rate")}</th>
              <th>{window.t("Tier")}</th>
              <th style={{ width: 70 }}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((c, i) => (
              <tr key={c.id} style={selected.includes(c.id) ? { backgroundColor: "var(--b50)" } : undefined}>
                <td><input type="checkbox" checked={selected.includes(c.id)} onChange={() => toggleSelect(c.id)} style={{ cursor: "pointer" }} /></td>
                <td className="mono muted">{i + 1}</td>
                <td>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div style={{ width: 26, height: 26, borderRadius: "var(--r-sm)", background: c.registered ? "var(--b50)" : "var(--canvas)", border: "1px solid " + (c.registered ? "var(--b100)" : "var(--border)"), display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, fontWeight: 700, color: c.registered ? "var(--b700)" : "var(--muted)" }}>
                      {c.name.split(" ").map(p => p[0]).slice(0, 2).join("")}
                    </div>
                    <div>
                      <div className="strong" style={{ fontSize: 12.5 }}>{c.name}</div>
                      {c.courier_code
                        ? <div className="mono" style={{ fontSize: 10, color: "var(--b700)" }}>{c.courier_code}</div>
                        : (!c.registered && <div style={{ fontSize: 10, color: "var(--muted-2)" }}>{window.t("Unregistered")}</div>)}
                    </div>
                  </div>
                </td>
                <td className="mono" style={{ fontSize: 11.5 }}>{c.phone ? <a href={`tel:${String(c.phone).replace(/\s+/g, "")}`} style={{ color: "var(--muted)" }} title={window.t("Call")}>{c.phone}</a> : <span className="muted-2">—</span>}</td>
                <td>
                  <div>{c.zones?.length ? c.zones.join(", ") : c.zone}</div>
                  {c.clients?.length > 0 && <div style={{ fontSize: 10, color: "var(--muted-2)" }}>{c.clients.join(", ")}</div>}
                </td>
                <td><ContractBadge type={c.contract_type} /></td>
                <td className="num">{c.contract_type === "freelancer"
                  ? (Object.values(c.client_meta || {}).some((m) => m && (m.rate_ppd || m.rate)) ? window.t("Per client") : (c.rate_per_parcel ? `${c.rate_per_parcel} / p` : "—"))
                  : `${fmtSAR(c.monthly_salary)} / mo`}</td>
                <td className="num">{fmtNum(c.offloaded)}</td>
                <td className="num">{fmtNum(c.delivered)}</td>
                <td className="num">{fmtNum(c.returned)}</td>
                <td>{c.offloaded > 0 ? <RateBadge r={c.rate} /> : <span className="muted-2">—</span>}</td>
                <td><TierBadge tier={c.tier} /></td>
                <td>
                  <div style={{ display: "flex", gap: 4 }}>
                    <button className="btn ghost sm" title="Edit" onClick={() => setDrawer({ mode: "edit", courier: c })}><Icon name="edit" size={12} /></button>
                    <button className="btn ghost sm" title="Remove" onClick={() => setRemoveTargets([c])}><Icon name="trash" size={12} color="var(--crit)" /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="sec">
        <h2>{window.t("Performance")} · {window.t(period === "Daily" ? "Last 7 days" : period === "Weekly" ? "Last 4 weeks" : "Last 6 months")}</h2>
        <div className="sec-right">
          <div className="segmented" title="Chart type">
            <button className={chartKind === "bars" ? "on" : ""} onClick={() => setChartKind("bars")} title="Bars (volume)">
              <Icon name="kanban" size={12} /> Bars
            </button>
            <button className={chartKind === "line" ? "on" : ""} onClick={() => setChartKind("line")} title="Line (rate trend)">
              <Icon name="trend" size={12} /> Line
            </button>
          </div>
          <Segmented options={["Daily", "Weekly", "Monthly"]} value={period} onChange={setPeriod} />
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
        {COURIER_ROWS.slice(0, 6).map(c => {
          // Real series from the courier's logged entries, bucketed by the
          // selected period: Daily = last 7 days, Weekly = last 4 weeks,
          // Monthly = last 6 months.
          const mine = (window.ENTRIES || []).filter((e) => e.courier === c.name);
          const today = new Date(); today.setHours(0, 0, 0, 0);
          const iso = (dt) => `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, "0")}-${String(dt.getDate()).padStart(2, "0")}`;
          const buckets = [];
          if (period === "Daily") {
            for (let i = 6; i >= 0; i--) {
              const d = new Date(today); d.setDate(d.getDate() - i);
              buckets.push({ p: `${d.getDate()}/${d.getMonth() + 1}`, from: iso(d), to: iso(d) });
            }
          } else if (period === "Weekly") {
            for (let i = 3; i >= 0; i--) {
              const end = new Date(today); end.setDate(end.getDate() - i * 7);
              const start = new Date(end); start.setDate(start.getDate() - 6);
              buckets.push({ p: i === 0 ? "Now" : `W-${i}`, from: iso(start), to: iso(end) });
            }
          } else {
            for (let i = 5; i >= 0; i--) {
              const d = new Date(today.getFullYear(), today.getMonth() - i, 1);
              const endM = new Date(today.getFullYear(), today.getMonth() - i + 1, 0);
              buckets.push({ p: d.toLocaleString("en-US", { month: "short" }), from: iso(d), to: iso(endM) });
            }
          }
          const data = buckets.map((b) => {
            let off = 0, del = 0;
            for (const e of mine) if (e.date >= b.from && e.date <= b.to) { off += e.offloaded; del += e.delivered; }
            return { p: b.p, off, del, ret: Math.max(0, off - del), rate: off > 0 ? Math.round((del / off) * 100) : 0 };
          });
          const active = data.filter((x) => x.off > 0);
          const trend = active.length >= 2 ? active[active.length - 1].rate - active[0].rate : 0;
          return (
            <div key={c.id} className="card">
              <div className="card-body" style={{ padding: 14 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</div>
                    <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{c.zone}</div>
                  </div>
                  <RateBadge r={c.rate} />
                </div>
                <div style={{ marginTop: 10, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                  <TierBadge tier={c.tier} />
                  {chartKind === "line" &&
                    <span className={"trend-chip " + (trend > 0 ? "up" : trend < 0 ? "dn" : "flat")}>
                      <Icon name={trend > 0 ? "trend" : trend < 0 ? "trend-down" : "arrow-right"} size={11} />
                      {trend > 0 ? "+" : ""}{trend}pp
                    </span>
                  }
                </div>
                <div style={{ height: 110, marginTop: 8 }}>
                  <ResponsiveContainer width="100%" height="100%">
                    {chartKind === "bars" ? (
                      <BarChart data={data} margin={{ top: 4, right: 4, left: -24, bottom: 0 }}>
                        <CartesianGrid strokeDasharray="3 3" stroke="var(--border-soft)" vertical={false} />
                        <XAxis dataKey="p" tick={{ ...tickStyle, fontSize: 10 }} axisLine={false} tickLine={false} />
                        <YAxis tick={{ ...tickStyle, fontSize: 10 }} axisLine={false} tickLine={false} width={32} />
                        <Tooltip contentStyle={tipStyle} />
                        <Bar dataKey="off" name="Off" fill="var(--warn)" radius={[2, 2, 0, 0]} />
                        <Bar dataKey="del" name="Del" fill="var(--good)" radius={[2, 2, 0, 0]} />
                        <Bar dataKey="ret" name="Ret" fill="var(--crit)" radius={[2, 2, 0, 0]} />
                      </BarChart>
                    ) : (
                      <LineChart data={data} margin={{ top: 6, right: 6, left: -24, bottom: 0 }}>
                        <CartesianGrid strokeDasharray="3 3" stroke="var(--border-soft)" vertical={false} />
                        <XAxis dataKey="p" tick={{ ...tickStyle, fontSize: 10 }} axisLine={false} tickLine={false} />
                        <YAxis tick={{ ...tickStyle, fontSize: 10 }} axisLine={false} tickLine={false} width={32} domain={[0, 100]} />
                        <Tooltip contentStyle={tipStyle} formatter={(v) => v + "%"} />
                        <ReferenceLine y={75} stroke="var(--crit)" strokeDasharray="3 3" />
                        <Line type="monotone" dataKey="rate" name="Rate"
                              stroke={trend < 0 ? "var(--crit)" : trend > 0 ? "var(--good)" : "var(--b500)"}
                              strokeWidth={2.5} dot={{ r: 3 }} />
                      </LineChart>
                    )}
                  </ResponsiveContainer>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {drawer &&
        <CourierDrawer
          mode={drawer.mode}
          courier={drawer.courier}
          onClose={() => setDrawer(null)}
          onToast={onToast}
        />
      }
      {removeTargets &&
        <DeleteCouriersModal
          targets={removeTargets}
          onClose={() => setRemoveTargets(null)}
          onDone={(n) => { setSelected([]); setRemoveTargets(null); onToast(`${n} courier${n > 1 ? "s" : ""} deleted`, "danger"); }}
          onToast={onToast}
        />
      }
    </div>
  );
}

// "Are you sure?" for courier deletion — single or bulk — with an optional
// checkbox to also wipe all their logged data, so re-adding them later
// starts with a completely clean history.
function DeleteCouriersModal({ targets, onClose, onDone, onToast }) {
  const [wipe, setWipe] = useState(false);
  const [busy, setBusy] = useState(false);

  const run = async () => {
    if (busy) return;
    setBusy(true);
    try {
      for (const c of targets) {
        if (wipe) await window.buscoDeleteCourierEntries(c);
        await window.buscoDeleteCourier(c.id);
      }
      await window.buscoLoadAllData();
      onDone(targets.length);
    } catch (e) {
      onToast(e?.message || "Delete failed", "danger");
      setBusy(false);
    }
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 470 }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div style={{ fontSize: 15, fontWeight: 700 }}>
            {targets.length === 1 ? `${window.t("Delete")} ${targets[0].name}?` : `${window.t("Delete")} ${targets.length} ${window.t("couriers?")}`}
          </div>
          <button className="close-x" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div className="modal-body">
          {targets.length > 1 &&
            <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 10, maxHeight: 90, overflowY: "auto" }}>
              {targets.map((c) => c.name).join(" · ")}
            </div>
          }
          <div style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.5 }}>
            {window.t("They will be removed from the directory. Their logged history stays in reports unless you tick the box below.")}
          </div>
          <label style={{ display: "flex", gap: 9, alignItems: "flex-start", marginTop: 14, padding: "10px 12px", border: "1px solid var(--crit-100)", background: "var(--crit-50)", borderRadius: "var(--r-sm)", cursor: "pointer" }}>
            <input type="checkbox" checked={wipe} onChange={(e) => setWipe(e.target.checked)} style={{ marginTop: 2, cursor: "pointer" }} />
            <span style={{ fontSize: 12, color: "var(--crit-700)" }}>
              <b>{window.t("Also delete all their logged data.")}</b> {window.t("Every entry tied to them is erased — if they're added again later, they start with no history. This can't be undone.")}
            </span>
          </label>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 16 }}>
            <button className="btn" onClick={onClose} disabled={busy}>{window.t("Cancel")}</button>
            <button className="btn" style={{ background: "var(--crit)", borderColor: "var(--crit)", color: "#fff" }} onClick={run} disabled={busy}>
              {busy ? <span className="spinner" /> : <Icon name="trash" size={12} color="#fff" />} {busy ? window.t("Deleting…") : window.t("Delete")}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function CourierDrawer({ mode = "add", courier, onClose, onToast }) {
  const editing = mode === "edit";
  const [name, setName] = useState(courier?.name || "");
  const [phone, setPhone] = useState(courier && courier.phone !== "—" ? courier.phone : "");
  const [clients, setClients] = useState(courier?.clients || []);
  const [zones, setZones] = useState(
    courier?.zones?.length ? courier.zones
      : (courier?.zone && courier.zone !== "—" ? courier.zone.split(",").map(s => s.trim()).filter(Boolean) : [])
  );
  const [type, setType] = useState(courier?.contract_type || "freelancer");
  const [rate, setRate] = useState(courier?.rate_per_parcel ?? "");
  const [salary, setSalary] = useState(courier?.monthly_salary ?? "");
  // Per-client data: the courier ID this client assigned them, and (for
  // freelancers working several clients) the per-client rate per parcel.
  const [clientMeta, setClientMeta] = useState(courier?.client_meta || {});
  const setMeta = (clientName, field, value) =>
    setClientMeta((m) => ({ ...m, [clientName]: { ...(m[clientName] || {}), [field]: value } }));

  // Busco ID is assigned automatically: BUS-xxx (salaried) / BSF-xxx (freelancer).
  const buscoId = editing ? (courier?.courier_code || "—") : window.buscoNextCourierCode(type);
  useEffect(() => { const esc = (e) => e.key === "Escape" && onClose(); document.addEventListener("keydown", esc); return () => document.removeEventListener("keydown", esc); }, [onClose]);

  const clientOptions = (window.CLIENTS || []).map(c => c.name);
  const zoneOptions = (() => {
    const fromClients = (window.CLIENTS || []).flatMap(c => c.cities.map(x => x.name));
    return [...new Set([...fromClients, ...zones])];
  })();

  const save = () => {
    const meta = {};
    for (const cn of clients) if (clientMeta[cn]) meta[cn] = clientMeta[cn];
    const payload = { name, code: editing ? courier?.courier_code : undefined, phone, clients, zones, type, rate, salary, clientMeta: meta };
    if (editing) { Store.updateCourier(courier.id, payload); onToast && onToast(`${name} updated`); }
    else { Store.addCourier(payload); onToast && onToast(`${name || "Courier"} added as ${buscoId}`); }
    onClose();
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="slide-panel" onClick={(e) => e.stopPropagation()}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600 }}>{editing ? window.t("Edit courier") : window.t("Add courier")}</h3>
            <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{editing ? `Update ${courier.name}’s details` : "Register a new courier to the directory"}</div>
          </div>
          <button className="close-x" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div style={{ padding: 22, display: "flex", flexDirection: "column", gap: 14, overflowY: "auto", flex: 1 }}>
          <div className="field-row c2">
            <div className="field"><label>{window.t("Full name")}</label><input autoFocus value={name} onChange={e => setName(e.target.value)} placeholder="Mohammed Al-…" /></div>
            <div className="field">
              <label>{window.t("Busco ID")} <span className="muted" style={{ textTransform: "none", fontWeight: 400 }}>{window.t("auto")}</span></label>
              <div className="mono" style={{ border: "1px dashed var(--border)", borderRadius: "var(--r-sm)", padding: "8px 11px", fontSize: 12.5, color: "var(--b700)", background: "var(--b50)" }}>{buscoId}</div>
            </div>
          </div>
          <div className="field"><label>{window.t("Phone")}</label><input value={phone} onChange={e => setPhone(e.target.value)} placeholder="+966 …" className="mono" /></div>
          <div className="field"><label>{window.t("Client")}</label><MultiSelect options={clientOptions} value={clients} onChange={setClients} placeholder={window.t("Select clients…")} /></div>
          <div className="field"><label>{window.t("Zone / area")}</label><MultiSelect options={zoneOptions} value={zones} onChange={setZones} placeholder={window.t("Select zones…")} /></div>

          {clients.length > 0 &&
            <div className="field">
              <label>{window.t("Per-client details")}</label>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {clients.map((cn) => (
                  <div key={cn} style={{ border: "1px solid var(--border)", borderRadius: "var(--r-sm)", padding: "10px 12px", background: "var(--surface-2)" }}>
                    <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 8 }}>{cn}</div>
                    <div className="field">
                      <label>{window.t("Courier ID at this client")}</label>
                      <input className="mono" value={clientMeta[cn]?.courier_id || ""} onChange={(e) => setMeta(cn, "courier_id", e.target.value)} placeholder="AJSA1004780" />
                    </div>
                    {type === "freelancer" &&
                      <div className="field-row c2" style={{ marginTop: 8 }}>
                        <div className="field">
                          <label>{window.t("PPD rate per parcel")}</label>
                          <input className="mono" type="number" step="0.001" value={clientMeta[cn]?.rate_ppd ?? clientMeta[cn]?.rate ?? ""} onChange={(e) => setMeta(cn, "rate_ppd", e.target.value)} placeholder="6.00" />
                        </div>
                        <div className="field">
                          <label>{window.t("COD rate per parcel")}</label>
                          <input className="mono" type="number" step="0.001" value={clientMeta[cn]?.rate_cod ?? ""} onChange={(e) => setMeta(cn, "rate_cod", e.target.value)} placeholder="7.00" />
                        </div>
                      </div>
                    }
                  </div>
                ))}
              </div>
              <div style={{ fontSize: 10.5, color: "var(--muted)", marginTop: 5 }}>{window.t("The client's courier ID is what their reports use — needed for the report upload to match couriers.")}</div>
            </div>
          }
          <div className="field">
            <label>{window.t("Contract type")}</label>
            <div className="segmented" style={{ width: "100%" }}>
              <button className={type === "freelancer" ? "on" : ""} onClick={() => setType("freelancer")} style={{ flex: 1 }}>{window.t("Freelancer")}</button>
              <button className={type === "salary" ? "on" : ""}     onClick={() => setType("salary")}     style={{ flex: 1 }}>{window.t("Salaried")}</button>
            </div>
          </div>
          {type === "freelancer" ? (
            <div style={{ fontSize: 11, color: "var(--muted)", padding: "2px 2px 0" }}>
              {window.t("Freelancer rates are set per client in the Per-client details above.")}
            </div>
          ) : (
            <div className="field"><label>{window.t("Monthly salary (SAR)")}</label><input className="mono" type="number" value={salary} onChange={e => setSalary(e.target.value)} placeholder="4200" /></div>
          )}
        </div>
        <div style={{ padding: 18, borderTop: "1px solid var(--border)", display: "flex", justifyContent: "flex-end", gap: 8 }}>
          <button className="btn" onClick={onClose}>{window.t("Cancel")}</button>
          <button className="btn primary" disabled={!name} onClick={save}>{editing ? "Save changes" : "Save courier"}</button>
        </div>
      </div>
    </div>
  );
}

// ── ALERTS & REWARDS ─────────────────────────────────────────
function AlertsScreen() {
  const critical = COURIER_ROWS.filter(c => c.offloaded > 0 && c.rate < 70);
  const warning  = COURIER_ROWS.filter(c => c.offloaded > 0 && c.rate >= 70 && c.rate < 75);
  const clientAlerts = CLIENT_ROWS.filter(c => c.offloaded > 0 && c.rate < 75);
  const top3 = COURIER_ROWS.slice(0, 3);

  const tierCounts = COURIER_ROWS.reduce((a, c) => {
    a[c.tier.key] = (a[c.tier.key] || 0) + 1; return a;
  }, {});
  const tierData = [
    { name: "Elite",    value: tierCounts.elite || 0, fill: "#EAB308" },
    { name: "Star",     value: tierCounts.star  || 0, fill: "#94A3B8" },
    { name: "Pro",      value: tierCounts.pro   || 0, fill: "#C2410C" },
    { name: "On Track", value: tierCounts.track || 0, fill: "var(--good)" },
    { name: "Needs",    value: tierCounts.needs || 0, fill: "var(--crit)" },
    { name: "No data",  value: tierCounts.nodata || 0, fill: "var(--muted-2)" },
  ].filter((t) => t.value > 0);
  const healthy = (tierCounts.elite || 0) + (tierCounts.star || 0) + (tierCounts.pro || 0) + (tierCounts.track || 0);
  const allClear = critical.length === 0 && warning.length === 0 && clientAlerts.length === 0;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <div className="kpi-row">
        <KPI label={window.t("Critical")} value={critical.length} sub={window.t("rate below 70%")} icon="alert" tint="var(--crit-50)" accent="var(--crit-700)" tone={critical.length > 0 ? "bad" : ""} />
        <KPI label={window.t("Warning")} value={warning.length} sub={window.t("rate 70–74%")} icon="alert-circle" tint="var(--warn-50)" accent="var(--warn-700)" />
        <KPI label={window.t("Client alerts")} value={clientAlerts.length} sub={window.t("client rate below 75%")} icon="building" tint="var(--info-50)" accent="var(--info-700)" />
        <KPI label={window.t("Healthy couriers")} value={healthy} sub={window.t("on track or better")} icon="check-circle" tint="var(--good-50)" accent="var(--good-700)" tone={healthy > 0 ? "good" : ""} />
      </div>

      {allClear &&
        <div className="banner" style={{ background: "var(--good-50)", borderColor: "var(--good-100)", color: "var(--good-700)" }}>
          <Icon name="check-circle" size={16} color="var(--good-700)" />
          <div><b>{window.t("All clear.")}</b> {window.t("No couriers or clients below target right now.")}</div>
        </div>
      }

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }} data-tour="alerts">
        <AlertCard
          tone="crit" icon="alert" title="Critical"
          subtitle="Rate below 70%"
          count={critical.length}
          rows={critical.map(c => ({ name: c.name, sub: c.zone, rate: c.rate, msg: "Pair with senior router · reduce daily load" }))}
        />
        <AlertCard
          tone="warn" icon="alert-circle" title="Warning"
          subtitle="Rate 70–74%"
          count={warning.length}
          rows={warning.map(c => ({ name: c.name, sub: c.zone, rate: c.rate, msg: "Monitor next 7 days · trend forming" }))}
        />
        <AlertCard
          tone="info" icon="building" title="Client alerts"
          subtitle="Client rate below 75%"
          count={clientAlerts.length}
          rows={clientAlerts.map(c => ({ name: c.name, sub: c.cities.map(x => x.name).join(", "), rate: c.rate, msg: "Reassign couriers · escalate to ops lead" }))}
        />
      </div>

      <div className="sec">
        <h2>{window.t("Top performers")} <span className="ct">3</span></h2>
        <div className="sec-right">
          <Icon name="trophy" size={14} color="var(--warn-600)" />
          <span className="muted" style={{ fontSize: 11.5 }}>All-time delivery rate · top 3</span>
        </div>
      </div>
      <div className="podium">
        <PodiumCard rank={2} c={top3[1]} />
        <PodiumCard rank={1} c={top3[0]} />
        <PodiumCard rank={3} c={top3[2]} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16 }}>
        <div className="tbl-wrap">
          <div className="tbl-head">
            <h3>{window.t("Full rankings · all couriers")}</h3>
            <span className="sub">Ordered by all-time rate</span>
          </div>
          <table className="data">
            <thead>
              <tr>
                <th style={{ width: 32 }}>#</th>
                <th>{window.t("Courier")}</th>
                <th>{window.t("Zone")}</th>
                <th>{window.t("Contract")}</th>
                <th>All-time</th>
                <th>7-day</th>
                <th className="num">{window.t("Delivered")}</th>
                <th>{window.t("Tier")}</th>
              </tr>
            </thead>
            <tbody>
              {COURIER_ROWS.map((c, i) => (
                <tr key={c.id}>
                  <td className="mono">{i + 1}</td>
                  <td className="strong">{c.name}</td>
                  <td className="muted">{c.zone}</td>
                  <td><ContractBadge type={c.contract_type} /></td>
                  <td>{c.offloaded > 0 ? <RateBadge r={c.rate} /> : <span className="muted-2">—</span>}</td>
                  <td>{c.offloaded > 0 ? <RateBadge r={c.rate7} /> : <span className="muted-2">—</span>}</td>
                  <td className="num">{fmtNum(c.delivered)}</td>
                  <td><TierBadge tier={c.tier} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="card">
          <div className="card-head">
            <div className="ch-l">
              <h3>{window.t("Fleet tier distribution")}</h3>
              <div className="ch-sub">{COURIER_ROWS.length} active couriers</div>
            </div>
          </div>
          <div className="card-body">
            <div style={{ height: 200 }}>
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie data={tierData} dataKey="value" nameKey="name" innerRadius={46} outerRadius={76} paddingAngle={2}>
                    {tierData.map((e, i) => <Cell key={i} fill={e.fill} />)}
                  </Pie>
                  <Tooltip contentStyle={tipStyle} />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 8 }}>
              {tierData.map((t, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 11.5 }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}>
                    <span className="dot" style={{ background: t.fill }} /> {t.name}
                  </span>
                  <span className="mono" style={{ fontWeight: 600 }}>{t.value}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function AlertCard({ tone, icon, title, subtitle, count, rows }) {
  const tones = {
    crit: { bg: "var(--crit-50)", bd: "var(--crit-100)", ct: "var(--crit-700)" },
    warn: { bg: "var(--warn-50)", bd: "var(--warn-100)", ct: "var(--warn-700)" },
    info: { bg: "var(--info-50)", bd: "var(--info-100)", ct: "var(--info-700)" },
    good: { bg: "var(--good-50)", bd: "var(--good-100)", ct: "var(--good-700)" },
  }[tone];

  return (
    <div style={{ background: tones.bg, border: `1px solid ${tones.bd}`, borderRadius: "var(--r-md)", padding: 14, display: "flex", flexDirection: "column", gap: 10 }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: "var(--r-sm)", background: "rgba(255,255,255,0.65)", display: "flex", alignItems: "center", justifyContent: "center", color: tones.ct }}>
            <Icon name={icon} size={16} color={tones.ct} />
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, color: tones.ct }}>{title}</div>
            <div style={{ fontSize: 11, color: tones.ct, opacity: 0.75 }}>{subtitle}</div>
          </div>
        </div>
        <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: tones.ct, lineHeight: 1 }}>{count}</div>
      </div>
      {rows.length === 0 ? (
        <div style={{ fontSize: 11.5, color: tones.ct, opacity: 0.7, padding: "8px 0" }}>{window.t("None in this category.")}</div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          {rows.map((r, i) => (
            <div key={i} style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-sm)", padding: "9px 11px" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <div style={{ fontSize: 12, fontWeight: 600 }}>{r.name}</div>
                <RateBadge r={r.rate} />
              </div>
              <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{r.sub}</div>
              <div style={{ fontSize: 11, color: tones.ct, marginTop: 4 }}>{r.msg}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function PodiumCard({ rank, c }) {
  if (!c) return <div />;
  return (
    <div className={"podium-card p" + rank}>
      <div className="rk">{rank}</div>
      <div className="label-tiny">Rank {rank}</div>
      <div style={{ fontSize: 16, fontWeight: 600, marginTop: 6, letterSpacing: "-0.01em" }}>{c.name}</div>
      <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{c.zone}</div>
      <div style={{ margin: "14px 0 10px" }}><RateBadge r={c.rate} size="lg" /></div>
      <TierBadge tier={c.tier} />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 12 }}>
        <div className="tile"><div className="tl">7-day</div><div className="tv" style={{ color: "var(--good-700)" }}>{c.rate7}%</div></div>
        <div className="tile"><div className="tl">{window.t("Entries")}</div><div className="tv">{c.runs}</div></div>
      </div>
    </div>
  );
}

Object.assign(window, { ClientsScreen, ClientDetailModal, CouriersScreen, AlertsScreen });
