// screens-me.jsx — member account: credits, packs, history, stats, settings

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

function MeScreen({ user, setUser, setTab, openCheckout, onSignOut, openSettings, showToast, enterAdmin, upcomingBookings }) {
  const getAppToday = window.NADI_HELPERS.getAppToday;
  const parseLocalDate = window.NADI_HELPERS.parseLocalDate;
  
  const total = (user.creditPacks || []).reduce((s, p) => s + p.credits, 0);

  // Parse local date time for sorting
  const parseLocalDateTime = (dateStr, timeStr) => {
    if (!dateStr || !timeStr) return null;
    const [year, month, day] = dateStr.split('-').map(Number);
    const [hours, minutes] = timeStr.split(':').map(Number);
    return new Date(year, month - 1, day, hours, minutes);
  };

  const upcoming = (upcomingBookings || [])
    .map(b => {
      const s = window.NADI.SCHEDULE.find(x => x.id === b.session_id);
      if (!s) return null;
      return {
        ...s,
        bookingId: b.id,
        date: b.date,
      };
    })
    .filter(Boolean)
    .filter(s => {
      const d = parseLocalDateTime(s.date, s.time);
      return d && d >= getAppToday();
    })
    .sort((a, b) => parseLocalDateTime(a.date, a.time) - parseLocalDateTime(b.date, b.time));

  return (
    <PullToRefresh>
      <div style={{ paddingBottom: 24 }}>
        {/* Hero */}
        <section style={{ padding: "8px 22px 0" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <Eyebrow>my account</Eyebrow>
            <button onClick={openSettings} className="press" style={{ padding: 6 }}>
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
                <circle cx="10" cy="10" r="2.2"/>
                <path d="M10 2v2M10 16v2M2 10h2M16 10h2M4.4 4.4l1.4 1.4M14.2 14.2l1.4 1.4M4.4 15.6l1.4-1.4M14.2 5.8l1.4-1.4"/>
              </svg>
            </button>
          </div>
          <div style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 18 }}>
            <Avatar name={user.name} initials={user.initials} tone="var(--primary)" size={64} anon={!user.visibleByDefault} />
            <div>
              <h1 className="display" style={{ fontSize: 36, color: "var(--ink)" }}>
                {user.visibleByDefault ? user.name.split(" ")[0] : "Anonymous"}
              </h1>
              <Mono>member since {user.joined.toLowerCase()}</Mono>
            </div>
          </div>

          {/* Default privacy toggle — applies to every new booking */}
          <div style={{
            marginTop: 18,
            padding: "14px 16px",
            border: "1px solid var(--rule)",
            background: user.visibleByDefault ? "transparent" : "var(--surface)",
            display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
          }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <Mono color="var(--ink-soft)">default for new bookings</Mono>
              </div>
              <div style={{ marginTop: 4, fontFamily: "Newsreader, serif", fontSize: 17, color: "var(--ink)" }}>
                {user.visibleByDefault ? "Visible to your circle" : "Going anonymously"}
              </div>
              <Mono style={{ marginTop: 2 }}>
                {user.visibleByDefault ? "friends see you in class lists" : "you appear as +1 anon"} · override per class
              </Mono>
            </div>
            <ToggleSwitch
              defaultOn={!user.visibleByDefault}
              key={String(user.visibleByDefault)}
              onChange={(v) => {
                if (!setUser) return;
                setUser({ ...user, visibleByDefault: !v });
                showToast && showToast(v ? "Going incognito by default." : "Visible to your friends.");
              }}
            />
          </div>
        </section>

        {/* Credits big card */}
        <section style={{ padding: "24px 22px 0" }}>
          <div style={{
            background: "var(--ink)", color: "var(--bg)",
            padding: "26px 22px 20px",
            position: "relative", overflow: "hidden",
          }}>
            <span aria-hidden style={{
              position: "absolute", left: -40, bottom: -40,
              width: 160, height: 160, 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)">credits remaining</Mono>
              <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginTop: 6 }}>
                <span className="display" style={{ fontSize: 96, color: "#E8A07F", letterSpacing: "-0.04em", lineHeight: 0.85 }}>{total}</span>
                <Mono color="rgba(248,241,225,0.6)">credit{total === 1 ? "" : "s"}</Mono>
              </div>
              <div style={{ marginTop: 16, display: "flex", gap: 8 }}>
                <button onClick={() => openCheckout()} className="press" style={{
                  flex: 1, padding: "12px 14px",
                  background: "var(--primary)", color: "var(--primary-ink)",
                  fontFamily: "Geist, sans-serif", fontSize: 12,
                  letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 500,
                  border: 0,
                }}>+ Buy a pack</button>
                <button onClick={() => setTab("book")} className="press" style={{
                  flex: 1, padding: "12px 14px",
                  background: "transparent", color: "var(--bg)",
                  border: "1px solid rgba(248,241,225,0.4)",
                  fontFamily: "Geist, sans-serif", fontSize: 12,
                  letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 500,
                }}>Book a class</button>
              </div>
            </div>
          </div>
        </section>

        {/* Stats row */}
        <section style={{ padding: "24px 22px 0" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 1, background: "var(--rule)", border: "1px solid var(--rule)" }}>
            <StatCell label="streak" value={user.streak} suffix="weeks" accent />
            <StatCell label="this month" value={(user.history || []).filter(h => h.date && (h.date.includes(new Date().toLocaleDateString("en-US", { month: "short" })) || h.date.includes("May") || h.date.includes("may"))).length} suffix="visits" />
            <StatCell label="lifetime" value={user.visits} suffix="classes" />
          </div>
        </section>

        {/* Activity sparkline */}
        <section style={{ padding: "28px 22px 0" }}>
          <Eyebrow>activity · last 6 months</Eyebrow>
          <ActivityBars monthly={user.monthly} />
        </section>

        {/* Active packs */}
        <section style={{ padding: "28px 22px 0" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14 }}>
            <Eyebrow>active packs</Eyebrow>
            <button onClick={() => openCheckout()} className="press" style={{ background: "transparent" }}>
              <Mono color="var(--primary)">+ add</Mono>
            </button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {(user.creditPacks || [])
              .slice().sort((a, b) => new Date(a.expires) - new Date(b.expires))
              .map((p, i) => {
                const getStartOfDay = (dateObj) => new Date(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate());
                const expiryDate = parseLocalDate(p.expires);
                const todayDate = getStartOfDay(getAppToday());
                const daysLeft = Math.max(0, Math.round((expiryDate - todayDate) / 86400000));
                
                const pct = Math.round((p.credits / p.total) * 100);
                const urgent = daysLeft <= 10;
                return (
                  <div key={i} style={{
                    padding: 18,
                    background: i === 0 ? "var(--surface)" : "var(--bg)",
                    border: "1px solid var(--rule)",
                    borderLeft: i === 0 ? "3px solid var(--primary)" : "1px solid var(--rule)",
                  }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                      <Mono color={i === 0 ? "var(--primary)" : "var(--ink-soft)"}>{i === 0 ? "spending next" : "queued"}</Mono>
                      <Mono color={urgent ? "var(--primary)" : "var(--ink-soft)"}>{daysLeft} days left</Mono>
                    </div>
                    <h3 style={{ fontFamily: "Newsreader, serif", fontSize: 22, fontWeight: 400, marginTop: 8, color: "var(--ink)" }}>{p.packageName}</h3>
                    <div style={{ marginTop: 4, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                      <Mono>{p.credits} of {p.total} credits</Mono>
                      <Mono>{pct}%</Mono>
                    </div>
                    <div style={{ marginTop: 10, height: 3, background: "var(--surface-2)", position: "relative" }}>
                      <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${pct}%`, background: "var(--primary)" }} />
                    </div>
                  </div>
                );
              })}
          </div>
        </section>

        {/* Upcoming + History tabs */}
        <section style={{ padding: "28px 22px 0" }}>
          <Eyebrow>your classes</Eyebrow>
          <div style={{ marginTop: 14, display: "flex", flexDirection: "column", gap: 0 }}>
            {upcoming.length > 0 && (
              <>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
                  <Mono>upcoming</Mono>
                  <Mono>tap to change privacy</Mono>
                </div>
                {upcoming.map((s) => <ClassRow key={s.id + (s.date || "")} s={s} upcoming user={user} setUser={setUser} showToast={showToast} />)}
                <div style={{ height: 18 }} />
              </>
            )}
            <Mono style={{ display: "block", marginBottom: 8 }}>history</Mono>
            {(user.history || []).map((h) => <HistoryRow key={h.id} h={h} />)}
          </div>
        </section>

        <section style={{ padding: "30px 22px 0" }}>
          {enterAdmin && (
            <div style={{ marginBottom: 12 }}>
              <button onClick={enterAdmin} className="press" style={{
                width: "100%",
                padding: "16px 18px",
                background: "var(--ink)", color: "var(--bg)",
                display: "flex", justifyContent: "space-between", alignItems: "center",
                gap: 12,
                border: "1px solid var(--ink)",
              }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 12 }}>
                  <span className="breath" style={{ width: 7, height: 7, background: "var(--primary)" }} />
                  <span style={{ fontFamily: "Newsreader, serif", fontSize: 17, textAlign: "left" }}>
                    Switch to staff mode
                  </span>
                </span>
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "rgba(248,241,225,0.7)" }}>
                  owner →
                </span>
              </button>
            </div>
          )}
          <Button variant="ghost" size="md" fullWidth onClick={onSignOut}>Sign out</Button>
        </section>
      </div>
    </PullToRefresh>
  );
}

function StatCell({ label, value, suffix, accent }) {
  return (
    <div style={{ background: "var(--bg)", padding: "16px 14px" }}>
      <Mono>{label}</Mono>
      <div style={{
        fontFamily: "Newsreader, serif", fontSize: 38, fontWeight: 400, lineHeight: 1,
        color: accent ? "var(--primary)" : "var(--ink)",
        marginTop: 6, letterSpacing: "-0.02em",
      }}>{value}</div>
      <Mono style={{ marginTop: 4 }}>{suffix}</Mono>
    </div>
  );
}

function ActivityBars({ monthly }) {
  const max = Math.max(1, ...monthly.map((x) => x.n));
  return (
    <div style={{ marginTop: 12, background: "var(--bg)", border: "1px solid var(--rule)", padding: "18px 16px" }}>
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${monthly.length}, 1fr)`, alignItems: "end", gap: 10, height: 120 }}>
        {monthly.map((row, i) => {
          const h = Math.round((row.n / max) * 100);
          const isLast = i === monthly.length - 1;
          return (
            <div key={row.m} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
              <span style={{ fontFamily: "Newsreader, serif", fontSize: 14, color: "var(--ink)" }}>{row.n}</span>
              <div style={{ width: "100%", height: h, background: isLast ? "var(--primary)" : "var(--accent)", opacity: isLast ? 1 : 0.55 }} />
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 8, display: "grid", gridTemplateColumns: `repeat(${monthly.length}, 1fr)`, gap: 10 }}>
        {monthly.map((row) => <Mono key={row.m} style={{ textAlign: "center" }}>{row.m.toLowerCase()}</Mono>)}
      </div>
    </div>
  );
}

function ClassRow({ s, upcoming, user, setUser, showToast }) {
  const c = findClass(s.classId), co = findCoach(s.coachId);
  const privacy = (user && user.bookingPrivacy && user.bookingPrivacy[s.id])
    || (user && user.visibleByDefault ? "self" : "anon");
  const isAnon = privacy === "anon";
  const flipPrivacy = (e) => {
    e && e.stopPropagation();
    if (!user || !setUser) return;
    const next = isAnon ? "self" : "anon";
    setUser({
      ...user,
      bookingPrivacy: { ...(user.bookingPrivacy || {}), [s.id]: next },
    });
    showToast && showToast(next === "anon" ? "Going anonymously." : "Visible to your circle.");
  };

  const dateStr = s.date ? window.NADI_HELPERS.parseLocalDate(s.date).toLocaleDateString("en-GB", { weekday: "short", day: "2-digit", month: "short" }).toLowerCase() : DAYS_SHORT[s.day].toLowerCase();

  return (
    <div style={{
      padding: "14px 0",
      borderBottom: "1px solid var(--rule)",
      display: "grid", gridTemplateColumns: "62px 1fr auto", gap: 12, alignItems: "center",
    }}>
      <div>
        <div style={{ fontFamily: "Newsreader, serif", fontSize: 20, fontWeight: 400, lineHeight: 1, color: "var(--ink)" }}>{s.time}</div>
        <Mono>{dateStr}</Mono>
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: "Newsreader, serif", fontSize: 18, color: "var(--ink)" }}>{c.name}</div>
        <Mono>{co.firstName.toLowerCase()} · {s.roomShort.toLowerCase()}</Mono>
      </div>
      {upcoming ? (
        <button onClick={flipPrivacy} className="press" aria-label={isAnon ? "Going anonymously, tap to make visible" : "Visible, tap to go anonymous"} style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "7px 10px 7px 7px",
          border: `1px solid ${isAnon ? "var(--rule-strong)" : "var(--primary)"}`,
          background: isAnon ? "var(--surface)" : "transparent",
          color: isAnon ? "var(--ink-soft)" : "var(--primary)",
          borderRadius: 999,
        }}>
          <Avatar size={22} initials={user && user.initials} tone="var(--primary)" anon={isAnon} />
          <span style={{
            fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.08em",
            textTransform: "lowercase",
          }}>{isAnon ? "anon" : "visible"}</span>
        </button>
      ) : null}
    </div>
  );
}

function HistoryRow({ h }) {
  const c = findClass(h.classId), co = findCoach(h.coachId);
  return (
    <div style={{
      padding: "14px 0",
      borderBottom: "1px solid var(--rule)",
      display: "grid", gridTemplateColumns: "1fr auto", gap: 12, alignItems: "center",
    }}>
      <div>
        <div style={{ fontFamily: "Newsreader, serif", fontSize: 17, color: "var(--ink)" }}>{c.name}</div>
        <Mono>{co.firstName.toLowerCase()} · {h.roomShort.toLowerCase()}</Mono>
      </div>
      <Mono>{h.date.toLowerCase()}</Mono>
    </div>
  );
}

Object.assign(window, { MeScreen });
