// screens-admin-shell.jsx — Admin shell (tab bar, top strip) + Now screen

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

// ── Admin tab bar (4 tabs, distinct from member bar) ─────────────────
const ADMIN_TAB_DEFS = [
  { id: "now",      label: "Now" },
  { id: "schedule", label: "Schedule" },
  { id: "people",   label: "People" },
  { id: "more",     label: "More" },
];

function AdminTabIcon({ id, active }) {
  const stroke = active ? "var(--bg)" : "rgba(248,241,225,0.55)";
  const sw = 1.4;
  if (id === "now") return (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <circle cx="11" cy="11" r="3" fill={active ? "var(--primary)" : "none"} stroke={active ? "var(--primary)" : stroke}/>
      <circle cx="11" cy="11" r="8.5"/>
      <path d="M11 4v2M11 16v2M4 11h2M16 11h2"/>
    </svg>
  );
  if (id === "schedule") return (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="16" height="14" rx="0.5"/>
      <path d="M3 9h16"/>
      <path d="M7 3v4M15 3v4"/>
    </svg>
  );
  if (id === "people") return (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <circle cx="8" cy="8" r="3.2" fill={active ? "var(--primary)" : "none"} stroke={active ? "var(--primary)" : stroke}/>
      <circle cx="15.5" cy="9.5" r="2.5"/>
      <path d="M2 19c1.4-3.2 4-4.6 6.5-4.6S13.7 16 15 19"/>
      <path d="M15 14.6c2 0 4 1.3 5 4.4"/>
    </svg>
  );
  if (id === "more") return (
    <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke={stroke} strokeWidth={sw}>
      <circle cx="6" cy="11" r="1.6" fill={stroke}/>
      <circle cx="11" cy="11" r="1.6" fill={stroke}/>
      <circle cx="16" cy="11" r="1.6" fill={stroke}/>
    </svg>
  );
  return null;
}

function AdminTabBar({ tab, setTab }) {
  return (
    <nav aria-label="Admin" style={{
      position: "absolute", left: 0, right: 0, bottom: 0,
      paddingBottom: "calc(8px + var(--safe-bot))",
      paddingTop: 8,
      background: "var(--ink)",
      borderTop: "1px solid #2A1F18",
      display: "grid", gridTemplateColumns: "repeat(4, 1fr)",
      zIndex: 20,
    }}>
      {ADMIN_TAB_DEFS.map((t) => {
        const active = t.id === tab;
        return (
          <button key={t.id} onClick={() => setTab(t.id)} className="press" style={{
            display: "flex", flexDirection: "column", alignItems: "center", gap: 4,
            paddingTop: 8, paddingBottom: 4,
            background: "transparent",
            color: active ? "var(--bg)" : "rgba(248,241,225,0.55)",
          }}>
            <AdminTabIcon id={t.id} active={active} />
            <span style={{
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 10, letterSpacing: "0.1em",
              textTransform: "uppercase",
              fontWeight: active ? 500 : 400,
            }}>{t.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// ── Admin top strip (always visible at top) ────────────────────────
function AdminTopStrip({ admin, onExitAdmin }) {
  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "10px 18px",
      background: "var(--ink)", color: "var(--bg)",
      borderBottom: "1px solid #2A1F18",
    }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
        <span style={{
          width: 22, height: 22, borderRadius: "50%",
          background: "var(--bg)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          overflow: "hidden", flexShrink: 0,
        }}>
          <img src="mobile/logo-nadi.png" alt="" style={{
            width: 22, height: 22, display: "block",
            mixBlendMode: "multiply",
          }} />
        </span>
        <span className="breath" style={{ width: 7, height: 7, background: "var(--primary)" }} />
        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "rgba(248,241,225,0.85)" }}>
          staff mode · {admin.role.toLowerCase()}
        </span>
      </span>
      <button onClick={onExitAdmin} className="press" style={{
        display: "inline-flex", alignItems: "center", gap: 8,
        background: "transparent", padding: "4px 6px",
        color: "rgba(248,241,225,0.7)",
      }}>
        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "lowercase" }}>
          exit
        </span>
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M3 3l6 6M9 3l-6 6"/></svg>
      </button>
    </div>
  );
}

// ── NOW SCREEN ─────────────────────────────────────────────────────
function AdminNowScreen({ admin, openMember, openSession }) {
  const today = window.NADI_ADMIN.todaysSessions();
  const liveOrUpcoming = today.filter((s) => true);
  const rev = window.NADI_ADMIN.TODAY_REVENUE;
  const yest = window.NADI_ADMIN.YESTERDAY_REVENUE;
  const diff = rev - yest;
  const diffPct = Math.round((diff / yest) * 100);

  return (
    <div className="screen-fade scroll" style={{ flex: 1, paddingBottom: 24 }}>
      {/* Greeting */}
      <section style={{ padding: "12px 22px 18px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <Mono>{DAYS_LONG[TODAY_DAY].toLowerCase()} · {String(DATES_THIS_WEEK[TODAY_DAY]).padStart(2, "0")} {new Date().toLocaleDateString("en-GB", { month: "short" }).toLowerCase()}</Mono>
          <Mono>{String(TODAY_HOUR).padStart(2, "0")}:{String(TODAY_MIN).padStart(2, "0")} · live</Mono>
        </div>
        <h1 className="display stretch-in" style={{ fontSize: 42, marginTop: 14, letterSpacing: "-0.025em" }}>
          The floor, <em style={{ fontStyle: "italic", color: "var(--primary)" }}>now.</em>
        </h1>
      </section>

      {/* Revenue pulse */}
      <section style={{ padding: "0 22px 22px" }}>
        <div style={{ background: "var(--ink)", color: "var(--bg)", padding: "22px 22px 18px", position: "relative", overflow: "hidden" }}>
          <span aria-hidden style={{
            position: "absolute", right: -60, top: -40,
            width: 200, height: 200, borderRadius: "50%",
            background: "var(--primary)", opacity: 0.14,
            animation: "nadi-breath 8s ease-in-out infinite",
          }} />
          <div style={{ position: "relative" }}>
            <Mono color="rgba(248,241,225,0.6)">today · gross revenue</Mono>
            <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginTop: 6 }}>
              <span className="display" style={{ fontSize: 56, color: "#E8A07F", letterSpacing: "-0.03em", lineHeight: 0.9 }}>
                {fmtIDR(rev)}
              </span>
            </div>
            <Mono color={diff > 0 ? "var(--primary)" : "rgba(248,241,225,0.55)"} style={{ marginTop: 6 }}>
              {diff > 0 ? "↑" : "↓"} {Math.abs(diffPct)}% vs yesterday · {fmtIDR(yest)}
            </Mono>

            {/* Hourly pulse */}
            <HourlyPulse rows={window.NADI_ADMIN.TODAY_REVENUE_HOURLY} />
          </div>
        </div>
      </section>

      {/* Live class strip */}
      <section style={{ padding: "0 22px 26px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 12 }}>
          <Eyebrow>today's classes</Eyebrow>
          <Mono>{today.length} sessions</Mono>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {today.map((s) => <LiveSessionRow key={s.id} s={s} onClick={() => openSession && openSession(s)} />)}
        </div>
      </section>

      {/* Churn alerts */}
      <ChurnAlerts openMember={openMember} />

      {/* Quick actions */}
      <section style={{ padding: "0 22px 12px" }}>
        <Eyebrow>quick actions</Eyebrow>
        <div style={{ marginTop: 12, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 1, background: "var(--rule)", border: "1px solid var(--rule)" }}>
          <QuickAction icon="walkin" label="Walk-in sale" sub="add member + pack" />
          <QuickAction icon="book" label="Manual booking" sub="book for a member" />
          <QuickAction icon="cancel" label="Cancel a class" sub="notify attendees" />
          <QuickAction icon="qr" label="QR check-in" sub="scan member code" />
        </div>
      </section>
    </div>
  );
}

function HourlyPulse({ rows }) {
  const max = Math.max(1, ...rows.map((r) => r.v));
  const nowH = new Date().getHours();
  return (
    <div style={{ marginTop: 18 }}>
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${rows.length}, 1fr)`, alignItems: "end", height: 56, gap: 3 }}>
        {rows.map((r) => {
          const isPast = parseInt(r.h, 10) <= nowH;
          const h = r.v > 0 ? Math.max(4, Math.round((r.v / max) * 50)) : 2;
          return (
            <div key={r.h} style={{
              height: h,
              background: r.v > 0 ? "var(--primary)" : (isPast ? "rgba(248,241,225,0.16)" : "rgba(248,241,225,0.08)"),
              opacity: r.v > 0 || isPast ? 1 : 0.6,
            }} />
          );
        })}
      </div>
      <div style={{ marginTop: 6, display: "grid", gridTemplateColumns: `repeat(${rows.length}, 1fr)`, gap: 3 }}>
        {rows.map((r, i) => (
          <Mono key={r.h} color="rgba(248,241,225,0.45)" style={{ textAlign: "center", fontSize: 8.5 }}>
            {(i % 2 === 0) ? r.h : ""}
          </Mono>
        ))}
      </div>
    </div>
  );
}

function LiveSessionRow({ s, onClick }) {
  const c = findClass(s.classId), co = findCoach(s.coachId);
  const checkin = (window.NADI_ADMIN.CHECKINS && window.NADI_ADMIN.CHECKINS[s.id]) || { checked: 0, ready: s.booked };
  const nowTime = `${String(TODAY_HOUR).padStart(2, "0")}:${String(TODAY_MIN).padStart(2, "0")}`;
  const isPast = s.time < nowTime;
  const isNow = !isPast && s.time <= `${String(TODAY_HOUR + 1).padStart(2, "0")}:${String(TODAY_MIN + 30).padStart(2, "0")}`;
  const pct = Math.round((checkin.checked / s.booked) * 100) || 0;

  return (
    <button onClick={onClick} className="press" style={{
      width: "100%", textAlign: "left",
      padding: "14px 16px",
      background: "var(--bg)",
      border: "1px solid var(--rule)",
      borderLeft: `3px solid ${isPast ? "var(--rule-strong)" : isNow ? "var(--primary)" : "var(--accent)"}`,
      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 · {s.roomShort.toLowerCase()}</Mono>
      </div>
      <div style={{ minWidth: 0 }}>
        <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()}</Mono>
        </div>
      </div>
      <div style={{ textAlign: "right" }}>
        {isPast ? (
          <>
            <Mono color="var(--ink)">{checkin.checked}/{s.booked}</Mono>
            <Mono style={{ display: "block", marginTop: 4 }}>checked in</Mono>
          </>
        ) : (
          <>
            <Mono color={isNow ? "var(--primary)" : "var(--ink)"}>{s.booked}/{s.capacity}</Mono>
            <Mono style={{ display: "block", marginTop: 4 }}>{isNow ? "starting" : "booked"}</Mono>
          </>
        )}
      </div>
    </button>
  );
}

function ChurnAlerts({ openMember }) {
  const list = window.NADI_ADMIN.CHURN_LIST;
  return (
    <section style={{ padding: "0 22px 26px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 12 }}>
        <Eyebrow color="var(--primary)">churn watch · 3</Eyebrow>
        <Mono>lapsed members</Mono>
      </div>
      <div style={{ background: "var(--surface)", border: "1px solid var(--rule)" }}>
        {list.slice(0, 3).map((m, i) => (
          <button key={m.id} onClick={() => openMember && openMember(m)} className="press" style={{
            width: "100%", textAlign: "left",
            display: "grid", gridTemplateColumns: "36px 1fr auto", gap: 12, alignItems: "center",
            padding: "12px 16px",
            background: "transparent",
            borderBottom: i < list.length - 1 ? "1px solid var(--rule)" : "none",
          }}>
            <Avatar name={m.name} initials={m.initials} tone={m.tone} size={36} />
            <div>
              <div style={{ fontFamily: "Newsreader, serif", fontSize: 17, color: "var(--ink)" }}>{m.name}</div>
              <Mono>last seen {m.lastVisit.toLowerCase()} · {m.visits} lifetime</Mono>
            </div>
            <div style={{ textAlign: "right" }}>
              <Mono color="var(--primary)">{m.daysSinceVisit}d ago</Mono>
              <Mono style={{ display: "block", marginTop: 2 }}>nudge →</Mono>
            </div>
          </button>
        ))}
      </div>
    </section>
  );
}

function QuickAction({ icon, label, sub, onClick }) {
  return (
    <button onClick={onClick} className="press" style={{
      background: "var(--bg)", padding: "16px 14px", textAlign: "left",
      display: "flex", flexDirection: "column", gap: 8,
      minHeight: 100,
    }}>
      <QAIcon id={icon} />
      <div>
        <div style={{ fontFamily: "Newsreader, serif", fontSize: 17, color: "var(--ink)" }}>{label}</div>
        <Mono>{sub}</Mono>
      </div>
    </button>
  );
}

function QAIcon({ id }) {
  const props = { width: 18, height: 18, viewBox: "0 0 20 20", fill: "none", stroke: "var(--primary)", strokeWidth: 1.4, strokeLinecap: "round", strokeLinejoin: "round" };
  if (id === "walkin") return <svg {...props}><path d="M10 11c2 0 4 1.5 5 4M10 11c-2 0-4 1.5-5 4"/><circle cx="10" cy="6" r="3"/><path d="M14 4v3M15.5 5.5h-3"/></svg>;
  if (id === "book") return <svg {...props}><rect x="3" y="4" width="14" height="13"/><path d="M3 7h14M7 2v4M13 2v4"/><path d="M7 11l2 2 4-4"/></svg>;
  if (id === "cancel") return <svg {...props}><circle cx="10" cy="10" r="7"/><path d="M7 7l6 6M13 7l-6 6"/></svg>;
  if (id === "qr") return <svg {...props}><rect x="3" y="3" width="6" height="6"/><rect x="11" y="3" width="6" height="6"/><rect x="3" y="11" width="6" height="6"/><path d="M11 11h2v2M15 11v2M11 15v2h2M15 15h2"/></svg>;
  return null;
}

Object.assign(window, { ADMIN_TAB_DEFS, AdminTabBar, AdminTopStrip, AdminNowScreen, LiveSessionRow });
