/* global React */
// Admin Console — manage team members, Workable IDs, timezones, working hours,
// and weekend shift coverage windows. Has sub-tabs: Roster | Weekend Hours.

const { useState: useStateA, useMemo: useMemoA, useRef: useRefA } = React;

const TEAM_OPTIONS = ["L1", "L2", "Invoicing"];
const REGION_OPTIONS = ["EMEA", "APAC", "LATAM"];
const STATUS_OPTIONS = [
  { value: "working", label: "Working" },
  { value: "off",     label: "Time Off" },
];
const REASON_OPTIONS = ["Time Off", "WR", "Sick", "Holiday", "Parental", "Other"];
const TZ_SUGGESTIONS = [
  { code: "GMT",  label: "GMT — Greenwich Mean Time (UTC+0)" },
  { code: "WET",  label: "WET — Western European Time (UTC+0)" },
  { code: "CET",  label: "CET — Central European Time (UTC+1)" },
  { code: "EET",  label: "EET — Eastern European Time (UTC+2)" },
  { code: "MSK",  label: "MSK — Moscow Time (UTC+3)" },
  { code: "GST",  label: "GST — Gulf Standard Time (UTC+4)" },
  { code: "PKT",  label: "PKT — Pakistan Time (UTC+5)" },
  { code: "IST",  label: "IST — India Time (UTC+5:30)" },
  { code: "BST",  label: "BST — Bangladesh Time (UTC+6)" },
  { code: "ICT",  label: "ICT — Indochina Time (UTC+7)" },
  { code: "MYT",  label: "MYT — Malaysia Time (UTC+8)" },
  { code: "SGT",  label: "SGT — Singapore Time (UTC+8)" },
  { code: "CST_CN", label: "CST — China Standard Time (UTC+8)" },
  { code: "JST",  label: "JST — Japan Time (UTC+9)" },
  { code: "AEST", label: "AEST — Australian Eastern Time (UTC+10)" },
  { code: "NZST", label: "NZST — New Zealand Time (UTC+12)" },
  { code: "BRT",  label: "BRT — Brasília Time (UTC−3)" },
  { code: "ART",  label: "ART — Argentina Time (UTC−3)" },
  { code: "CLT",  label: "CLT — Chile Time (UTC−4)" },
  { code: "COT",  label: "COT — Colombia Time (UTC−5)" },
  { code: "ET",   label: "ET — US Eastern Time (UTC−5)" },
  { code: "MXT",  label: "MXT — Mexico City Time (UTC−6)" },
  { code: "PT",   label: "PT — US Pacific Time (UTC−8)" },
];
const SECTIONS = [
  { id: "roster",  label: "Roster" },
  { id: "weekend", label: "Weekend Shift Hours" },
  { id: "leaders", label: "Daily Call Leaders" },
];

function AdminConsole({ people, setPeople, leadHistory, setLeadHistory, onLogout }) {
  const [section, setSection] = useStateA("roster");

  const updatePerson = (origName, patch) => {
    setPeople(prev => prev.map(p => p.name === origName ? { ...p, ...patch } : p));
  };

  const counts = useMemoA(() => ({
    total: people.length,
    L1: people.filter(p => p.team === "L1").length,
    L2: people.filter(p => p.team === "L2").length,
    Invoicing: people.filter(p => p.team === "Invoicing").length,
    off: people.filter(p => p.status === "off").length,
    noWorkable: people.filter(p => !p.workableId).length,
  }), [people]);

  return (
    <div className="adm-root">
      <header className="adm-header">
        <div>
          <div className="adm-eyebrow">Admin</div>
          <h1 className="adm-title">
            {section === "roster"   ? "Team members" :
             section === "weekend"  ? "Weekend shift hours" :
                                       "Daily call leaders"}
          </h1>
          <nav className="adm-section-tabs">
            {SECTIONS.map(s => (
              <button key={s.id}
                className={section === s.id ? "is-active" : ""}
                onClick={() => setSection(s.id)}>
                {s.label}
              </button>
            ))}
          </nav>
        </div>

        {section === "roster" && (
          <div className="adm-stat-row">
            <Stat label="Total" value={counts.total} />
            <Stat label="L1"    value={counts.L1} />
            <Stat label="L2"    value={counts.L2} />
            <Stat label="Inv."  value={counts.Invoicing} />
            <Stat label="Off"   value={counts.off} tone="red" />
            <Stat label="No Workable ID" value={counts.noWorkable} tone={counts.noWorkable ? "amber" : "muted"} />
          </div>
        )}
      </header>

      {section === "roster"
        ? <RosterPanel people={people} setPeople={setPeople} updatePerson={updatePerson} />
        : section === "weekend"
          ? <WeekendHoursPanel people={people} updatePerson={updatePerson} setPeople={setPeople} />
          : <LeadersPanel people={people} leadHistory={leadHistory} setLeadHistory={setLeadHistory} />}

      <footer className="adm-footer">
        <span className="adm-footer-note">
          Changes are saved to your browser automatically. Use Export to back them up.
        </span>
        {onLogout && (
          <button className="adm-btn adm-btn-ghost adm-signout" onClick={onLogout}>
            Sign out
          </button>
        )}
      </footer>
    </div>
  );
}

/* ── Roster panel ─────────────────────────────────────────── */
function RosterPanel({ people, setPeople, updatePerson }) {
  const [query, setQuery] = useStateA("");
  const [teamFilter, setTeamFilter] = useStateA("All");
  const [confirmDelete, setConfirmDelete] = useStateA(null); // person object pending delete
  const [showIds, setShowIds] = useStateA(false);            // hide/show Workable IDs
  const fileInputRef = useRefA(null);

  const filtered = useMemoA(() => {
    const q = query.trim().toLowerCase();
    return people.filter(p => {
      if (teamFilter !== "All" && p.team !== teamFilter) return false;
      if (!q) return true;
      return (p.name + " " + (p.workableId || "") + " " + (p.region || "") + " " + (p.tz || ""))
        .toLowerCase().includes(q);
    });
  }, [people, query, teamFilter]);

  // Detect data problems: duplicate Workable IDs and duplicate names.
  const dupes = useMemoA(() => {
    const idMap = new Map();
    const nameMap = new Map();
    people.forEach(p => {
      const id = String(p.workableId || "").trim();
      if (id) { (idMap.get(id) || idMap.set(id, []).get(id)).push(p.name); }
      const nm = String(p.name || "").trim().toLowerCase();
      if (nm) { (nameMap.get(nm) || nameMap.set(nm, []).get(nm)).push(p.name); }
    });
    const dupIds = [...idMap.entries()].filter(([, names]) => names.length > 1)
      .map(([id, names]) => ({ id, names }));
    const dupNames = [...nameMap.entries()].filter(([, names]) => names.length > 1)
      .map(([, names]) => names[0]);
    return { dupIds, dupNames };
  }, [people]);

  const removePerson = (person) => {
    setConfirmDelete(person);
  };

  const confirmRemove = () => {
    if (!confirmDelete) return;
    const target = confirmDelete;
    setPeople(prev => prev.filter(p => (p.uid || p.name) !== (target.uid || target.name)));
    setConfirmDelete(null);
  };

  const addPerson = () => {
    const base = window.CSStore.withDefaults({
      uid: window.CSStore.genUid ? window.CSStore.genUid() : ("p_" + Date.now().toString(36) + "_" + Math.random().toString(36).slice(2, 8)),
      name: "New Member",
      team: "L1",
      region: "EMEA",
      tz: "CET",
      status: "working",
      shift: "off",
    });
    let n = 1; let candidate = base.name;
    const existing = new Set(people.map(p => p.name));
    while (existing.has(candidate)) { n += 1; candidate = `New Member ${n}`; }
    base.name = candidate;
    setPeople(prev => [...prev, base]);
    setTimeout(() => {
      const input = document.querySelector(`input[data-admin-name="${candidate}"]`);
      if (input) { input.focus(); input.select(); }
    }, 30);
  };

  const exportJson = () => {
    const blob = new Blob([JSON.stringify(people, null, 2)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `cs-roster-${new Date().toISOString().slice(0,10)}.json`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const importJson = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        const parsed = JSON.parse(ev.target.result);
        if (!Array.isArray(parsed)) throw new Error("Not an array");
        setPeople(parsed.map(window.CSStore.withDefaults));
      } catch (err) {
        alert("Import failed: " + err.message);
      }
    };
    reader.readAsText(file);
    e.target.value = "";
  };

  const resetToDefaults = () => {
    if (!confirm("Reset roster to the original spreadsheet defaults? Your edits will be lost.")) return;
    window.CSStore.resetPeople();
    setPeople(window.CSStore.loadPeople());
  };

  return (
    <>
      <div className="adm-toolbar">
        <input
          className="adm-search"
          type="search"
          placeholder="Search by name, Workable ID, region…"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
        <div className="adm-team-filter">
          {["All", ...TEAM_OPTIONS].map(t => (
            <button key={t}
              className={teamFilter === t ? "is-active" : ""}
              onClick={() => setTeamFilter(t)}>{t}</button>
          ))}
        </div>
        <div className="adm-toolbar-actions">
          <button className="adm-btn adm-btn-ghost" onClick={exportJson}>↓ Export</button>
          <button className="adm-btn adm-btn-ghost" onClick={() => fileInputRef.current?.click()}>↑ Import</button>
          <input type="file" accept="application/json" ref={fileInputRef} style={{ display: "none" }} onChange={importJson} />
          <button className="adm-btn adm-btn-primary" onClick={addPerson}>+ Add member</button>
        </div>
      </div>

      {(dupes.dupIds.length > 0 || dupes.dupNames.length > 0) && (
        <div className="adm-dupe-warning">
          <strong>⚠ Data issues detected:</strong>
          {dupes.dupIds.map(d => (
            <div key={d.id}>
              Workable ID <code>{d.id}</code> is shared by: {d.names.join(", ")} — each person needs a unique ID.
            </div>
          ))}
          {dupes.dupNames.length > 0 && (
            <div>
              Duplicate name(s): {dupes.dupNames.join(", ")} — rename so each is distinct (e.g. add a last initial).
            </div>
          )}
        </div>
      )}

      <div className="adm-table-wrap">
        <table className="adm-table">
          <thead>
            <tr>
              <th className="adm-th-name">Name</th>
              <th>Team</th>
              <th>Region</th>
              <th>Timezone</th>
              <th>Working hours</th>
              <th>
                <span className="adm-th-with-toggle">
                  Workable ID
                  <button
                    type="button"
                    className="adm-eye-btn"
                    onClick={() => setShowIds(s => !s)}
                    title={showIds ? "Hide IDs" : "Show IDs"}
                  >{showIds ? "🙈 Hide" : "👁 Show"}</button>
                </span>
              </th>
              <th title="Exclude from daily-call leader rotation">No lead</th>
              <th className="adm-th-actions"></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(p => (
              <tr key={p.uid || p.name}>
                <td className="adm-td-name">
                  <input
                    type="text"
                    value={p.name}
                    data-admin-name={p.name}
                    onChange={(e) => updatePerson(p.name, { name: e.target.value })}
                    className="adm-input adm-input-name"
                  />
                </td>
                <td>
                  <select
                    className="adm-input"
                    value={p.team}
                    onChange={(e) => updatePerson(p.name, { team: e.target.value })}>
                    {TEAM_OPTIONS.map(t => <option key={t} value={t}>{t}</option>)}
                  </select>
                </td>
                <td>
                  <select
                    className="adm-input"
                    value={p.region || ""}
                    onChange={(e) => updatePerson(p.name, { region: e.target.value })}>
                    {REGION_OPTIONS.map(r => <option key={r} value={r}>{r}</option>)}
                  </select>
                </td>
                <td>
                  <select
                    className="adm-input adm-input-tz"
                    value={p.tz || ""}
                    onChange={(e) => updatePerson(p.name, { tz: e.target.value })}
                  >
                    {!TZ_SUGGESTIONS.some(t => t.code === p.tz) && p.tz && (
                      <option value={p.tz}>{p.tz}</option>
                    )}
                    {TZ_SUGGESTIONS.map(t => <option key={t.code} value={t.code}>{t.label}</option>)}
                  </select>
                </td>
                <td>
                  <input
                    type="text"
                    className="adm-input adm-input-mono"
                    placeholder="09:00–17:00"
                    value={p.hours || ""}
                    onChange={(e) => updatePerson(p.name, { hours: e.target.value })}
                  />
                </td>
                <td>
                  <input
                    type={showIds ? "text" : "password"}
                    className="adm-input adm-input-mono"
                    placeholder="(unset)"
                    value={p.workableId || ""}
                    onChange={(e) => updatePerson(p.name, { workableId: e.target.value })}
                    autoComplete="off"
                  />
                </td>
                <td className="adm-td-nolead">
                  <input
                    type="checkbox"
                    className="adm-nolead-check"
                    checked={!!p.excludeFromLead}
                    title={p.excludeFromLead ? "Excluded from leader rotation" : "Eligible to lead"}
                    onChange={(e) => updatePerson(p.name, { excludeFromLead: e.target.checked })}
                  />
                </td>
                <td className="adm-td-actions">
                  <button className="adm-row-del" onClick={() => removePerson(p)} title="Remove">✕</button>
                </td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={9} className="adm-empty">No members match your filters.</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {confirmDelete && (
        <div className="adm-modal-backdrop" onClick={() => setConfirmDelete(null)}>
          <div className="adm-modal" role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()}>
            <h3 className="adm-modal-title">Remove team member?</h3>
            <p className="adm-modal-body">
              <strong>{confirmDelete.name}</strong> will be removed from the roster.
              This change syncs to all users immediately. You can re-add them later by clicking <em>+ Add member</em>.
            </p>
            <div className="adm-modal-actions">
              <button className="adm-btn adm-btn-ghost" onClick={() => setConfirmDelete(null)}>Cancel</button>
              <button className="adm-btn adm-btn-danger" onClick={confirmRemove}>Remove {confirmDelete.name}</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

/* ── Weekend Hours panel ──────────────────────────────────── */
function WeekendHoursPanel({ people, updatePerson, setPeople }) {
  const [windows, setWindows] = useStateA(() => window.CSStore.loadWeekendWindows());
  const [savedFlash, setSavedFlash] = useStateA(false);

  const GROUPS = [
    { id: "APAC",  label: "APAC",  desc: "L1 · Asia-Pacific" },
    { id: "EMEA",  label: "EMEA",  desc: "L1 · Europe / MEA" },
    { id: "LATAM", label: "LATAM", desc: "L1 · Latin America" },
  ];

  const l2People = useMemoA(() => people.filter(p => p.team === "L2"), [people]);

  const TIME_OPTIONS = useMemoA(() => {
    const out = [];
    for (let h = 0; h <= 24; h++) {
      out.push(`${String(h).padStart(2, "0")}:00`);
      if (h < 24) out.push(`${String(h).padStart(2, "0")}:30`);
    }
    return out;
  }, []);

  const flash = () => { setSavedFlash(true); setTimeout(() => setSavedFlash(false), 1400); };

  const setWindow = (groupId, patch) => {
    setWindows(prev => {
      const next = { ...prev, [groupId]: { ...prev[groupId], ...patch } };
      window.CSStore.saveWeekendWindows(next);
      flash();
      return next;
    });
  };

  const setL2Hours = (name, patch) => {
    const person = people.find(p => p.name === name);
    const cur = person?.weekendShift || { start: "08:00", end: "20:00" };
    updatePerson(name, { weekendShift: { ...cur, ...patch } });
    flash();
  };

  const resetDefaults = () => {
    if (!confirm("Reset L1 weekend coverage windows to defaults?\n\nAPAC 00:00–08:00, EMEA 08:00–16:00, LATAM 16:00–24:00")) return;
    const defaults = {
      APAC:  { start: "00:00", end: "08:00" },
      EMEA:  { start: "08:00", end: "16:00" },
      LATAM: { start: "16:00", end: "24:00" },
      L2:    { start: "08:00", end: "20:00" },
    };
    setWindows(defaults);
    window.CSStore.saveWeekendWindows(defaults);
    flash();
  };

  return (
    <>
      <div className="adm-toolbar">
        <div className="adm-wh-title">
          <strong>Weekend coverage windows</strong>
          <span className={`adm-wh-saved ${savedFlash ? "is-flashing" : ""}`}>● Saved</span>
        </div>
        <div className="adm-toolbar-actions">
          <button className="adm-btn adm-btn-ghost" onClick={resetDefaults}>↺ Reset L1 to defaults</button>
        </div>
      </div>

      <div className="adm-wh-info">
        <strong>All times in UTC.</strong> L1 regions share one team-wide window each.
        L2 members each have their own weekend hours (set below). These draw the bars on the Weekend Schedule timeline.
      </div>

      <h3 className="adm-wh-section-title">L1 — region windows</h3>
      <div className="adm-wh-windows">
        {GROUPS.map(g => {
          const w = windows[g.id] || { start: "00:00", end: "08:00" };
          return (
            <section key={g.id} className="adm-wh-window-card">
              <div className="adm-wh-window-head">
                <h3 className={`adm-wh-region adm-wh-region-${g.id.toLowerCase()}`}>{g.label}</h3>
                <span className="adm-wh-window-desc">{g.desc}</span>
              </div>
              <div className="adm-wh-window-times">
                <label>
                  <span>Start (UTC)</span>
                  <select value={w.start} onChange={(e) => setWindow(g.id, { start: e.target.value })}>
                    {TIME_OPTIONS.map(t => <option key={t} value={t}>{t}</option>)}
                  </select>
                </label>
                <span className="adm-wh-window-dash">→</span>
                <label>
                  <span>End (UTC)</span>
                  <select value={w.end} onChange={(e) => setWindow(g.id, { end: e.target.value })}>
                    {TIME_OPTIONS.map(t => <option key={t} value={t}>{t}</option>)}
                  </select>
                </label>
              </div>
            </section>
          );
        })}
      </div>

      <h3 className="adm-wh-section-title">L2 — per-person hours</h3>
      <div className="adm-wh-windows">
        {l2People.map(p => {
          const w = p.weekendShift || { start: "08:00", end: "20:00" };
          return (
            <section key={p.uid || p.name} className="adm-wh-window-card">
              <div className="adm-wh-window-head">
                <h3 className="adm-wh-region adm-wh-region-l2">{p.name}</h3>
                <span className="adm-wh-window-desc">{p.tz} · {p.region}</span>
              </div>
              <div className="adm-wh-window-times">
                <label>
                  <span>Start (UTC)</span>
                  <select value={w.start} onChange={(e) => setL2Hours(p.name, { start: e.target.value })}>
                    {TIME_OPTIONS.map(t => <option key={t} value={t}>{t}</option>)}
                  </select>
                </label>
                <span className="adm-wh-window-dash">→</span>
                <label>
                  <span>End (UTC)</span>
                  <select value={w.end} onChange={(e) => setL2Hours(p.name, { end: e.target.value })}>
                    {TIME_OPTIONS.map(t => <option key={t} value={t}>{t}</option>)}
                  </select>
                </label>
              </div>
            </section>
          );
        })}
      </div>
    </>
  );
}

function PersonShiftCard({ person, onChange }) {
  const ws = person.weekendShift || { start: "09:00", end: "17:00" };
  const { startFrac, widthFrac } = computeFractions(ws.start, ws.end);

  return (
    <div className="adm-wh-card">
      <div className="adm-wh-card-name">
        <span className="mc-avatar mc-avatar-weekend">{person.name[0]}</span>
        <div>
          <div className="adm-wh-name">{person.name}</div>
          <div className="adm-wh-meta">{person.team}{person.region ? ` · ${person.region}` : ""} · {person.tz}</div>
        </div>
      </div>
      <div className="adm-wh-fields">
        <label>
          <span>Start</span>
          <input
            type="time"
            className="adm-input adm-input-mono"
            value={ws.start || ""}
            onChange={(e) => onChange({ start: e.target.value })}
          />
        </label>
        <span className="adm-wh-sep">→</span>
        <label>
          <span>End</span>
          <input
            type="time"
            className="adm-input adm-input-mono"
            value={ws.end || ""}
            onChange={(e) => onChange({ end: e.target.value })}
          />
        </label>
      </div>
      <MiniTimeline startFrac={startFrac} widthFrac={widthFrac} region={person.region || person.team} />
    </div>
  );
}

function MiniTimeline({ startFrac, widthFrac, region }) {
  const ticks = [0, 6, 12, 18, 24];
  return (
    <div className="adm-wh-mini">
      <div className="adm-wh-mini-track">
        <div
          className={`adm-wh-mini-bar adm-wh-bar-${(region || "").toLowerCase()}`}
          style={{ left: `${startFrac * 100}%`, width: `${widthFrac * 100}%` }}
        />
      </div>
      <div className="adm-wh-mini-axis">
        {ticks.map(h => (
          <span key={h} className="adm-wh-mini-tick" style={{ left: `${(h/24)*100}%` }}>
            {String(h).padStart(2, "0")}
          </span>
        ))}
      </div>
    </div>
  );
}

function computeFractions(start, end) {
  const s = parseTime(start);
  const e = parseTime(end);
  if (s == null || e == null) return { startFrac: 0, widthFrac: 0 };
  const startFrac = s / 24;
  let widthFrac = (e - s) / 24;
  if (widthFrac < 0) widthFrac += 1; // wrap past midnight
  return { startFrac, widthFrac };
}

function parseTime(t) {
  if (!t) return null;
  const m = /^(\d{1,2}):(\d{2})$/.exec(t);
  if (!m) return null;
  const h = +m[1], mi = +m[2];
  return h + mi / 60;
}

function Stat({ label, value, tone = "default" }) {
  return (
    <div className={`adm-stat adm-stat-${tone}`}>
      <div className="adm-stat-num">{value}</div>
      <div className="adm-stat-label">{label}</div>
    </div>
  );
}

/* ── Daily Call Leaders panel ─────────────────────────────── */
function LeadersPanel({ people, leadHistory: leadHistoryProp, setLeadHistory: setLeadHistoryProp }) {
  const today = window.CS_DATA?.meta?.today?.iso || new Date().toISOString().slice(0, 10);
  const [dateIso, setDateIso] = useStateA(today);
  const [localHistory, setLocalHistory] = useStateA(() => window.CSLeadHistory.load());
  const history = leadHistoryProp !== undefined ? leadHistoryProp : localHistory;
  const [flash, setFlash] = useStateA(null);
  const timeOff = window.CS_DATA?.timeOff || [];

  // updater(prev) → next; persists to wherever (parent or localStorage)
  const updateHistory = (updater) => {
    if (setLeadHistoryProp) {
      setLeadHistoryProp(updater);
    } else {
      setLocalHistory(prev => {
        const next = typeof updater === "function" ? updater(prev) : updater;
        try {
          localStorage.setItem("cs_lead_history_v1", JSON.stringify(next));
        } catch {}
        return next;
      });
    }
  };

  const SCOPES = window.CSLeadGen.SCOPES;

  const shiftDate = (days) => setDateIso(window.CSLeadGen.shiftDate(dateIso, days));

  const handlePick = (scope) => {
    const res = window.CSLeadGen.pickLead(scope, dateIso, people, timeOff, history);
    if (!res.name) {
      alert(`No one is available for ${scope} on ${dateIso}.`);
      return;
    }
    updateHistory(prev => ({ ...prev, [`${dateIso}__${scope}`]: res.name }));
    setFlash({ scope, reason: res.reason });
    setTimeout(() => setFlash(null), 2000);
  };

  const handleManual = (scope, name) => {
    updateHistory(prev => {
      const next = { ...prev };
      const key = `${dateIso}__${scope}`;
      if (name) next[key] = name;
      else delete next[key];
      return next;
    });
  };

  const handleClear = (scope) => {
    updateHistory(prev => {
      const next = { ...prev };
      delete next[`${dateIso}__${scope}`];
      return next;
    });
  };

  const resetAll = () => {
    if (!confirm("Reset the entire lead history? Manual overrides will be lost.")) return;
    updateHistory({ ...(window.CS_DATA?.leadsHistory || {}) });
  };

  // Last 7 days summary
  const recent = useMemoA(() => {
    const days = [];
    for (let i = -3; i <= 6; i++) {
      const d = window.CSLeadGen.shiftDate(dateIso, i);
      days.push(d);
    }
    return days;
  }, [dateIso]);

  return (
    <>
      <div className="adm-leaders-bar">
        <label className="adm-leaders-date">
          <span>Date</span>
          <input
            type="date"
            className="adm-input adm-input-mono"
            value={dateIso}
            onChange={(e) => setDateIso(e.target.value)}
          />
        </label>
        <div className="adm-leaders-nav">
          <button className="adm-btn adm-btn-ghost" onClick={() => shiftDate(-1)}>‹ Prev</button>
          <button className="adm-btn adm-btn-ghost" onClick={() => setDateIso(today)}>Today</button>
          <button className="adm-btn adm-btn-ghost" onClick={() => shiftDate(1)}>Next ›</button>
        </div>
        <div className="adm-toolbar-actions">
          <button className="adm-btn adm-btn-ghost" onClick={resetAll}>↺ Reset history</button>
        </div>
      </div>

      <div className="adm-leaders-cards">
        {SCOPES.map(scope => {
          const current = history[`${dateIso}__${scope}`] || null;
          const eligible = window.CSLeadGen.eligibleFor(scope, dateIso, people, timeOff, history);
          const allInScope = people.filter(p =>
            window.CSLeadGen.SCOPE_REGIONS[scope].has(p.region) &&
            (p.team === "L1" || p.team === "L2")
          );
          const skipped = allInScope.length - eligible.length;
          const isFlashing = flash?.scope === scope;
          const relaxed = isFlashing && flash.reason === "empty_relaxed";

          return (
            <section key={scope} className={`adm-leader-card ${isFlashing ? "is-flashing" : ""}`}>
              <header className="adm-leader-head">
                <div>
                  <div className="adm-leader-scope">{scope}</div>
                  <div className="adm-leader-date">{dateIso}</div>
                </div>
                {current && (
                  <button className="adm-leader-clear" onClick={() => handleClear(scope)} title="Clear assignment">✕</button>
                )}
              </header>

              <div className="adm-leader-current">
                {current ? (
                  <>
                    <span className="mc-avatar mc-avatar-lead adm-leader-avatar">{current[0]}</span>
                    <div className="adm-leader-name">
                      <div>{current}</div>
                      {relaxed && (
                        <div className="adm-leader-warn">
                          ⚠ Picked from relaxed pool (no strictly-eligible person)
                        </div>
                      )}
                    </div>
                  </>
                ) : (
                  <div className="adm-leader-empty">Not assigned</div>
                )}
              </div>

              <div className="adm-leader-actions">
                <button className="adm-btn adm-btn-primary adm-leader-pick" onClick={() => handlePick(scope)}>
                  🎲 {current ? "Re-pick" : "Pick"} random
                </button>
                <select
                  className="adm-input"
                  value={current || ""}
                  onChange={(e) => handleManual(scope, e.target.value)}
                >
                  <option value="">— manual override —</option>
                  {allInScope.map(p => (
                    <option key={p.name} value={p.name}>
                      {p.name}{eligible.find(e => e.name === p.name) ? "" : "  (ineligible)"}
                    </option>
                  ))}
                </select>
              </div>

              <div className="adm-leader-stats">
                <div>
                  <strong>{eligible.length}</strong>
                  <span>eligible</span>
                </div>
                <div>
                  <strong>{skipped}</strong>
                  <span>skipped</span>
                </div>
                <div>
                  <strong>{allInScope.length}</strong>
                  <span>in scope</span>
                </div>
              </div>

              {eligible.length > 0 && (
                <details className="adm-leader-details">
                  <summary>Pool ({eligible.length})</summary>
                  <div className="adm-leader-pool">
                    {eligible.map(p => (
                      <span key={p.name} className="adm-leader-chip">{p.name}</span>
                    ))}
                  </div>
                </details>
              )}
            </section>
          );
        })}
      </div>

      <section className="adm-leader-history">
        <h3>Recent assignments</h3>
        <div className="adm-history-grid">
          {recent.map(d => (
            <div key={d} className={`adm-history-day ${d === dateIso ? "is-active" : ""}`}>
              <div className="adm-history-date" onClick={() => setDateIso(d)}>{d}</div>
              {SCOPES.map(s => {
                const n = history[`${d}__${s}`];
                return (
                  <div key={s} className="adm-history-cell">
                    <span className="adm-history-scope">{s.replace("EMEA + APAC", "EU+AP")}</span>
                    <span className={`adm-history-name ${n ? "" : "is-empty"}`}>
                      {n || "—"}
                    </span>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </section>
    </>
  );
}

window.AdminConsole = AdminConsole;
window.computeShiftFractions = computeFractions;
window.parseShiftTime = parseTime;
