// screens-admin-schedule.jsx — Admin schedule ops + session edit sheet

const { fmtIDR, findClass, findCoach, DAYS_SHORT, DAYS_LONG, DATES_THIS_WEEK, TODAY_DAY } = window.NADI_HELPERS;

function AdminScheduleScreen({ openSession, openAddSession, showToast }) {
  const [day, setDay] = useState(TODAY_DAY);
  const sessions = window.NADI.SCHEDULE.filter((s) => s.day === day).sort((a, b) => a.time.localeCompare(b.time));

  // Total this day
  const totalBooked = sessions.reduce((s, x) => s + x.booked, 0);
  const totalCap = sessions.reduce((s, x) => s + x.capacity, 0);
  const fillPct = Math.round((totalBooked / totalCap) * 100);

  return (
    <div className="screen-fade" style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      {/* Header */}
      <div style={{ padding: "12px 22px 14px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <Eyebrow>schedule · this week</Eyebrow>
          <button onClick={openAddSession} className="press" style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "6px 12px",
            border: "1px solid var(--ink)", background: "var(--ink)", color: "var(--bg)",
            fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, letterSpacing: "0.08em",
            textTransform: "lowercase",
          }}>+ add session</button>
        </div>
        <h1 className="display" style={{ fontSize: 36, marginTop: 12 }}>
          {day === TODAY_DAY ? <>Today, <em style={{ fontStyle: "italic", color: "var(--primary)" }}>{DAYS_LONG[day].toLowerCase()}.</em></> : <>{DAYS_LONG[day]}.</>}
        </h1>
        <Mono style={{ marginTop: 6, display: "block" }}>
          {sessions.length} sessions · {totalBooked}/{totalCap} seats ({fillPct}% full)
        </Mono>
        <div style={{ marginTop: 14 }}>
          <AdminDayStrip day={day} setDay={setDay} />
        </div>
      </div>

      {/* Sessions list */}
      <div className="scroll" style={{ flex: 1, padding: "12px 22px 24px" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {sessions.map((s) => <AdminSessionRow key={s.id} s={s} onClick={() => openSession(s)} />)}
        </div>
      </div>
    </div>
  );
}

function AdminDayStrip({ day, setDay }) {
  return (
    <div className="scroll" style={{
      display: "flex", gap: 6, paddingBottom: 4,
      overflowX: "auto", margin: "0 -22px", padding: "0 22px 4px",
    }}>
      {DAYS_SHORT.map((d, i) => {
        const active = i === day;
        const isToday = i === TODAY_DAY;
        return (
          <button key={i} onClick={() => setDay(i)} className="press" style={{
            flexShrink: 0, width: 50, height: 60,
            border: `1px solid ${active ? "var(--ink)" : "var(--rule)"}`,
            background: active ? "var(--ink)" : "transparent",
            color: active ? "var(--bg)" : "var(--ink)",
            display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 3,
            position: "relative",
          }}>
            <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.08em", opacity: active ? 0.7 : 0.6, textTransform: "lowercase" }}>{d.toLowerCase()}</span>
            <span style={{ fontFamily: "Newsreader, serif", fontSize: 20, fontWeight: 400, lineHeight: 1 }}>{DATES_THIS_WEEK[i]}</span>
            {isToday && !active && <span style={{ position: "absolute", bottom: 4, width: 4, height: 4, borderRadius: "50%", background: "var(--primary)" }} />}
          </button>
        );
      })}
    </div>
  );
}

function AdminSessionRow({ s, onClick }) {
  const c = findClass(s.classId), co = findCoach(s.coachId);
  const left = s.capacity - s.booked;
  const full = left === 0;
  const pct = Math.round((s.booked / s.capacity) * 100);
  return (
    <button onClick={onClick} className="press" style={{
      width: "100%", textAlign: "left",
      background: "var(--bg)", border: "1px solid var(--rule)",
      padding: "14px 16px",
      display: "grid", gridTemplateColumns: "62px 1fr auto", gap: 12, alignItems: "center",
    }}>
      <div>
        <div style={{ fontFamily: "Newsreader, serif", fontSize: 22, fontWeight: 400, lineHeight: 1, color: "var(--ink)" }}>{s.time}</div>
        <Mono style={{ marginTop: 4 }}>{c.duration}m</Mono>
      </div>
      <div>
        <div style={{ fontFamily: "Newsreader, serif", fontSize: 18, color: "var(--ink)", textWrap: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</div>
        <div style={{ marginTop: 4, display: "flex", alignItems: "center", gap: 8 }}>
          <Avatar name={co.name} initials={co.initials} tone={co.tone} size={18} />
          <Mono>{co.firstName.toLowerCase()} · {s.roomShort.toLowerCase()}</Mono>
        </div>
      </div>
      <div style={{ textAlign: "right" }}>
        <Mono color={full ? "var(--primary)" : "var(--ink)"}>{s.booked}/{s.capacity}</Mono>
        <div style={{ marginTop: 6, width: 56, height: 3, background: "var(--surface-2)", marginLeft: "auto", position: "relative" }}>
          <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${pct}%`, background: full ? "var(--primary)" : "var(--accent)" }} />
        </div>
      </div>
    </button>
  );
}

// ── Session edit sheet (used from admin schedule + now) ────────────
function AdminSessionSheet({ session, onClose, showToast, openRoster }) {
  if (!session) return null;
  const c = findClass(session.classId), co = findCoach(session.coachId);
  const checkin = (window.NADI_ADMIN.CHECKINS && window.NADI_ADMIN.CHECKINS[session.id]) || { checked: 0 };
  const isPast = session.day < TODAY_DAY || (session.day === TODAY_DAY && session.time < "14:08");
  const pct = Math.round((session.booked / session.capacity) * 100);

  return (
    <Sheet open={!!session} onClose={onClose} maxHeight="92%">
      <div style={{ padding: "10px 22px 26px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Mono>{DAYS_LONG[session.day].toLowerCase()} · {session.time} · {c.duration}m</Mono>
          <button onClick={onClose} className="press" style={{ background: "transparent", padding: 6 }}><Mono>close ×</Mono></button>
        </div>

        <h2 className="display" style={{ fontSize: 40, marginTop: 14 }}>{c.name}</h2>
        <Mono style={{ marginTop: 4, display: "block" }}>with {co.name.toLowerCase()} · {session.roomShort.toLowerCase()}</Mono>

        {/* Capacity bar */}
        <div style={{ marginTop: 22 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <Mono>occupancy</Mono>
            <Mono color={pct === 100 ? "var(--primary)" : "var(--ink-soft)"}>{session.booked}/{session.capacity} · {pct}%</Mono>
          </div>
          <div style={{ marginTop: 8, height: 5, background: "var(--surface-2)", position: "relative" }}>
            <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${pct}%`, background: pct === 100 ? "var(--primary)" : "var(--accent)" }} />
          </div>
        </div>

        {/* Detail grid */}
        <div style={{ marginTop: 18, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 1, background: "var(--rule)", border: "1px solid var(--rule)" }}>
          <DetailCell label="checked in" value={isPast ? `${session.attendedCount || 0}/${session.booked}` : "—"} sub={isPast ? "complete" : "not yet"} />
          <DetailCell label="waitlist" value={session.waitlistCount > 0 ? `${session.waitlistCount} waiting` : "—"} sub={session.waitlistCount > 0 ? "promote on cancel" : "open"} />
          <DetailCell label="revenue" value={fmtIDR(session.booked * 180000)} sub={`${session.booked} credits`} />
          <DetailCell label="coach pay" value={fmtIDR(co.rate || 200000)} sub="per session" />
        </div>

        {/* Quick actions */}
        <div style={{ marginTop: 22, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <Button variant="primary" size="md" onClick={() => { openRoster && openRoster(session); }}>View roster</Button>
          <Button variant="ghost" size="md" onClick={() => showToast && showToast("Session edited.")}>Edit details</Button>
          <Button variant="ghost" size="md" onClick={() => showToast && showToast("Reassigned teacher.")}>Reassign teacher</Button>
          <Button variant="dangerGhost" size="md" onClick={async () => {
            const token = localStorage.getItem("nadi_token");
            if (!token) return;
            if (!confirm("Are you sure you want to cancel this class?")) return;
            try {
              const res = await fetch(`/api/admin/sessions/${session.id}`, {
                method: "DELETE",
                headers: { "Authorization": `Bearer ${token}` }
              });
              if (res.ok) {
                showToast && showToast("Class cancelled — attendees notified.");
                if (window.NADI_RELOAD_SCHEDULE) {
                  await window.NADI_RELOAD_SCHEDULE();
                }
                onClose();
              } else {
                const err = await res.json();
                showToast && showToast(err.detail || "Failed to cancel class.");
              }
            } catch (e) {
              console.error(e);
              showToast && showToast("Error connecting to server.");
            }
          }}>Cancel class</Button>
        </div>

        {/* Notify attendees */}
        <div style={{ marginTop: 22, padding: 16, background: "var(--surface)", border: "1px solid var(--rule)" }}>
          <Mono color="var(--primary)">notify attendees</Mono>
          <p style={{ fontFamily: "Newsreader, serif", fontSize: 14, color: "var(--ink-soft)", fontWeight: 300, marginTop: 6, lineHeight: 1.5 }}>
            Push a quick note to everyone booked — late teacher, room change, weather.
          </p>
          <div style={{ marginTop: 12 }}>
            <Button variant="ghost" size="sm" onClick={() => showToast && showToast("Notice sent to attendees.")}>+ Send notice</Button>
          </div>
        </div>
      </div>
    </Sheet>
  );
}

// ── Roster sheet (member list for a session) ──────────────────────
function AdminRosterSheet({ session, onClose, openMember, showToast }) {
  if (!session) return null;
  const c = findClass(session.classId);

  // Mock roster — take the friends + a few members
  const friendIds = session.friends;
  const friendMembers = friendIds.map((fid) => {
    // Friends map approximately to members by initials
    const f = window.NADI.FRIENDS.find((x) => x.id === fid);
    if (!f) return null;
    return { id: fid, name: f.name + " " + (f.id === "f1" ? "Putri" : ""), initials: f.initials, tone: f.tone };
  }).filter(Boolean);

  const extra = window.NADI_ADMIN.MEMBERS.slice(0, session.booked - friendMembers.length).map((m) => ({
    id: m.id, name: m.name, initials: m.initials, tone: m.tone, memberId: m.id,
  }));
  const roster = [...friendMembers, ...extra];
  const dateStr = session.date ? window.NADI_HELPERS.parseLocalDate(session.date).toLocaleDateString("en-GB", { day: "2-digit", month: "short" }).toLowerCase() : "";
  const nameSuffix = dateStr ? ` (${dateStr})` : "";

  return (
    <Sheet open={!!session} onClose={onClose} maxHeight="92%">
      <div style={{ padding: "10px 22px 26px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Mono>roster · {DAYS_LONG[session.day].toLowerCase()} · {session.time}</Mono>
          <button onClick={onClose} className="press" style={{ background: "transparent", padding: 6 }}><Mono>close ×</Mono></button>
        </div>
        <h2 className="display" style={{ fontSize: 32, marginTop: 14 }}>{c.name}</h2>
        <Mono style={{ marginTop: 4, display: "block" }}>{session.booked} booked · {session.capacity - session.booked} open</Mono>

        <div style={{ marginTop: 18 }}>
          {roster.map((r, i) => (
            <button key={r.id + i} onClick={() => r.memberId && openMember && openMember(window.NADI_ADMIN.MEMBERS.find((m) => m.id === r.memberId))} className="press" style={{
              width: "100%", textAlign: "left",
              padding: "12px 4px",
              borderBottom: "1px solid var(--rule)",
              display: "grid", gridTemplateColumns: "36px 1fr auto", gap: 12, alignItems: "center",
              background: "transparent",
            }}>
              <Avatar name={r.name} initials={r.initials} tone={r.tone} size={36} />
              <div>
                <div style={{ fontFamily: "Newsreader, serif", fontSize: 17, color: "var(--ink)" }}>{r.name}{nameSuffix}</div>
                <Mono>{i < 4 ? "checked in" : "booked"}</Mono>
              </div>
              <button onClick={(e) => { e.stopPropagation(); showToast && showToast(i < 4 ? "Un-checked." : "Checked in."); }} className="press" style={{
                padding: "6px 12px",
                border: `1px solid ${i < 4 ? "var(--rule)" : "var(--ink)"}`,
                background: i < 4 ? "transparent" : "var(--ink)",
                color: i < 4 ? "var(--ink)" : "var(--bg)",
                fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.08em",
                textTransform: "lowercase",
              }}>{i < 4 ? "uncheck" : "check in"}</button>
            </button>
          ))}
        </div>

        <div style={{ marginTop: 20 }}>
          <Button variant="ghost" size="md" fullWidth onClick={() => showToast && showToast("Walk-in dialog opened.")}>+ Add walk-in</Button>
        </div>
      </div>
    </Sheet>
  );
}

// ── Add session sheet ────────────────────────────────────────────
function AdminAddSessionSheet({ open, onClose, showToast }) {
  const [classId, setClassId] = useState("hatha");
  const [coachId, setCoachId] = useState("ayu");
  const [day, setDay] = useState(TODAY_DAY);
  const [time, setTime] = useState("18:00");
  const [room, setRoom] = useState(0);
  const [capacity, setCapacity] = useState(14);

  return (
    <Sheet open={open} onClose={onClose} maxHeight="92%">
      <div style={{ padding: "10px 22px 26px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Mono>schedule · add session</Mono>
          <button onClick={onClose} className="press" style={{ background: "transparent", padding: 6 }}><Mono>close ×</Mono></button>
        </div>
        <h2 className="display" style={{ fontSize: 32, marginTop: 12 }}>New session.</h2>

        <div style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 18 }}>
          <div>
            <Mono>class type</Mono>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 8 }}>
              {window.NADI.CLASS_TYPES.map((c) => (
                <Chip key={c.id} active={classId === c.id} onClick={() => setClassId(c.id)}>{c.name.toLowerCase()}</Chip>
              ))}
            </div>
          </div>
          <div>
            <Mono>teacher</Mono>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 8 }}>
              {window.NADI.COACHES.map((co) => (
                <Chip key={co.id} active={coachId === co.id} onClick={() => setCoachId(co.id)}>{co.firstName.toLowerCase()}</Chip>
              ))}
            </div>
          </div>
          <div>
            <Mono>day</Mono>
            <div style={{ display: "flex", gap: 4, marginTop: 8, flexWrap: "wrap" }}>
              {DAYS_SHORT.map((d, i) => (
                <Chip key={i} active={day === i} onClick={() => setDay(i)}>{d.toLowerCase()}</Chip>
              ))}
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <label>
              <Mono>time</Mono>
              <input value={time} onChange={(e) => setTime(e.target.value)} style={{
                marginTop: 6, width: "100%", borderBottom: "1px solid var(--rule)", padding: "8px 0",
                fontFamily: "Newsreader, serif", fontSize: 22, color: "var(--ink)",
              }} />
            </label>
            <label>
              <Mono>capacity</Mono>
              <input type="number" value={capacity} onChange={(e) => setCapacity(parseInt(e.target.value, 10) || 0)} style={{
                marginTop: 6, width: "100%", borderBottom: "1px solid var(--rule)", padding: "8px 0",
                fontFamily: "Newsreader, serif", fontSize: 22, color: "var(--ink)",
              }} />
            </label>
          </div>
          <div>
            <Mono>room</Mono>
            <div style={{ display: "flex", gap: 6, marginTop: 8 }}>
              {window.NADI.STUDIOS.map((st, i) => (
                <Chip key={st.id} active={room === i} onClick={() => setRoom(i)}>{st.name.toLowerCase()}</Chip>
              ))}
            </div>
          </div>
        </div>

        <div style={{ marginTop: 26, 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;
            const dateStr = "2026-05-" + String(DATES_THIS_WEEK[day]).padStart(2, "0");
            const payload = {
              date: dateStr,
              time: time,
              class_id: classId,
              coach_id: coachId,
              room: window.NADI.STUDIOS[room].full,
              capacity: capacity,
              booked: 0
            };
            try {
              const res = await fetch("/api/admin/sessions", {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                  "Authorization": `Bearer ${token}`
                },
                body: JSON.stringify(payload)
              });
              if (res.ok) {
                showToast && showToast("Session created.");
                if (window.NADI_RELOAD_SCHEDULE) {
                  await window.NADI_RELOAD_SCHEDULE();
                }
                onClose();
              } else {
                const err = await res.json();
                showToast && showToast(err.detail || "Failed to create session.");
              }
            } catch (e) {
              console.error(e);
              showToast && showToast("Error connecting to server.");
            }
          }}>Add session</Button>
        </div>
      </div>
    </Sheet>
  );
}

Object.assign(window, {
  AdminScheduleScreen, AdminSessionRow,
  AdminSessionSheet, AdminRosterSheet, AdminAddSessionSheet,
});
