// screens-saved.jsx — favourites: classes + teachers (with quick next-session)

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

function SavedScreen({ user, openClassSheet, toggleSavedClass, toggleSavedCoach, setTab, openFindFriends, openFriendProfile, unfollowFriend }) {
  const [seg, setSeg] = useState("classes"); // "classes" | "teachers" | "friends"

  return (
    <div className="screen-fade" style={{ flex: 1, display: "flex", flexDirection: "column" }}>
      <TopBar eyebrow="saved" title="Your shortlist." />
      <PullToRefresh>
        <div style={{ flex: 1, padding: "16px 22px 24px" }}>
          {/* Segmented control */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", border: "1px solid var(--rule)", marginBottom: 20 }}>
            {[
              ["classes",  "Classes",  user.savedClasses.length],
              ["teachers", "Teachers", user.savedCoaches.length],
              ["friends",  "Friends",  user.following.length],
            ].map(([id, label, n]) => (
              <button key={id} onClick={() => setSeg(id)} className="press" style={{
                padding: "12px 6px",
                background: seg === id ? "var(--ink)" : "transparent",
                color: seg === id ? "var(--bg)" : "var(--ink-soft)",
                fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
                letterSpacing: "0.08em", textTransform: "uppercase",
                display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
              }}>
                <span>{label}</span>
                <span style={{ opacity: 0.6 }}>{n}</span>
              </button>
            ))}
          </div>

          {seg === "classes"  && <SavedClassList user={user} openClassSheet={openClassSheet} toggleSavedClass={toggleSavedClass} setTab={setTab} />}
          {seg === "teachers" && <SavedCoachList user={user} openClassSheet={openClassSheet} toggleSavedCoach={toggleSavedCoach} setTab={setTab} />}
          {seg === "friends"  && <SavedFriendsList user={user} openFindFriends={openFindFriends} openFriendProfile={openFriendProfile} />}
        </div>
      </PullToRefresh>
    </div>
  );
}

// ── Friends list ────────────────────────────────────────────────
function SavedFriendsList({ user, openFindFriends, openFriendProfile }) {
  const friends = user.following.map((id) => findFriend(id)).filter(Boolean);
  const pending = user.pendingFollowers.map((id) => findFriend(id)).filter(Boolean);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      {/* Find friends CTA */}
      <button onClick={openFindFriends} className="press" style={{
        width: "100%", textAlign: "left",
        padding: 18,
        background: "var(--ink)", color: "var(--bg)",
        border: "1px solid var(--ink)",
        display: "flex", justifyContent: "space-between", alignItems: "center",
        gap: 12,
      }}>
        <div>
          <Mono color="rgba(248,241,225,0.6)">find your circle</Mono>
          <div style={{ fontFamily: "Newsreader, serif", fontSize: 22, fontWeight: 400, marginTop: 6 }}>
            <em style={{ fontStyle: "italic", color: "#E8A07F" }}>Follow</em> someone.
          </div>
        </div>
        <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="9" cy="9" r="5"/><path d="M12.5 12.5L18 18"/><path d="M9 7v4M7 9h4"/>
        </svg>
      </button>

      {/* Pending requests */}
      {pending.length > 0 && (
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
            <Eyebrow color="var(--primary)">requests · {pending.length}</Eyebrow>
            <Mono>waiting on you</Mono>
          </div>
          <div style={{ border: "1px solid var(--rule)" }}>
            {pending.map((p, i) => (
              <div key={p.id} style={{
                padding: "12px 14px",
                background: "var(--surface)",
                display: "grid", gridTemplateColumns: "40px 1fr auto", gap: 12, alignItems: "center",
                borderBottom: i < pending.length - 1 ? "1px solid var(--rule)" : "none",
              }}>
                <Avatar name={p.name} initials={p.initials} tone={p.tone} size={40} />
                <div>
                  <div style={{ fontFamily: "Newsreader, serif", fontSize: 17, color: "var(--ink)" }}>{p.name}</div>
                  <Mono>{p.mutual} mutual · sent {p.since}</Mono>
                </div>
                <div style={{ display: "flex", gap: 6 }}>
                  <button className="press" onClick={() => openFriendProfile && openFriendProfile({ ...p, isPending: true, action: "accept" })} style={{
                    padding: "8px 12px", background: "var(--ink)", color: "var(--bg)",
                    fontFamily: "'JetBrains Mono', monospace", fontSize: 10,
                    letterSpacing: "0.06em", textTransform: "lowercase",
                  }}>follow back</button>
                  <button className="press" onClick={() => openFriendProfile && openFriendProfile({ ...p, isPending: true, action: "decline" })} style={{
                    padding: "8px 12px", background: "transparent", color: "var(--ink-soft)",
                    border: "1px solid var(--rule)",
                    fontFamily: "'JetBrains Mono', monospace", fontSize: 10,
                    letterSpacing: "0.06em", textTransform: "lowercase",
                  }}>decline</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Following list */}
      {friends.length > 0 && (
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
            <Eyebrow>following · {friends.length}</Eyebrow>
            <Mono>your circle</Mono>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {friends.map((f) => {
              // Find a class this friend is going to (next one)
              const sharedNext = window.NADI.SCHEDULE
                .filter((s) => s.friends.includes(f.id))
                .sort((a, b) => window.NADI_HELPERS.minutesUntil(a) - window.NADI_HELPERS.minutesUntil(b))[0];
              return (
                <button key={f.id} onClick={() => openFriendProfile && openFriendProfile(f)} className="press" style={{
                  width: "100%", textAlign: "left",
                  padding: "14px 16px",
                  background: "var(--bg)", border: "1px solid var(--rule)",
                  display: "grid", gridTemplateColumns: "42px 1fr auto", gap: 12, alignItems: "center",
                }}>
                  <Avatar name={f.name} initials={f.initials} tone={f.tone} size={42} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontFamily: "Newsreader, serif", fontSize: 17, color: "var(--ink)" }}>{f.firstName || f.name}</div>
                    {sharedNext ? (
                      <Mono>next: {window.NADI_HELPERS.DAYS_SHORT[sharedNext.day].toLowerCase()} {sharedNext.time} · {window.NADI_HELPERS.findClass(sharedNext.classId).name.toLowerCase()}</Mono>
                    ) : (
                      <Mono>no upcoming classes</Mono>
                    )}
                  </div>
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="var(--ink-soft)" strokeWidth="1.4" strokeLinecap="round"><path d="M5 2l5 5-5 5"/></svg>
                </button>
              );
            })}
          </div>
        </div>
      )}

      {friends.length === 0 && pending.length === 0 && (
        <EmptyState title="No friends yet."
          body="Follow someone to see when they're on the mat. Tap a face in any class to start."
          cta="Find friends" onCta={openFindFriends} />
      )}
    </div>
  );
}

function SavedClassList({ user, openClassSheet, toggleSavedClass, setTab }) {
  if (user.savedClasses.length === 0) return <EmptyState
    title="Nothing saved yet."
    body="Tap the ▢ on any class to keep it close. We'll surface the next time it's on."
    cta="Browse classes" onCta={() => setTab("book")}
  />;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {user.savedClasses.map((id) => {
        const c = findClass(id);
        const nextSess = window.NADI.SCHEDULE
          .filter((s) => s.classId === id && minutesUntil(s) > 0)
          .sort((a, b) => minutesUntil(a) - minutesUntil(b))[0];
        const accent = c.color === "primary" ? "var(--primary)" : c.color === "accent" ? "var(--accent)" : "var(--muted)";
        return (
          <div key={id} style={{
            background: "var(--bg)", border: "1px solid var(--rule)",
            borderLeft: `3px solid ${accent}`,
            padding: 18,
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <Mono>{c.duration} min · {c.level.toLowerCase()}</Mono>
              <button onClick={() => toggleSavedClass(id)} className="press" style={{ padding: 4 }}>
                <FavIcon size={14} active />
              </button>
            </div>
            <h3 className="display" style={{ fontSize: 30, marginTop: 8, color: "var(--ink)" }}>{c.name}</h3>
            <p style={{ fontFamily: "Newsreader, serif", fontSize: 15, color: "var(--ink-soft)", marginTop: 6, fontWeight: 300, lineHeight: 1.45 }}>{c.tagline}.</p>

            {nextSess ? (
              <button onClick={() => openClassSheet(nextSess)} className="press" style={{
                marginTop: 16, width: "100%",
                display: "flex", justifyContent: "space-between", alignItems: "center",
                padding: "12px 14px",
                background: "var(--surface)", border: "1px solid var(--rule)",
                textAlign: "left",
              }}>
                <div>
                  <Mono color="var(--primary)">next session</Mono>
                  <div style={{ fontFamily: "Newsreader, serif", fontSize: 17, color: "var(--ink)", marginTop: 4 }}>
                    {DAYS_SHORT[nextSess.day]} · {nextSess.time} · {findCoach(nextSess.coachId).firstName}
                  </div>
                </div>
                <Mono color="var(--ink)">{fmtCountdown(minutesUntil(nextSess))} →</Mono>
              </button>
            ) : (
              <div style={{ marginTop: 14 }}>
                <Mono>not scheduled this week</Mono>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function SavedCoachList({ user, openClassSheet, toggleSavedCoach, setTab }) {
  if (user.savedCoaches.length === 0) return <EmptyState
    title="No teachers saved."
    body="Tap a teacher to save them. We'll show you their upcoming classes first."
    cta="Browse classes" onCta={() => setTab("book")}
  />;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {user.savedCoaches.map((id) => {
        const co = findCoach(id);
        const nextSess = window.NADI.SCHEDULE
          .filter((s) => s.coachId === id && minutesUntil(s) > 0)
          .sort((a, b) => minutesUntil(a) - minutesUntil(b))[0];
        return (
          <div key={id} style={{ background: "var(--bg)", border: "1px solid var(--rule)", padding: 18 }}>
            <div style={{ display: "flex", gap: 16, alignItems: "flex-start" }}>
              <Avatar name={co.name} initials={co.initials} tone={co.tone} size={56} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <Mono>{co.yrs} yrs teaching</Mono>
                  <button onClick={() => toggleSavedCoach(id)} className="press" style={{ padding: 4 }}>
                    <FavIcon size={14} active />
                  </button>
                </div>
                <h3 className="display" style={{ fontSize: 26, marginTop: 4 }}>{co.name}</h3>
                <Mono color="var(--primary)">{co.title.toLowerCase()}</Mono>
              </div>
            </div>
            <p style={{ fontFamily: "Newsreader, serif", fontSize: 15, color: "var(--ink-soft)", marginTop: 14, fontWeight: 300, lineHeight: 1.5 }}>{co.bio}</p>
            {nextSess && (
              <button onClick={() => openClassSheet(nextSess)} className="press" style={{
                marginTop: 14, width: "100%", textAlign: "left",
                display: "flex", justifyContent: "space-between", alignItems: "center",
                padding: "12px 14px",
                background: "var(--surface)", border: "1px solid var(--rule)",
              }}>
                <div>
                  <Mono color="var(--primary)">teaching next</Mono>
                  <div style={{ fontFamily: "Newsreader, serif", fontSize: 17, color: "var(--ink)", marginTop: 4 }}>
                    {findClass(nextSess.classId).name} · {DAYS_SHORT[nextSess.day]} {nextSess.time}
                  </div>
                </div>
                <Mono color="var(--ink)">{fmtCountdown(minutesUntil(nextSess))} →</Mono>
              </button>
            )}
          </div>
        );
      })}
    </div>
  );
}

function EmptyState({ title, body, cta, onCta }) {
  return (
    <div style={{ padding: "60px 20px", textAlign: "center", border: "1px dashed var(--rule)" }}>
      <BreathDot size={32} />
      <h3 style={{ fontFamily: "Newsreader, serif", fontSize: 26, fontWeight: 400, marginTop: 18, color: "var(--ink)" }}>{title}</h3>
      <p style={{ fontFamily: "Newsreader, serif", fontSize: 15, color: "var(--ink-soft)", marginTop: 8, fontWeight: 300, lineHeight: 1.5 }}>{body}</p>
      {cta && <div style={{ marginTop: 22 }}><Button variant="primary" size="md" onClick={onCta}>{cta}</Button></div>}
    </div>
  );
}

Object.assign(window, { SavedScreen, EmptyState, SavedFriendsList });
