// ─────────────────────────────────────────────────────────────────
//  Accounts — admin management of the Organization → School → Counselor
//  hierarchy. Drill down from all organizations → a district's schools →
//  a school's counselors → one counselor's engagement detail. Search is
//  global (jumps straight to matching counselors). Admins can add/edit
//  districts, schools and counselors; every level shows rolled-up
//  engagement derived from the counselor records.
// ─────────────────────────────────────────────────────────────────

function AccountsView() {
  const orgs = window.useOrgs();
  const { Avatar } = window.UI;
  const I = window.I;

  const [drill, setDrill] = useState({ districtId: null, schoolId: null }); // level state
  const [query, setQuery] = useState("");
  const [typeFilter, setTypeFilter] = useState("all"); // all | district | school (root only)

  const [orgModal, setOrgModal] = useState(null);        // { kind:'district'|'school', data?, lockDistrict? }
  const [counselorModal, setCounselorModal] = useState(null); // { data? , lockSchool? }
  const [viewing, setViewing] = useState(null);          // counselor being inspected

  // ── lookups ──────────────────────────────────────────────────────────
  const districtById = Object.fromEntries(orgs.districts.map(d => [d.id, d]));
  const schoolById = Object.fromEntries(orgs.schools.map(s => [s.id, s]));
  const schoolsOfDistrict = (did) => orgs.schools.filter(s => s.districtId === did);
  const counselorsOfSchool = (sid) => orgs.counselors.filter(c => c.schoolId === sid);
  const counselorsInDistrict = (did) =>
    orgs.counselors.filter(c => schoolById[c.schoolId] && schoolById[c.schoolId].districtId === did);

  // organization = a district OR a standalone school (districtId === null)
  const standaloneSchools = orgs.schools.filter(s => !s.districtId);
  const orgRows = [
    ...orgs.districts.map(d => ({
      kind: "district", id: d.id, name: d.name, region: d.region,
      schoolCount: schoolsOfDistrict(d.id).length,
      counselors: counselorsInDistrict(d.id),
    })),
    ...standaloneSchools.map(s => ({
      kind: "school", id: s.id, name: s.name, region: "Independent school",
      schoolCount: 1, counselors: counselorsOfSchool(s.id),
    })),
  ];

  // organization name for a counselor (district name, or the standalone school name)
  const orgNameForSchool = (sid) => {
    const s = schoolById[sid]; if (!s) return "—";
    return s.districtId ? (districtById[s.districtId]?.name || "—") : s.name;
  };

  // ── global search ──────────────────────────────────────────────────────
  const q = query.trim().toLowerCase();
  const searchHits = q
    ? orgs.counselors.filter(c =>
        c.name.toLowerCase().includes(q) ||
        c.email.toLowerCase().includes(q) ||
        (schoolById[c.schoolId]?.name || "").toLowerCase().includes(q) ||
        orgNameForSchool(c.schoolId).toLowerCase().includes(q))
    : null;

  // ── contextual add ───────────────────────────────────────────────────
  const addButton = (() => {
    if (drill.schoolId) return { label: "Add counselor", fn: () => setCounselorModal({ lockSchool: drill.schoolId }) };
    if (drill.districtId) return { label: "Add school", fn: () => setOrgModal({ kind: "school", lockDistrict: drill.districtId }) };
    return { label: "Add organization", fn: () => setOrgModal({ kind: "district" }) };
  })();

  const curDistrict = drill.districtId ? districtById[drill.districtId] : null;
  const curSchool = drill.schoolId ? schoolById[drill.schoolId] : null;

  // subtitle for the top bar
  const totalCounselors = orgs.counselors.length;
  const subtitle = `${orgs.districts.length} districts · ${orgs.schools.length} schools · ${totalCounselors} counselors`;

  return (
    <>
      <window.TopBar
        title="Accounts"
        subtitle={subtitle}
        right={
          <button onClick={addButton.fn} style={btnDark}>
            <I.Plus size={13} sw={2.5} /> {addButton.label}
          </button>
        }
      />

      <div style={{ padding: 32, display: "flex", flexDirection: "column", gap: 20 }}>
        {/* Breadcrumb + search */}
        <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
          <Crumbs
            items={[
              { label: "All accounts", onClick: () => setDrill({ districtId: null, schoolId: null }) },
              curDistrict && { label: curDistrict.name, onClick: () => setDrill({ districtId: curDistrict.id, schoolId: null }) },
              curSchool && { label: curSchool.name, onClick: () => {} },
            ].filter(Boolean)}
          />
          <div style={{ flex: 1 }} />
          <div style={{ position: "relative", width: 300, maxWidth: "50vw" }}>
            <I.Search size={14} stroke="var(--ink-3)" style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)" }} />
            <input
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Search all counselors, schools, orgs…"
              style={{ width: "100%", padding: "9px 12px 9px 34px", border: "1px solid var(--line-2)", borderRadius: 8, fontSize: 13, background: "var(--card)" }}
            />
            {query && (
              <button onClick={() => setQuery("")} style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)", padding: 4 }}>
                <I.X size={14} stroke="var(--ink-3)" />
              </button>
            )}
          </div>
        </div>

        {/* GLOBAL SEARCH RESULTS */}
        {searchHits ? (
          <CounselorTable
            rows={searchHits}
            schoolById={schoolById}
            orgNameForSchool={orgNameForSchool}
            showLocation
            emptyText={`No counselors match “${query}”.`}
            onOpen={setViewing}
          />
        ) : !drill.districtId && !drill.schoolId ? (
          /* ROOT — organizations */
          <>
            <StatRow r={window.rollup(orgs.counselors)} extra={[{ label: "Organizations", value: orgRows.length }]} lead />
            <div style={{ display: "flex", gap: 6, background: "var(--bg-2)", padding: 4, borderRadius: 9, border: "1px solid var(--line)", width: "fit-content" }}>
              {[["all", "All accounts"], ["district", "Districts"], ["school", "Standalone schools"]].map(([id, label]) => {
                const active = typeFilter === id;
                return (
                  <button key={id} onClick={() => setTypeFilter(id)} style={{ padding: "7px 14px", borderRadius: 6, background: active ? "var(--card)" : "transparent", color: active ? "var(--ink)" : "var(--ink-3)", fontSize: 12.5, fontWeight: 500, boxShadow: active ? "0 1px 2px rgba(0,0,0,0.06)" : "none" }}>
                    {label}
                  </button>
                );
              })}
            </div>
            <OrgTable
              rows={orgRows.filter(r => typeFilter === "all" || r.kind === typeFilter)}
              onOpen={(r) => r.kind === "district" ? setDrill({ districtId: r.id, schoolId: null }) : setDrill({ districtId: null, schoolId: r.id })}
              onEdit={(r) => r.kind === "district"
                ? setOrgModal({ kind: "district", data: districtById[r.id] })
                : setOrgModal({ kind: "school", data: schoolById[r.id] })}
            />
          </>
        ) : drill.districtId && !drill.schoolId ? (
          /* DISTRICT — schools */
          <>
            <StatRow r={window.rollup(counselorsInDistrict(drill.districtId))} extra={[{ label: "Schools", value: schoolsOfDistrict(drill.districtId).length }]} lead
              action={{ label: "Edit district", fn: () => setOrgModal({ kind: "district", data: curDistrict }) }} />
            <SchoolTable
              rows={schoolsOfDistrict(drill.districtId).map(s => ({ school: s, counselors: counselorsOfSchool(s.id) }))}
              onOpen={(s) => setDrill({ districtId: drill.districtId, schoolId: s.id })}
              onEdit={(s) => setOrgModal({ kind: "school", data: s, lockDistrict: drill.districtId })}
            />
          </>
        ) : (
          /* SCHOOL — counselors */
          <>
            <StatRow r={window.rollup(counselorsOfSchool(drill.schoolId))} lead
              action={{ label: "Edit school", fn: () => setOrgModal({ kind: "school", data: curSchool, lockDistrict: curSchool.districtId }) }} />
            <CounselorTable
              rows={counselorsOfSchool(drill.schoolId)}
              schoolById={schoolById}
              orgNameForSchool={orgNameForSchool}
              emptyText="No counselors at this school yet. Add one to get started."
              onOpen={setViewing}
            />
          </>
        )}
      </div>

      {orgModal && (
        <OrgModal
          {...orgModal}
          districts={orgs.districts}
          onClose={() => setOrgModal(null)}
        />
      )}
      {counselorModal && (
        <CounselorModal
          {...counselorModal}
          schools={orgs.schools}
          districtById={districtById}
          schoolById={schoolById}
          orgNameForSchool={orgNameForSchool}
          onClose={() => setCounselorModal(null)}
        />
      )}
      {viewing && (
        <CounselorDetail
          counselor={orgs.counselors.find(c => c.id === viewing.id) || viewing}
          schoolById={schoolById}
          orgNameForSchool={orgNameForSchool}
          onEdit={() => { setCounselorModal({ data: viewing }); setViewing(null); }}
          onDelete={() => { window.deleteCounselor(viewing.id); setViewing(null); }}
          onClose={() => setViewing(null)}
        />
      )}
    </>
  );
}

// ── Breadcrumb ────────────────────────────────────────────────────────────
function Crumbs({ items }) {
  const I = window.I;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13 }}>
      {items.map((it, i) => {
        const last = i === items.length - 1;
        return (
          <React.Fragment key={i}>
            {i > 0 && <I.ChevronRight size={13} stroke="var(--ink-4)" />}
            <button onClick={it.onClick} disabled={last} style={{ fontSize: 13, fontWeight: last ? 600 : 500, color: last ? "var(--ink)" : "var(--ink-3)", cursor: last ? "default" : "pointer" }}>
              {it.label}
            </button>
          </React.Fragment>
        );
      })}
    </div>
  );
}

// ── Roll-up stat cards ──────────────────────────────────────────────────
function StatRow({ r, extra = [], lead, action }) {
  const cards = [
    ...extra,
    { label: "Counselors", value: r.count, sub: `${r.active} active` },
    { label: "Minutes (MTD)", value: r.minutesMTD.toLocaleString() },
    { label: "Resources shared", value: r.shares },
    { label: "Avg. completion", value: `${r.avgCompletion}%` },
  ];
  return (
    <div>
      {action && (
        <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 10 }}>
          <button onClick={action.fn} style={btnOutline}><window.I.Edit size={12} stroke="var(--ink-2)" /> {action.label}</button>
        </div>
      )}
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${cards.length}, 1fr)`, gap: 14 }}>
        {cards.map((c, i) => (
          <div key={i} style={{ padding: 18, background: "var(--card)", border: "1px solid var(--line)", borderRadius: "var(--radius)" }}>
            <div style={{ fontSize: 11.5, color: "var(--ink-3)", fontWeight: 500, letterSpacing: 0.02, textTransform: "uppercase" }}>{c.label}</div>
            <div className="serif" style={{ fontSize: 32, lineHeight: 1, letterSpacing: -0.015, marginTop: 10 }}>{c.value}</div>
            {c.sub && <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 6 }}>{c.sub}</div>}
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Organizations table (root) ─────────────────────────────────────────
function OrgTable({ rows, onOpen, onEdit }) {
  const I = window.I;
  const grid = "minmax(180px,1.6fr) 150px 90px 110px 130px 140px 90px";
  return (
    <TableShell grid={grid} head={["Organization", "Type", "Schools", "Counselors", "Minutes (MTD)", "Avg. completion", ""]}>
      {rows.map((r, i) => {
        const roll = window.rollup(r.counselors);
        return (
          <div key={r.id} className="nav-item" style={{ ...rowStyle(grid, i), cursor: "pointer" }} onClick={() => onOpen(r)}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
              <div style={{ width: 34, height: 34, borderRadius: 8, background: r.kind === "district" ? "var(--accent-soft)" : "var(--teal-soft)", color: r.kind === "district" ? "var(--accent-ink)" : "var(--teal-ink)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <I.Home size={16} stroke={r.kind === "district" ? "var(--accent-ink)" : "var(--teal-ink)"} />
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.region}</div>
              </div>
            </div>
            <div><Pill tone={r.kind === "district" ? "accent" : "teal"}>{r.kind === "district" ? "District" : "School"}</Pill></div>
            <div style={cellNum}>{r.kind === "district" ? r.schoolCount : "—"}</div>
            <div style={cellNum}>{roll.count} <span style={{ color: "var(--ink-4)" }}>· {roll.active} active</span></div>
            <div style={cellNum}>{roll.minutesMTD.toLocaleString()}</div>
            <div style={cell}><MiniBar pct={roll.avgCompletion} /></div>
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 6 }} onClick={e => e.stopPropagation()}>
              <button onClick={() => onEdit(r)} style={iconBtn}><I.Edit size={12} stroke="var(--ink-2)" /></button>
              <button onClick={() => onOpen(r)} style={iconBtn}><I.ChevronRight size={13} stroke="var(--ink-2)" /></button>
            </div>
          </div>
        );
      })}
    </TableShell>
  );
}

// ── Schools table (district level) ──────────────────────────────────────
function SchoolTable({ rows, onOpen, onEdit }) {
  const I = window.I;
  const grid = "minmax(180px,1.6fr) 120px 120px 130px 150px 90px";
  return (
    <TableShell grid={grid} head={["School", "Counselors", "Minutes (MTD)", "Resources shared", "Avg. completion", ""]}>
      {rows.map(({ school, counselors }, i) => {
        const roll = window.rollup(counselors);
        return (
          <div key={school.id} className="nav-item" style={{ ...rowStyle(grid, i), cursor: "pointer" }} onClick={() => onOpen(school)}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
              <div style={{ width: 32, height: 32, borderRadius: 7, background: "var(--bg-2)", border: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <I.Home size={15} stroke="var(--ink-3)" />
              </div>
              <div style={{ fontSize: 13.5, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{school.name}</div>
            </div>
            <div style={cellNum}>{roll.count} <span style={{ color: "var(--ink-4)" }}>· {roll.active}</span></div>
            <div style={cellNum}>{roll.minutesMTD.toLocaleString()}</div>
            <div style={cellNum}>{roll.shares}</div>
            <div style={cell}><MiniBar pct={roll.avgCompletion} /></div>
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 6 }} onClick={e => e.stopPropagation()}>
              <button onClick={() => onEdit(school)} style={iconBtn}><I.Edit size={12} stroke="var(--ink-2)" /></button>
              <button onClick={() => onOpen(school)} style={iconBtn}><I.ChevronRight size={13} stroke="var(--ink-2)" /></button>
            </div>
          </div>
        );
      })}
    </TableShell>
  );
}

// ── Counselors table (school level + search) ────────────────────────────
function CounselorTable({ rows, schoolById, orgNameForSchool, showLocation, emptyText, onOpen }) {
  const I = window.I;
  const { Avatar } = window.UI;
  const grid = showLocation
    ? "minmax(180px,1.4fr) minmax(160px,1.4fr) 110px 110px 110px 120px"
    : "minmax(200px,1.6fr) 100px 110px 110px 120px 120px";
  const head = showLocation
    ? ["Counselor", "School · Organization", "Minutes (MTD)", "Sessions", "Shares", "Status"]
    : ["Counselor", "Minutes (MTD)", "All-time min", "Sessions", "Shares", "Status"];
  if (!rows.length) {
    return <div style={{ padding: 40, textAlign: "center", color: "var(--ink-3)", fontSize: 13, background: "var(--card)", border: "1px solid var(--line)", borderRadius: "var(--radius)" }}>{emptyText}</div>;
  }
  return (
    <TableShell grid={grid} head={head}>
      {rows.map((c, i) => (
        <div key={c.id} className="nav-item" style={{ ...rowStyle(grid, i), cursor: "pointer" }} onClick={() => onOpen(c)}>
          <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
            <Avatar initials={window.initialsOf(c.name)} size={32} color={c.status === "active" ? "#2B8C8C" : "#8AADA0"} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{c.name}</div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.email}</div>
            </div>
          </div>
          {showLocation ? (
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 12.5, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{schoolById[c.schoolId]?.name || "—"}</div>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{orgNameForSchool(c.schoolId)}</div>
            </div>
          ) : (
            <div style={cellNum}>{c.minutesMTD}</div>
          )}
          <div style={cellNum}>{showLocation ? c.minutesMTD : c.minutesAllTime}</div>
          <div style={cellNum}>{c.sessions}/{window.ORG_TOTAL_SESSIONS}</div>
          <div style={cellNum}>{c.shares}</div>
          <div style={cell}><StatusPill status={c.status} /></div>
        </div>
      ))}
    </TableShell>
  );
}

// ── Counselor detail drawer ─────────────────────────────────────────────
function CounselorDetail({ counselor: c, schoolById, orgNameForSchool, onEdit, onDelete, onClose }) {
  const I = window.I;
  const { Avatar, Modal } = window.UI;
  const [confirmDel, setConfirmDel] = useState(false);
  const stats = [
    { label: "Minutes this month", value: c.minutesMTD },
    { label: "All-time minutes", value: c.minutesAllTime },
    { label: "Sessions completed", value: `${c.sessions} / ${window.ORG_TOTAL_SESSIONS}` },
    { label: "Resources shared", value: c.shares },
    { label: "Resources downloaded", value: c.downloads },
    { label: "Last active", value: c.lastActive },
  ];
  return (
    <Modal open onClose={onClose} width={560}>
      <div style={{ padding: 28 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <Avatar initials={window.initialsOf(c.name)} size={46} color={c.status === "active" ? "#2B8C8C" : "#8AADA0"} />
            <div>
              <h2 className="serif" style={{ fontSize: 24, margin: 0, letterSpacing: -0.015 }}>{c.name}</h2>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 3 }}>{schoolById[c.schoolId]?.name || "—"} · {orgNameForSchool(c.schoolId)}</div>
            </div>
          </div>
          <button onClick={onClose} style={{ padding: 6 }}><I.X size={18} stroke="var(--ink-3)" /></button>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 16, fontSize: 12.5, color: "var(--ink-2)" }}>
          <I.Mail size={14} stroke="var(--ink-3)" /> {c.email}
          <span style={{ marginLeft: "auto" }}><StatusPill status={c.status} /></span>
        </div>

        <div style={{ fontSize: 11, letterSpacing: 0.06, textTransform: "uppercase", color: "var(--ink-3)", fontWeight: 500, margin: "22px 0 10px" }}>Individual engagement</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
          {stats.map((s, i) => (
            <div key={i} style={{ padding: 14, background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: 9 }}>
              <div style={{ fontSize: 10.5, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: 0.03, fontWeight: 500 }}>{s.label}</div>
              <div style={{ fontSize: 19, fontWeight: 600, marginTop: 6, letterSpacing: -0.01 }}>{s.value}</div>
            </div>
          ))}
        </div>

        <div style={{ display: "flex", gap: 10, justifyContent: "space-between", marginTop: 24, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
          {confirmDel ? (
            <div style={{ display: "flex", alignItems: "center", gap: 10, flex: 1 }}>
              <span style={{ fontSize: 12.5, color: "var(--warn)" }}>Remove {c.name}?</span>
              <window.UI.Btn variant="outline" size="sm" onClick={() => setConfirmDel(false)}>Cancel</window.UI.Btn>
              <button onClick={onDelete} style={{ ...btnDark, background: "var(--warn)" }}>Remove account</button>
            </div>
          ) : (
            <>
              <button onClick={() => setConfirmDel(true)} style={{ ...btnOutline, color: "var(--warn)", borderColor: "var(--warn-soft)" }}><I.Trash size={12} stroke="var(--warn)" /> Remove</button>
              <button onClick={onEdit} style={btnDark}><I.Edit size={12} stroke="white" /> Edit counselor</button>
            </>
          )}
        </div>
      </div>
    </Modal>
  );
}

// ── Org (district / school) add-edit modal ──────────────────────────────
function OrgModal({ kind, data, lockDistrict, districts, onClose }) {
  const I = window.I;
  const isDistrict = kind === "district";
  const [name, setName] = useState(data?.name || "");
  const [region, setRegion] = useState(data?.region || "");
  const [districtId, setDistrictId] = useState(
    lockDistrict ?? data?.districtId ?? (isDistrict ? null : "__standalone")
  );

  const save = () => {
    if (!name.trim()) return;
    if (isDistrict) {
      window.upsertDistrict({ id: data?.id, name: name.trim(), region: region.trim() });
    } else {
      window.upsertSchool({
        id: data?.id,
        name: name.trim(),
        districtId: districtId === "__standalone" ? null : districtId,
      });
    }
    onClose();
  };

  return (
    <window.UI.Modal open onClose={onClose} width={520}>
      <div style={{ padding: 28 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <div style={labelCaps}>Accounts · {data ? "Edit" : "New"} {isDistrict ? "district" : "school"}</div>
            <h2 className="serif" style={{ fontSize: 24, margin: "6px 0 0", letterSpacing: -0.015 }}>{data ? name || "Untitled" : (isDistrict ? "New district" : "New school")}</h2>
          </div>
          <button onClick={onClose} style={{ padding: 6 }}><I.X size={18} stroke="var(--ink-3)" /></button>
        </div>

        <div style={{ marginTop: 22 }}>
          <Field label={isDistrict ? "District name" : "School name"}>
            <input style={fld} value={name} onChange={e => setName(e.target.value)} placeholder={isDistrict ? "e.g. Cascade USD #47" : "e.g. Westbrook High School"} autoFocus />
          </Field>
          {isDistrict ? (
            <Field label="Region / state">
              <input style={fld} value={region} onChange={e => setRegion(e.target.value)} placeholder="e.g. Washington" />
            </Field>
          ) : (
            <Field label="Parent organization">
              <select style={fld} value={districtId ?? "__standalone"} onChange={e => setDistrictId(e.target.value)} disabled={!!lockDistrict}>
                <option value="__standalone">Standalone school (no district)</option>
                {districts.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}
              </select>
              {lockDistrict && <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 6 }}>Adding within the current district.</div>}
            </Field>
          )}
        </div>

        <div style={modalFoot}>
          <window.UI.Btn variant="outline" onClick={onClose}>Cancel</window.UI.Btn>
          <window.UI.Btn onClick={save}>{data ? "Save changes" : "Create"}</window.UI.Btn>
        </div>
      </div>
    </window.UI.Modal>
  );
}

// ── Counselor add-edit modal ────────────────────────────────────────────
function CounselorModal({ data, lockSchool, schools, districtById, schoolById, orgNameForSchool, onClose }) {
  const I = window.I;
  const [name, setName] = useState(data?.name || "");
  const [email, setEmail] = useState(data?.email || "");
  const [schoolId, setSchoolId] = useState(data?.schoolId || lockSchool || schools[0]?.id || "");
  const [status, setStatus] = useState(data?.status || "invited");

  const orgName = schoolId ? orgNameForSchool(schoolId) : "—";
  const valid = name.trim() && /.+@.+\..+/.test(email) && schoolId;

  const save = () => {
    if (!valid) return;
    window.upsertCounselor({ id: data?.id, name: name.trim(), email: email.trim(), schoolId, status });
    onClose();
  };

  // group schools by org for the dropdown
  const districtSchools = schools.filter(s => s.districtId);
  const standalone = schools.filter(s => !s.districtId);
  const byDistrict = {};
  districtSchools.forEach(s => { (byDistrict[s.districtId] ||= []).push(s); });

  return (
    <window.UI.Modal open onClose={onClose} width={560}>
      <div style={{ padding: 28 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <div style={labelCaps}>Accounts · {data ? "Edit" : "New"} counselor</div>
            <h2 className="serif" style={{ fontSize: 24, margin: "6px 0 0", letterSpacing: -0.015 }}>{data ? (name || "Counselor") : "Add counselor"}</h2>
          </div>
          <button onClick={onClose} style={{ padding: 6 }}><I.X size={18} stroke="var(--ink-3)" /></button>
        </div>

        <div style={{ marginTop: 22 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <Field label="Full name">
              <input style={fld} value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Rachel Kim" autoFocus />
            </Field>
            <Field label="Email address">
              <input style={fld} value={email} onChange={e => setEmail(e.target.value)} placeholder="name@school.k12.us" type="email" />
            </Field>
          </div>

          <Field label="School">
            <select style={fld} value={schoolId} onChange={e => setSchoolId(e.target.value)} disabled={!!lockSchool}>
              {Object.entries(byDistrict).map(([did, list]) => (
                <optgroup key={did} label={districtById[did]?.name || "District"}>
                  {list.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                </optgroup>
              ))}
              {standalone.length > 0 && (
                <optgroup label="Standalone schools">
                  {standalone.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                </optgroup>
              )}
            </select>
          </Field>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <Field label="Organization">
              <div style={{ ...fld, background: "var(--bg-2)", color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 8 }}>
                <I.Home size={13} stroke="var(--ink-3)" /> {orgName}
              </div>
              <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 6 }}>Set automatically by the school.</div>
            </Field>
            <Field label="Account status">
              <select style={fld} value={status} onChange={e => setStatus(e.target.value)}>
                <option value="active">Active</option>
                <option value="invited">Invited</option>
                <option value="inactive">Inactive</option>
              </select>
            </Field>
          </div>
        </div>

        <div style={modalFoot}>
          <window.UI.Btn variant="outline" onClick={onClose}>Cancel</window.UI.Btn>
          <window.UI.Btn onClick={save} style={valid ? {} : { opacity: 0.5, pointerEvents: "none" }}>{data ? "Save changes" : "Add counselor"}</window.UI.Btn>
        </div>
      </div>
    </window.UI.Modal>
  );
}

// ── small shared bits ───────────────────────────────────────────────────
function TableShell({ grid, head, children }) {
  return (
    <div style={{ border: "1px solid var(--line)", borderRadius: "var(--radius)", background: "var(--card)", overflow: "hidden" }}>
      <div style={{ overflowX: "auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: grid, gap: 16, padding: "12px 20px", background: "var(--bg-2)", borderBottom: "1px solid var(--line)", fontSize: 11, color: "var(--ink-3)", fontWeight: 500, letterSpacing: 0.04, textTransform: "uppercase", minWidth: 700 }}>
          {head.map((h, i) => <div key={i} style={{ textAlign: i === head.length - 1 && (h === "" || h === "Status") ? (h === "" ? "right" : "left") : "left" }}>{h}</div>)}
        </div>
        {children}
      </div>
    </div>
  );
}
function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 12, fontWeight: 500, color: "var(--ink-2)", marginBottom: 6 }}>{label}</div>
      {children}
    </div>
  );
}
function Pill({ children, tone }) {
  const map = { accent: ["var(--accent-soft)", "var(--accent-ink)"], teal: ["var(--teal-soft)", "var(--teal-ink)"] };
  const [bg, fg] = map[tone] || map.accent;
  return <span style={{ fontSize: 10.5, fontWeight: 500, padding: "3px 9px", borderRadius: 999, background: bg, color: fg }}>{children}</span>;
}
function StatusPill({ status }) {
  const map = {
    active:   ["var(--success-soft)", "#14504F", "Active"],
    invited:  ["var(--accent-soft)", "var(--accent-ink)", "Invited"],
    inactive: ["var(--bg-2)", "var(--ink-3)", "Inactive"],
  };
  const [bg, fg, label] = map[status] || map.inactive;
  return (
    <span style={{ fontSize: 10.5, fontWeight: 500, padding: "3px 9px", borderRadius: 999, background: bg, color: fg, display: "inline-flex", alignItems: "center", gap: 5 }}>
      <span style={{ width: 5, height: 5, borderRadius: 999, background: fg, opacity: 0.7 }} /> {label}
    </span>
  );
}
function MiniBar({ pct }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <div style={{ width: 70, height: 6, background: "var(--line)", borderRadius: 3, overflow: "hidden" }}>
        <div style={{ width: `${pct}%`, height: "100%", background: pct >= 66 ? "var(--teal)" : pct >= 33 ? "var(--accent)" : "var(--orange)" }} />
      </div>
      <span className="mono" style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{pct}%</span>
    </div>
  );
}

// shared style tokens
const btnDark = { padding: "8px 14px", borderRadius: 8, background: "var(--ink)", color: "white", fontSize: 13, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 7, border: "none", cursor: "pointer" };
const btnOutline = { padding: "6px 11px", borderRadius: 7, background: "var(--card)", border: "1px solid var(--line-2)", color: "var(--ink-2)", fontSize: 12, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 6, cursor: "pointer" };
const iconBtn = { padding: 6, border: "1px solid var(--line)", borderRadius: 6, background: "var(--card)", cursor: "pointer" };
const cell = { fontSize: 12.5, color: "var(--ink-2)", display: "flex", alignItems: "center" };
const cellNum = { ...cell, };
const fld = { width: "100%", padding: "10px 12px", border: "1px solid var(--line-2)", borderRadius: 7, fontSize: 13, background: "var(--card)", boxSizing: "border-box" };
const labelCaps = { fontSize: 11, color: "var(--ink-3)", letterSpacing: 0.06, textTransform: "uppercase", fontWeight: 500 };
const modalFoot = { display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 8, paddingTop: 20, borderTop: "1px solid var(--line)" };
function rowStyle(grid, i) {
  return { display: "grid", gridTemplateColumns: grid, gap: 16, padding: "13px 20px", alignItems: "center", borderTop: i > 0 ? "1px solid var(--line)" : "none", minWidth: 700 };
}

window.AccountsView = AccountsView;
