// screens-admin-people.jsx — People (Members + Coaches), Member detail, Coach detail

const { fmtIDR, findClass, findCoach } = window.NADI_HELPERS;

function AdminPeopleScreen({ openMember, openCoach, showToast }) {
  const [seg, setSeg] = useState("members");  // members | coaches
  const [query, setQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");  // all | active | new | lapsed

  return (
    <div className="screen-fade" style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div style={{ padding: "12px 22px 12px" }}>
        <Eyebrow>people</Eyebrow>
        <h1 className="display" style={{ fontSize: 38, marginTop: 12, marginBottom: 14 }}>
          {seg === "members" ? "Members" : "Coaches"}.
        </h1>

        {/* Segmented */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", border: "1px solid var(--rule)", marginBottom: 14 }}>
          {[["members", "Members", window.NADI_ADMIN.MEMBERS.length], ["coaches", "Coaches", window.NADI.COACHES.length]].map(([id, label, n]) => (
            <button key={id} onClick={() => setSeg(id)} className="press" style={{
              padding: "12px 8px",
              background: seg === id ? "var(--ink)" : "transparent",
              color: seg === id ? "var(--bg)" : "var(--ink-soft)",
              fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
              letterSpacing: "0.1em", textTransform: "uppercase",
              display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
            }}>{label}<span style={{ opacity: 0.6 }}>{n}</span></button>
          ))}
        </div>

        {/* Search */}
        <div style={{ position: "relative" }}>
          <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", display: "flex" }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="var(--ink-soft)" strokeWidth="1.4" strokeLinecap="round"><circle cx="6" cy="6" r="4.5"/><path d="M10 10l3 3"/></svg>
          </span>
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={seg === "members" ? "Search by name, email, phone…" : "Search teachers…"}
            style={{
              width: "100%", padding: "12px 14px 12px 36px",
              border: "1px solid var(--rule)", background: "var(--bg)",
              fontFamily: "Geist, sans-serif", fontSize: 14, color: "var(--ink)",
            }}
          />
        </div>

        {seg === "members" && (
          <div style={{ display: "flex", gap: 6, marginTop: 12, overflowX: "auto", margin: "12px -22px 0", padding: "0 22px" }} className="scroll">
            {[["all","All"],["active","Active"],["new","New"],["lapsed","Lapsed"]].map(([id, label]) => (
              <Chip key={id} active={statusFilter === id} onClick={() => setStatusFilter(id)}>{label}</Chip>
            ))}
            <button onClick={() => showToast && showToast("Add member dialog.")} className="press" style={{
              marginLeft: "auto", flexShrink: 0,
              padding: "8px 14px",
              background: "var(--ink)", color: "var(--bg)",
              fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
              letterSpacing: "0.06em", textTransform: "lowercase",
              borderRadius: 999, border: "1px solid var(--ink)",
            }}>+ add</button>
          </div>
        )}
      </div>

      {/* List */}
      <div className="scroll" style={{ flex: 1, padding: "8px 22px 24px" }}>
        {seg === "members" ? (
          <MemberList query={query} statusFilter={statusFilter} openMember={openMember} />
        ) : (
          <CoachList query={query} openCoach={openCoach} showToast={showToast} />
        )}
      </div>
    </div>
  );
}

function MemberList({ query, statusFilter, openMember }) {
  let list = window.NADI_ADMIN.MEMBERS;
  if (statusFilter !== "all") list = list.filter((m) => m.status === statusFilter);
  if (query) {
    const q = query.toLowerCase();
    list = list.filter((m) => m.name.toLowerCase().includes(q) || m.email.toLowerCase().includes(q) || m.phone.includes(query));
  }
  if (list.length === 0) return (
    <div style={{ padding: "40px 0", textAlign: "center" }}><Mono>no matches</Mono></div>
  );
  return (
    <div style={{ borderTop: "1px solid var(--rule)" }}>
      {list.map((m) => <MemberRow key={m.id} m={m} onClick={() => openMember(m)} />)}
    </div>
  );
}

function MemberRow({ m, onClick }) {
  const statusColors = {
    active: "var(--accent)",
    new: "var(--primary)",
    lapsed: "var(--muted)",
  };
  return (
    <button onClick={onClick} className="press" style={{
      width: "100%", textAlign: "left",
      display: "grid", gridTemplateColumns: "40px 1fr auto", gap: 12,
      padding: "14px 0",
      borderBottom: "1px solid var(--rule)",
      background: "transparent", alignItems: "center",
    }}>
      <Avatar name={m.name} initials={m.initials} tone={m.tone} size={40} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: "Newsreader, serif", fontSize: 18, color: "var(--ink)" }}>{m.name}</div>
        <Mono>{m.package === "—" ? "no active pack" : m.package.toLowerCase()} · {m.visits} visits</Mono>
      </div>
      <div style={{ textAlign: "right" }}>
        <span style={{
          fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5,
          letterSpacing: "0.08em", textTransform: "uppercase",
          padding: "3px 8px",
          border: `1px solid ${statusColors[m.status]}`,
          color: statusColors[m.status],
        }}>{m.status}</span>
        <div style={{ marginTop: 6, fontFamily: "Newsreader, serif", fontSize: 20, color: m.credits === 0 ? "var(--primary)" : "var(--ink)" }}>
          {m.credits}
        </div>
        <Mono style={{ fontSize: 9.5 }}>credit{m.credits === 1 ? "" : "s"}</Mono>
      </div>
    </button>
  );
}

function CoachList({ query, openCoach, showToast }) {
  let list = window.NADI.COACHES;
  if (query) {
    const q = query.toLowerCase();
    list = list.filter((c) => c.name.toLowerCase().includes(q));
  }
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {list.map((c) => {
        const payout = window.NADI_ADMIN.PAYOUTS.find((p) => p.coachId === c.id) || { classes: 0, hours: 0, rate: 200000, paid: false };
        const currentRate = c.rate || payout.rate || 200000;
        const currentTotal = payout.classes * currentRate;
        return (
          <button key={c.id} onClick={() => openCoach(c)} className="press" style={{
            width: "100%", textAlign: "left",
            padding: 16, background: "var(--bg)", border: "1px solid var(--rule)",
            display: "grid", gridTemplateColumns: "56px 1fr auto", gap: 14, alignItems: "center",
          }}>
            <Avatar name={c.name} initials={c.initials} tone={c.tone} size={56} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontFamily: "Newsreader, serif", fontSize: 20, color: "var(--ink)" }}>{c.name}</div>
              <Mono color="var(--primary)">{c.title.toLowerCase()}</Mono>
              <Mono style={{ marginTop: 6, display: "block" }}>{payout.classes} classes this month · {payout.hours}h</Mono>
            </div>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontFamily: "Newsreader, serif", fontSize: 16, color: "var(--ink)" }}>{fmtIDR(currentTotal)}</div>
              <Mono color={payout.paid ? "var(--accent)" : "var(--primary)"} style={{ marginTop: 2 }}>{payout.paid ? "paid" : "owed"}</Mono>
            </div>
          </button>
        );
      })}
      <button onClick={() => showToast && showToast("Add coach dialog.")} className="press" style={{
        padding: "14px 16px", background: "transparent",
        border: "1px dashed var(--rule)", color: "var(--ink-soft)",
        fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase",
      }}>+ Add coach</button>
    </div>
  );
}

// ── MEMBER DETAIL SHEET (full CRUD) ─────────────────────────────────
function AdminMemberSheet({ member, onClose, showToast }) {
  const [tab, setTab] = useState("overview");  // overview | bookings | packs | edit
  if (!member) return null;

  return (
    <Sheet open={!!member} onClose={onClose} maxHeight="95%">
      <div style={{ padding: "10px 22px 26px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Mono>member · #{member.id}</Mono>
          <button onClick={onClose} className="press" style={{ background: "transparent", padding: 6 }}><Mono>close ×</Mono></button>
        </div>

        <div style={{ marginTop: 16, display: "flex", alignItems: "center", gap: 16 }}>
          <Avatar name={member.name} initials={member.initials} tone={member.tone} size={64} />
          <div style={{ minWidth: 0 }}>
            <h2 className="display" style={{ fontSize: 32 }}>{member.name}</h2>
            <Mono>joined {new Date(member.joined).toLocaleDateString("en-GB", { month: "short", year: "numeric" }).toLowerCase()}</Mono>
          </div>
        </div>

        {/* Stats row */}
        <div style={{ marginTop: 18, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 1, background: "var(--rule)", border: "1px solid var(--rule)" }}>
          <SmallStat label="credits" value={member.credits} accent={member.credits === 0} />
          <SmallStat label="visits" value={member.visits} />
          <SmallStat label="status" value={member.status} text />
        </div>

        {/* Contact */}
        <div style={{ marginTop: 18, padding: 14, background: "var(--surface)", border: "1px solid var(--rule)" }}>
          <Mono>contact</Mono>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
            <span style={{ fontFamily: "Newsreader, serif", fontSize: 16 }}>{member.email}</span>
            <span style={{ fontFamily: "Newsreader, serif", fontSize: 16 }}>{member.phone}</span>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ marginTop: 22, display: "flex", gap: 6, borderBottom: "1px solid var(--rule)" }}>
          {[["overview","Overview"],["bookings","Bookings"],["packs","Packs"],["edit","Edit"]].map(([id, label]) => (
            <button key={id} onClick={() => setTab(id)} className="press" style={{
              padding: "10px 4px",
              background: "transparent",
              color: tab === id ? "var(--ink)" : "var(--ink-soft)",
              fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
              letterSpacing: "0.1em", textTransform: "uppercase",
              borderBottom: tab === id ? "2px solid var(--primary)" : "2px solid transparent",
              marginBottom: -1, flex: 1,
            }}>{label}</button>
          ))}
        </div>

        <div style={{ marginTop: 18 }}>
          {tab === "overview" && <MemberOverview member={member} showToast={showToast} />}
          {tab === "bookings" && <MemberBookings member={member} showToast={showToast} />}
          {tab === "packs" && <MemberPacks member={member} showToast={showToast} />}
          {tab === "edit" && <MemberEdit member={member} showToast={showToast} onClose={onClose} />}
        </div>
      </div>
    </Sheet>
  );
}

function SmallStat({ label, value, suffix, accent, text }) {
  return (
    <div style={{ background: "var(--bg)", padding: "14px 12px", textAlign: "left" }}>
      <Mono>{label}</Mono>
      <div style={{
        fontFamily: "Newsreader, serif",
        fontSize: text ? 18 : 28,
        fontWeight: 400, lineHeight: 1, marginTop: 6,
        color: accent ? "var(--primary)" : "var(--ink)",
        letterSpacing: "-0.01em",
        textTransform: text ? "capitalize" : "none",
      }}>{value}</div>
      {suffix && <Mono style={{ marginTop: 4 }}>{suffix}</Mono>}
    </div>
  );
}

function MemberOverview({ member, showToast }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      {/* Quick actions */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
        <Button variant="primary" size="md" onClick={() => showToast && showToast("Booking dialog opened.")}>Book a class</Button>
        <Button variant="ghost" size="md" onClick={() => showToast && showToast("Pack added.")}>Sell pack</Button>
        <Button variant="ghost" size="md" onClick={() => showToast && showToast("Credit refunded.")}>Refund 1 credit</Button>
        <Button variant="ghost" size="md" onClick={() => showToast && showToast("Note added.")}>Add note</Button>
      </div>

      {/* Last visit */}
      <div style={{ padding: 14, background: "var(--surface)", border: "1px solid var(--rule)" }}>
        <Mono>last visit</Mono>
        <div style={{ fontFamily: "Newsreader, serif", fontSize: 18, color: "var(--ink)", marginTop: 6 }}>{member.lastVisit}</div>
      </div>

      {/* Recent payments for this member */}
      <div>
        <Mono>recent purchases</Mono>
        <div style={{ marginTop: 8, borderTop: "1px solid var(--rule)" }}>
          {window.NADI_ADMIN.PAYMENTS.filter((p) => p.memberId === member.id).map((p) => (
            <div key={p.id} style={{ padding: "12px 0", borderBottom: "1px solid var(--rule)", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <div>
                <div style={{ fontFamily: "Newsreader, serif", fontSize: 16, color: "var(--ink)" }}>{p.item}</div>
                <Mono>{p.date} · {p.method.toLowerCase()}</Mono>
              </div>
              <Mono color="var(--ink)" style={{ fontSize: 14, fontFamily: "Newsreader, serif", textTransform: "none", letterSpacing: 0 }}>{fmtIDR(p.amount)}</Mono>
            </div>
          ))}
          {window.NADI_ADMIN.PAYMENTS.filter((p) => p.memberId === member.id).length === 0 && (
            <div style={{ padding: "16px 0" }}><Mono>no purchases yet</Mono></div>
          )}
        </div>
      </div>
    </div>
  );
}

function MemberBookings({ member, showToast }) {
  // Mock 4 sessions
  const upcoming = window.NADI.SCHEDULE.slice(0, 2);
  const past = window.NADI.SCHEDULE.slice(2, 6);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <div>
        <Mono>upcoming · {upcoming.length}</Mono>
        <div style={{ marginTop: 8, borderTop: "1px solid var(--rule)" }}>
          {upcoming.map((s) => {
            const c = findClass(s.classId), co = findCoach(s.coachId);
            return (
              <div key={s.id} style={{ padding: "12px 0", borderBottom: "1px solid var(--rule)", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <div>
                  <div style={{ fontFamily: "Newsreader, serif", fontSize: 16, color: "var(--ink)" }}>{c.name}</div>
                  <Mono>{window.NADI_HELPERS.DAYS_SHORT[s.day]} {s.time} · {co.firstName.toLowerCase()}</Mono>
                </div>
                <button onClick={() => showToast && showToast("Booking cancelled.")} className="press" style={{
                  padding: "5px 10px", background: "transparent", border: "1px solid var(--rule)",
                  fontFamily: "'JetBrains Mono', monospace", fontSize: 9.5, letterSpacing: "0.06em", textTransform: "lowercase", color: "var(--primary)",
                }}>cancel</button>
              </div>
            );
          })}
        </div>
      </div>
      <div>
        <Mono>past · {past.length}</Mono>
        <div style={{ marginTop: 8, borderTop: "1px solid var(--rule)" }}>
          {past.map((s) => {
            const c = findClass(s.classId), co = findCoach(s.coachId);
            return (
              <div key={s.id} style={{ padding: "12px 0", borderBottom: "1px solid var(--rule)", display: "flex", justifyContent: "space-between" }}>
                <div>
                  <div style={{ fontFamily: "Newsreader, serif", fontSize: 16, color: "var(--ink)" }}>{c.name}</div>
                  <Mono>{window.NADI_HELPERS.DAYS_SHORT[s.day]} {s.time} · {co.firstName.toLowerCase()}</Mono>
                </div>
                <Mono>attended</Mono>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function MemberPacks({ member, showToast }) {
  const packs = member.credits > 0 ? [
    { name: member.package.split(" + ")[0] || "Standard 5", credits: member.credits, total: 5, expires: "2026-06-04" },
  ] : [];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {packs.length === 0 ? (
        <div style={{ padding: 18, background: "var(--surface)", border: "1px dashed var(--rule)", textAlign: "center" }}>
          <Mono>no active packs</Mono>
        </div>
      ) : packs.map((p, i) => (
        <div key={i} style={{ padding: 16, background: "var(--bg)", border: "1px solid var(--rule)" }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <span style={{ fontFamily: "Newsreader, serif", fontSize: 18, color: "var(--ink)" }}>{p.name}</span>
            <Mono color="var(--primary)">expires {p.expires.slice(5)}</Mono>
          </div>
          <Mono style={{ marginTop: 4, display: "block" }}>{p.credits}/{p.total} credits remaining</Mono>
          <div style={{ marginTop: 12, display: "flex", gap: 8 }}>
            <Button variant="ghost" size="sm" onClick={() => showToast && showToast("Pack extended.")}>Extend 7 days</Button>
            <Button variant="dangerGhost" size="sm" onClick={() => showToast && showToast("Pack voided.")}>Void</Button>
          </div>
        </div>
      ))}
      <div>
        <Button variant="primary" size="md" fullWidth onClick={() => showToast && showToast("Sell pack flow.")}>Sell a pack</Button>
      </div>
    </div>
  );
}

function MemberEdit({ member, showToast, onClose }) {
  const [name, setName] = useState(member.name);
  const [email, setEmail] = useState(member.email);
  const [phone, setPhone] = useState(member.phone);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <Field label="Full name" value={name} onChange={setName} />
      <Field label="Email" value={email} onChange={setEmail} type="email" />
      <Field label="Phone" value={phone} onChange={setPhone} />

      <div style={{ marginTop: 10, display: "flex", gap: 8 }}>
        <Button variant="ghost" size="md" fullWidth onClick={onClose}>Cancel</Button>
        <Button variant="primary" size="md" fullWidth onClick={async () => {
          const token = localStorage.getItem("nadi_token");
          if (!token) return;
          try {
            const res = await fetch(`/api/admin/members/${member.id}`, {
              method: "PUT",
              headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${token}`
              },
              body: JSON.stringify({ name, email })
            });
            if (res.ok) {
              showToast && showToast("Member saved.");
              if (window.NADI_RELOAD_ADMIN_DATA) {
                await window.NADI_RELOAD_ADMIN_DATA();
              }
              onClose();
            } else {
              const err = await res.json();
              showToast && showToast(err.detail || "Failed to save member.");
            }
          } catch (e) {
            console.error(e);
            showToast && showToast("Error connecting to server.");
          }
        }}>Save</Button>
      </div>

      <div style={{ marginTop: 12, padding: 16, background: "rgba(181,86,60,0.06)", border: "1px solid var(--primary)" }}>
        <Mono color="var(--primary)">danger zone</Mono>
        <p style={{ fontFamily: "Newsreader, serif", fontSize: 14, color: "var(--ink-soft)", fontWeight: 300, marginTop: 6, lineHeight: 1.5 }}>
          Suspending freezes credits and prevents booking. Deleting is permanent.
        </p>
        <div style={{ marginTop: 12, display: "flex", gap: 8 }}>
          <Button variant="dangerGhost" size="sm" onClick={async () => {
            const token = localStorage.getItem("nadi_token");
            if (!token) return;
            try {
              const res = await fetch(`/api/admin/members/${member.id}`, {
                method: "PUT",
                headers: {
                  "Content-Type": "application/json",
                  "Authorization": `Bearer ${token}`
                },
                body: JSON.stringify({ status: "suspended" })
              });
              if (res.ok) {
                showToast && showToast("Member suspended.");
                if (window.NADI_RELOAD_ADMIN_DATA) {
                  await window.NADI_RELOAD_ADMIN_DATA();
                }
                onClose();
              } else {
                const err = await res.json();
                showToast && showToast(err.detail || "Failed to suspend member.");
              }
            } catch (e) {
              console.error(e);
              showToast && showToast("Error connecting to server.");
            }
          }}>Suspend</Button>
          <Button variant="dangerGhost" size="sm" onClick={async () => {
            const token = localStorage.getItem("nadi_token");
            if (!token) return;
            if (!confirm(`Are you sure you want to delete member ${member.name}?`)) return;
            try {
              const res = await fetch(`/api/admin/accounts/${member.id}`, {
                method: "DELETE",
                headers: {
                  "Authorization": `Bearer ${token}`
                }
              });
              if (res.ok) {
                showToast && showToast("Member deleted.");
                if (window.NADI_RELOAD_ADMIN_DATA) {
                  await window.NADI_RELOAD_ADMIN_DATA();
                }
                onClose();
              } else {
                const err = await res.json();
                showToast && showToast(err.detail || "Failed to delete member.");
              }
            } catch (e) {
              console.error(e);
              showToast && showToast("Error connecting to server.");
            }
          }}>Delete</Button>
        </div>
      </div>
    </div>
  );
}

// ── COACH DETAIL SHEET ────────────────────────────────────────────
function AdminCoachSheet({ coach, onClose, showToast }) {
  const [tab, setTab] = useState("overview");
  const [name, setName] = React.useState("");
  const [title, setTitle] = React.useState("");
  const [yrs, setYrs] = React.useState(0);
  const [bio, setBio] = React.useState("");
  const [rate, setRate] = React.useState(200000);

  React.useEffect(() => {
    if (coach) {
      setName(coach.name || "");
      setTitle(coach.title || "");
      setYrs(coach.yrs || 0);
      setBio(coach.bio || "");
      setRate(coach.rate || 200000);
    }
  }, [coach]);

  if (!coach) return null;
  const payout = window.NADI_ADMIN.PAYOUTS.find((p) => p.coachId === coach.id) || { classes: 0, hours: 0, rate: 200000, paid: false };
  const currentRate = coach.rate || payout.rate || 200000;
  const currentTotal = payout.classes * currentRate;
  const upcomingClasses = window.NADI.SCHEDULE.filter((s) => s.coachId === coach.id).slice(0, 5);

  return (
    <Sheet open={!!coach} onClose={onClose} maxHeight="95%">
      <div style={{ padding: "10px 22px 26px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Mono>coach · {coach.role || "teacher"}</Mono>
          <button onClick={onClose} className="press" style={{ background: "transparent", padding: 6 }}><Mono>close ×</Mono></button>
        </div>

        <div style={{ marginTop: 16, display: "flex", alignItems: "center", gap: 16 }}>
          <Avatar name={coach.name} initials={coach.initials} tone={coach.tone} size={64} />
          <div style={{ minWidth: 0 }}>
            <h2 className="display" style={{ fontSize: 28 }}>{coach.name}</h2>
            <Mono color="var(--primary)">{coach.title.toLowerCase()} · {coach.yrs} yrs</Mono>
          </div>
        </div>

        <p style={{ marginTop: 14, fontFamily: "Newsreader, serif", fontSize: 15, color: "var(--ink-soft)", fontWeight: 300, lineHeight: 1.5 }}>
          {coach.bio}
        </p>

        {/* Tabs */}
        <div style={{ marginTop: 22, display: "flex", gap: 6, borderBottom: "1px solid var(--rule)" }}>
          {[["overview","Overview"],["schedule","Schedule"],["pay","Pay"],["edit","Edit"]].map(([id, label]) => (
            <button key={id} onClick={() => setTab(id)} className="press" style={{
              padding: "10px 4px", background: "transparent",
              color: tab === id ? "var(--ink)" : "var(--ink-soft)",
              fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
              letterSpacing: "0.1em", textTransform: "uppercase",
              borderBottom: tab === id ? "2px solid var(--primary)" : "2px solid transparent",
              marginBottom: -1, flex: 1,
            }}>{label}</button>
          ))}
        </div>

        <div style={{ marginTop: 18 }}>
          {tab === "overview" && (
            <div>
              <Mono>specialties</Mono>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 8 }}>
                {coach.specialties.map((sid) => <Chip key={sid} active>{findClass(sid).name.toLowerCase()}</Chip>)}
              </div>
              <div style={{ marginTop: 22, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 1, background: "var(--rule)", border: "1px solid var(--rule)" }}>
                <SmallStat label="this month" value={payout.classes} suffix="classes" />
                <SmallStat label="hours" value={payout.hours} />
                <SmallStat label="owed" value={fmtIDR(currentTotal).replace("Rp ", "")} suffix="rp" accent={!payout.paid} />
              </div>
            </div>
          )}
          {tab === "schedule" && (
            <div style={{ borderTop: "1px solid var(--rule)" }}>
              {upcomingClasses.map((s) => {
                const c = findClass(s.classId);
                return (
                  <div key={s.id} style={{ padding: "12px 0", borderBottom: "1px solid var(--rule)", display: "flex", justifyContent: "space-between" }}>
                    <div>
                      <div style={{ fontFamily: "Newsreader, serif", fontSize: 16 }}>{c.name}</div>
                      <Mono>{window.NADI_HELPERS.DAYS_SHORT[s.day].toLowerCase()} {s.time} · {s.roomShort.toLowerCase()}</Mono>
                    </div>
                    <Mono>{s.booked}/{s.capacity}</Mono>
                  </div>
                );
              })}
            </div>
          )}
          {tab === "pay" && (
            <div>
              <div style={{ padding: 16, background: "var(--bg)", border: "1px solid var(--rule)" }}>
                <Mono>this month · {new Date().toLocaleDateString("en-GB", { month: "short" }).toLowerCase()}</Mono>
                <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginTop: 8 }}>
                  <span className="display" style={{ fontSize: 38, color: payout.paid ? "var(--accent)" : "var(--primary)" }}>{fmtIDR(currentTotal)}</span>
                  <Mono color={payout.paid ? "var(--accent)" : "var(--primary)"}>{payout.paid ? "paid" : "owed"}</Mono>
                </div>
                <Mono style={{ marginTop: 10, display: "block" }}>{payout.classes} classes × {fmtIDR(currentRate)}/class</Mono>
                {!payout.paid && (
                  <div style={{ marginTop: 16 }}>
                    <Button variant="primary" size="md" fullWidth onClick={() => showToast && showToast("Payout marked as paid.")}>Mark as paid · {fmtIDR(currentTotal)}</Button>
                  </div>
                )}
              </div>
            </div>
          )}
          {tab === "edit" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <Field label="Name" value={name} onChange={setName} />
              <Field label="Title" value={title} onChange={setTitle} />
              <Field label="Years teaching" value={yrs} onChange={(v) => setYrs(parseInt(v, 10) || 0)} type="number" />
              <Field label="Bio" value={bio} onChange={setBio} />
              <Field label="Pay rate (IDR/class)" value={rate} onChange={(v) => setRate(parseInt(v, 10) || 0)} type="number" />
              <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
                <Button variant="ghost" size="md" fullWidth onClick={onClose}>Cancel</Button>
                <Button variant="primary" size="md" fullWidth onClick={async () => {
                  const token = localStorage.getItem("nadi_token");
                  if (!token) return;
                  try {
                    const res = await fetch(`/api/admin/coaches/${coach.id}`, {
                      method: "PUT",
                      headers: {
                        "Content-Type": "application/json",
                        "Authorization": `Bearer ${token}`
                      },
                      body: JSON.stringify({
                        name: name,
                        title: title,
                        bio: bio,
                        yrs: yrs,
                        rate: rate
                      })
                    });
                    if (res.ok) {
                      showToast && showToast("Coach saved.");
                      if (window.NADI_RELOAD_PUBLIC) {
                        await window.NADI_RELOAD_PUBLIC();
                      }
                      onClose();
                    } else {
                      const err = await res.json();
                      showToast && showToast(err.detail || "Error saving coach.");
                    }
                  } catch (e) {
                    console.error(e);
                    showToast && showToast("Error connecting to server.");
                  }
                }}>Save</Button>
              </div>
            </div>
          )}
        </div>
      </div>
    </Sheet>
  );
}

Object.assign(window, { AdminPeopleScreen, AdminMemberSheet, AdminCoachSheet, SmallStat });
