// App shell — sidebar nav + topbar, used after persona is selected

const NAV_ITEMS = [
  { id: "home",         label: "Home",            icon: IconHome,     personas: ["coach", "student", "admin"] },
  { id: "competitions", label: "Competitions",    icon: IconTrophy,   personas: ["coach", "student", "admin"] },
  { id: "schedule",     label: "Schedule",        icon: IconCalendar, personas: ["coach", "student", "admin"] },
  { id: "standings",    label: "Standings",       icon: IconList,     personas: ["coach", "student", "admin"] },
  { id: "bracket",      label: "Bracket",         icon: IconBracket,  personas: ["coach", "student", "admin"] },
  { id: "teams",        label: "Manage Teams",    icon: IconUsers,    personas: ["coach", "admin"] },
  { id: "school",       label: "My School",       icon: IconBuilding, personas: ["coach", "student"] },
  { id: "admin",        label: "Admin Console",   icon: IconCog,      personas: ["admin"] },
];

const Shell = ({ persona, page, onNav, onSwitchPersona, children, onOpenLobby }) => {
  const D = window.NASEF_DATA;
  const personaInfo = window.PERSONAS.find(p => p.id === persona);
  const items = NAV_ITEMS.filter(i => i.personas.includes(persona));
  const liveMatch = D.matches.find(m => m.status === "live");
  const [userMenuOpen, setUserMenuOpen] = React.useState(false);
  const [bellOpen, setBellOpen] = React.useState(false);
  const [mobileNavOpen, setMobileNavOpen] = React.useState(false);
  // Close mobile nav whenever page changes
  React.useEffect(() => { setMobileNavOpen(false); }, [page]);
  const announcements = (D.announcements || []).filter(a => !a.audience || a.audience.includes(persona));

  const PersonaAvatar = ({ p, size = 28 }) => (
    p.avatarImg
      ? <img src={p.avatarImg} alt="" style={{ width: size, height: size, borderRadius: 8, objectFit: "cover", background: "var(--bg-deep)", border: `1px solid ${p.border || "var(--border)"}`, flexShrink: 0 }} />
      : <div className="crest sm" style={{ "--c1": p.color, "--c2": "rgba(0,0,0,0.4)", fontSize: 10, width: size, height: size }}>{p.avatar}</div>
  );

  return (
    <div className="app-shell" style={{ display: "grid", gridTemplateColumns: "236px 1fr", minHeight: "100vh", background: "var(--bg-deep)" }}>
      {/* Mobile nav backdrop */}
      {mobileNavOpen && <div className="mobile-nav-backdrop" onClick={() => setMobileNavOpen(false)} />}
      {/* Sidebar */}
      <aside className={"app-sidebar" + (mobileNavOpen ? " is-open" : "")} style={{
        background: "var(--bg-base)",
        borderRight: "1px solid var(--border-soft)",
        display: "flex", flexDirection: "column",
        position: "sticky", top: 0, height: "100vh",
      }}>
        <div style={{ padding: "18px 18px 14px", borderBottom: "1px solid var(--border-soft)" }}>
          <NASEFMark />
        </div>

        {/* Persona indicator */}
        <div style={{
          margin: "16px 14px 0",
          padding: "10px 12px",
          background: personaInfo.accent,
          border: `1px solid ${personaInfo.border}`,
          borderRadius: "var(--r-md)",
          display: "flex", alignItems: "center", gap: 10,
          cursor: "pointer",
          position: "relative",
        }} onClick={onSwitchPersona}>
          <PersonaAvatar p={personaInfo} size={28} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: personaInfo.color, fontFamily: "var(--font-display)", letterSpacing: "0.02em" }}>
              {personaInfo.name} · Demo
            </div>
            <div style={{ fontSize: 11, color: "var(--text-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
              {personaInfo.role}
            </div>
          </div>
          <IconChevRight size={12} style={{ color: "var(--text-muted)" }} />
        </div>

        {/* Nav */}
        <nav style={{ flex: 1, padding: "16px 10px", display: "flex", flexDirection: "column", gap: 2, overflowY: "auto" }}>
          <div className="upper muted" style={{ padding: "8px 10px 4px", fontSize: 10 }}>Workspace</div>
          {items.map(it => {
            const Ic = it.icon;
            const active = page === it.id;
            return (
              <button key={it.id} onClick={() => onNav(it.id)}
                style={{
                  all: "unset",
                  display: "flex", alignItems: "center", gap: 11,
                  padding: "9px 12px",
                  borderRadius: "var(--r-sm)",
                  cursor: "pointer",
                  fontSize: 13, fontWeight: 500,
                  background: active ? "var(--bg-elevated)" : "transparent",
                  color: active ? "var(--text)" : "var(--text-secondary)",
                  borderLeft: active ? "2px solid var(--nasef-orange)" : "2px solid transparent",
                  paddingLeft: active ? 14 : 12,
                  transition: "all 0.1s",
                }}
                onMouseEnter={e => { if (!active) e.currentTarget.style.background = "var(--bg-raised)"; }}
                onMouseLeave={e => { if (!active) e.currentTarget.style.background = "transparent"; }}
              >
                <Ic size={15} />
                {it.label}
              </button>
            );
          })}
        </nav>

        {/* Live match dock */}
        {liveMatch && (
          <div style={{ padding: "12px 14px 16px", borderTop: "1px solid var(--border-soft)", boxSizing: "border-box", overflow: "hidden" }}>
            <div className="upper muted" style={{ fontSize: 10, marginBottom: 8, padding: "0 2px" }}>Now Playing</div>
            <button onClick={() => onOpenLobby(liveMatch.id)}
              style={{
                all: "unset", cursor: "pointer", display: "block",
                width: "100%", boxSizing: "border-box",
                padding: 11, borderRadius: "var(--r-md)",
                background: "linear-gradient(180deg, rgba(255,59,92,0.12) 0%, rgba(255,59,92,0.02) 100%)",
                border: "1px solid rgba(255,59,92,0.3)",
                transition: "all 0.12s",
              }}
              onMouseEnter={e => e.currentTarget.style.borderColor = "rgba(255,59,92,0.6)"}
              onMouseLeave={e => e.currentTarget.style.borderColor = "rgba(255,59,92,0.3)"}
            >
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                <span className="badge live"><span className="dot" />LIVE</span>
                <span className="upper muted" style={{ fontSize: 10 }}>BO5 · G4</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6, minWidth: 0 }}>
                <Crest school={D.schoolsById[liveMatch.home]} size="sm" />
                <span style={{ fontSize: 12, fontWeight: 600, flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{D.schoolsById[liveMatch.home].mascot}</span>
                <span className="mono" style={{ fontSize: 13, fontWeight: 700 }}>2</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                <Crest school={D.schoolsById[liveMatch.away]} size="sm" />
                <span style={{ fontSize: 12, fontWeight: 600, flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: "var(--text-secondary)" }}>{D.schoolsById[liveMatch.away].mascot}</span>
                <span className="mono" style={{ fontSize: 13, fontWeight: 700, color: "var(--text-muted)" }}>1</span>
              </div>
              <div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px solid rgba(255,59,92,0.15)", fontSize: 11, color: "var(--text-secondary)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span>Open lobby</span>
                <IconArrowR size={12} />
              </div>
            </button>
          </div>
        )}
      </aside>

      {/* Main column */}
      <div style={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
        {/* Topbar */}
        <header className="app-topbar" style={{
          height: 60,
          borderBottom: "1px solid var(--border-soft)",
          background: "var(--bg-base)",
          display: "flex", alignItems: "center",
          padding: "0 28px",
          gap: 16,
          position: "sticky", top: 0, zIndex: 10,
        }}>
          {/* Mobile menu toggle — only visible on small screens via CSS */}
          <button className="btn ghost icon mobile-nav-toggle" aria-label="Open menu"
            onClick={() => setMobileNavOpen(o => !o)}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <line x1="3" y1="6"  x2="21" y2="6" />
              <line x1="3" y1="12" x2="21" y2="12" />
              <line x1="3" y1="18" x2="21" y2="18" />
            </svg>
          </button>
          <div className="app-search" style={{ position: "relative", flex: 1, maxWidth: 380 }}>
            <IconSearch size={14} style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--text-muted)", pointerEvents: "none", zIndex: 2 }} />
            <input className="input search-input" placeholder="Search teams, schools, matches…"
              style={{ paddingLeft: 38, paddingRight: 14, fontSize: 13, height: 38, width: "100%" }} />
          </div>
          <div className="app-topbar-brand" aria-hidden="true"><NASEFMark /></div>
          <div className="spacer" />
          <div style={{ position: "relative" }}>
            <button className="btn ghost icon" title="Notifications" onClick={() => setBellOpen(o => !o)} style={{ position: "relative" }}>
              <IconBell size={16} />
              {announcements.length > 0 && (
                <span style={{
                  position: "absolute", top: 4, right: 4,
                  minWidth: 14, height: 14, padding: "0 4px",
                  borderRadius: 99, fontSize: 9, fontWeight: 700,
                  background: "var(--nasef-orange)", color: "#14060A",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  border: "2px solid var(--bg-base)",
                }}>{announcements.length}</span>
              )}
            </button>
            {bellOpen && (
              <>
                <div onClick={() => setBellOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 90 }} />
                <div style={{
                  position: "absolute", right: 0, top: "calc(100% + 8px)",
                  background: "var(--bg-raised)", border: "1px solid var(--border)",
                  borderRadius: "var(--r-md)", width: 360,
                  boxShadow: "0 16px 40px -8px rgba(0,0,0,0.6)",
                  zIndex: 100, overflow: "hidden",
                }}>
                  <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--border-soft)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>Announcements</div>
                    <span className="badge orange" style={{ fontSize: 10 }}>{announcements.length} new</span>
                  </div>
                  <div style={{ maxHeight: 420, overflowY: "auto" }}>
                    {announcements.map(a => (
                      <div key={a.id} style={{ display: "flex", gap: 12, padding: "12px 14px", borderBottom: "1px solid var(--border-soft)" }}>
                        <div style={{
                          width: 28, height: 28, borderRadius: 8, flexShrink: 0,
                          background: a.priority === "warning" ? "rgba(247,185,40,0.12)" : "var(--bg-elevated)",
                          color: a.priority === "warning" ? "var(--warning)" : "var(--text-secondary)",
                          display: "flex", alignItems: "center", justifyContent: "center",
                        }}>
                          {a.priority === "warning" ? <IconWarn size={14} /> : <IconInfo size={14} />}
                        </div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 2 }}>{a.title}</div>
                          <div style={{ fontSize: 12, color: "var(--text-secondary)", lineHeight: 1.5 }}>{a.body}</div>
                          <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>{new Date(a.date).toLocaleDateString("en-US", { month: "short", day: "numeric" })}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </>
            )}
          </div>
          <div style={{ width: 1, height: 22, background: "var(--border)" }} />
          <div style={{ position: "relative" }}>
            <button className="btn ghost" onClick={() => setUserMenuOpen(o => !o)}
              style={{ padding: "4px 10px 4px 4px", display: "flex", alignItems: "center", gap: 8 }}>
              <PersonaAvatar p={personaInfo} size={28} />
              <div style={{ textAlign: "left", lineHeight: 1.1 }}>
                <div style={{ fontSize: 12, fontWeight: 600 }}>{personaInfo.role}</div>
                <div style={{ fontSize: 10, color: "var(--text-muted)" }}>{personaInfo.school}</div>
              </div>
              <IconChevDown size={12} />
            </button>
            {userMenuOpen && (
              <div style={{
                position: "absolute", right: 0, top: "calc(100% + 6px)",
                background: "var(--bg-raised)",
                border: "1px solid var(--border)",
                borderRadius: "var(--r-md)",
                padding: 6,
                minWidth: 220,
                boxShadow: "0 16px 40px -8px rgba(0,0,0,0.6)",
                zIndex: 100,
              }}>
                <div className="upper muted" style={{ padding: "8px 10px 4px", fontSize: 10 }}>Switch persona</div>
                {window.PERSONAS.map(p => (
                  <button key={p.id} onClick={() => { setUserMenuOpen(false); onSwitchPersona(); }}
                    style={{
                      all: "unset", cursor: "pointer", display: "flex", alignItems: "center", gap: 10,
                      padding: "8px 10px", borderRadius: "var(--r-sm)", width: "100%", boxSizing: "border-box",
                      background: persona === p.id ? "var(--bg-elevated)" : "transparent",
                    }}
                    onMouseEnter={e => { if (persona !== p.id) e.currentTarget.style.background = "var(--bg-elevated)"; }}
                    onMouseLeave={e => { if (persona !== p.id) e.currentTarget.style.background = "transparent"; }}
                  >
                    <PersonaAvatar p={p} size={28} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 600 }}>{p.name}</div>
                      <div style={{ fontSize: 10, color: "var(--text-muted)" }}>{p.role}</div>
                    </div>
                    {persona === p.id && <IconCheck size={12} style={{ color: p.color }} />}
                  </button>
                ))}
                <div style={{ height: 1, background: "var(--border-soft)", margin: "6px 4px" }} />
                <button className="btn ghost" onClick={() => location.hash = "#/landing"}
                  style={{ width: "100%", justifyContent: "flex-start", border: "none" }}>
                  <IconLogout size={13} /> Back to landing
                </button>
              </div>
            )}
          </div>
        </header>

        {/* Page content */}
        <main className="app-main fade-in" style={{ padding: "32px 40px 80px", maxWidth: 1400, width: "100%", margin: "0 auto", flex: 1, minWidth: 0 }} key={page}>
          {children}
        </main>
      </div>
    </div>
  );
};

window.Shell = Shell;
window.NAV_ITEMS = NAV_ITEMS;
