// ============================================
// App shell — top bar, sidebar (desktop), bottom tabs (mobile), notifications
// ============================================
const { useState: _useState, useEffect: _useEffect, useRef: _useRef, createContext, useContext } = React;

const AppContext = createContext({});
window.useApp = () => useContext(AppContext);

// Role definitions
const ROLES = {
  admin:        { label: "Swim School Admin", short: "Admin",       accent: "var(--c-admin)",       icon: "shield" },
  club:         { label: "Club Administrator", short: "Club",       accent: "var(--c-club)",        icon: "users" },
  coach:        { label: "Coach / Instructor", short: "Coach",      accent: "var(--teal)",          icon: "swimmer" },
  competitive:  { label: "Competitive Swimmer", short: "Competitive", accent: "var(--c-competitive)", icon: "trophy" },
  openwater:    { label: "Open Water / Triathlete", short: "Triathlete", accent: "var(--c-openwater)", icon: "wave" },
  recreation:   { label: "Recreational Swimmer", short: "Fitness",   accent: "var(--c-recreation)",  icon: "flame" },
  student:      { label: "Student", short: "Student",                accent: "var(--aqua)",          icon: "star" },
  parent:       { label: "Parent", short: "Parent",                  accent: "var(--c-parent)",      icon: "users" },
  developer:    { label: "API Developer", short: "Developer",        accent: "var(--c-api)",         icon: "code" },
};

// Nav definitions per role
const NAVS = {
  admin: [
    { id: "home", label: "Dashboard", icon: "home" },
    { id: "schedule", label: "Schedule", icon: "calendar" },
    { id: "people", label: "People", icon: "users" },
    { id: "classes", label: "Classes", icon: "ladder" },
    { id: "reports", label: "Reports", icon: "chart" },
    { id: "settings", label: "Settings", icon: "settings" },
  ],
  club: [
    { id: "home", label: "Dashboard", icon: "home" },
    { id: "roster", label: "Roster", icon: "users" },
    { id: "teams", label: "Teams", icon: "shield" },
    { id: "meets", label: "Meets", icon: "trophy" },
    { id: "billing", label: "Billing", icon: "credit-card" },
    { id: "analytics", label: "Analytics", icon: "chart" },
  ],
  coach: [
    { id: "home", label: "Today", icon: "home" },
    { id: "classes", label: "My Classes", icon: "calendar" },
    { id: "roster", label: "Students", icon: "users" },
    { id: "workouts", label: "Workouts", icon: "ladder" },
    { id: "messages", label: "Messages", icon: "msg" },
  ],
  competitive: [
    { id: "home", label: "Home", icon: "home" },
    { id: "train", label: "Train", icon: "stopwatch" },
    { id: "history", label: "History", icon: "calendar" },
    { id: "records", label: "Records", icon: "trophy" },
    { id: "profile", label: "Profile", icon: "settings" },
  ],
  openwater: [
    { id: "home", label: "Home", icon: "home" },
    { id: "session", label: "Session", icon: "wave" },
    { id: "races", label: "Races", icon: "pin" },
    { id: "plan", label: "Plan", icon: "calendar" },
    { id: "devices", label: "Devices", icon: "heart" },
  ],
  recreation: [
    { id: "home", label: "Home", icon: "home" },
    { id: "workouts", label: "Workouts", icon: "play" },
    { id: "history", label: "History", icon: "calendar" },
    { id: "achievements", label: "Badges", icon: "medal" },
    { id: "profile", label: "Profile", icon: "settings" },
  ],
  student: [
    { id: "home", label: "Home", icon: "home" },
    { id: "classes", label: "Classes", icon: "calendar" },
    { id: "progress", label: "Progress", icon: "ladder" },
    { id: "workouts", label: "Workouts", icon: "play" },
    { id: "achievements", label: "Badges", icon: "medal" },
  ],
  parent: [
    { id: "home", label: "Home", icon: "home" },
    { id: "schedule", label: "Schedule", icon: "calendar" },
    { id: "progress", label: "Progress", icon: "chart" },
    { id: "billing", label: "Billing", icon: "credit-card" },
    { id: "messages", label: "Messages", icon: "msg" },
  ],
  developer: [
    { id: "home", label: "Dashboard", icon: "home" },
    { id: "keys", label: "API Keys", icon: "key" },
    { id: "docs", label: "Docs", icon: "book" },
    { id: "webhooks", label: "Webhooks", icon: "webhook" },
    { id: "logs", label: "Logs", icon: "code" },
    { id: "analytics", label: "Analytics", icon: "chart" },
  ],
};

window.ROLES = ROLES;
window.NAVS = NAVS;

// ====== Sidebar (desktop) ======
function Sidebar({ role, current, onNav, onSwitchRole, onLogout, onOpenNotifs }) {
  const r = ROLES[role];
  const nav = NAVS[role];
  return (
    <aside style={{
      width: 240, background: "white", borderRight: "1px solid var(--gray-200)",
      display: "flex", flexDirection: "column", flexShrink: 0, height: "100vh", position: "sticky", top: 0,
    }}>
      <div className="row" style={{ padding: "20px 18px 16px", gap: 10 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: "var(--navy)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="logo" size={22} color="white"/>
        </div>
        <div>
          <div style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 18, letterSpacing: -0.3 }}>AquaFlow</div>
          <div style={{ fontSize: 10, color: "var(--gray-500)", letterSpacing: 1, textTransform: "uppercase" }}>{r.short}</div>
        </div>
      </div>

      <div style={{ padding: "0 12px", flex: 1, overflowY: "auto" }}>
        <div className="t-label" style={{ color: "var(--gray-500)", padding: "12px 8px 6px" }}>Navigate</div>
        {nav.map(n => {
          const active = current === n.id;
          return (
            <button key={n.id} onClick={() => onNav(n.id)}
              style={{
                width: "100%", display: "flex", alignItems: "center", gap: 10,
                padding: "10px 12px", marginBottom: 2, borderRadius: 10, textAlign: "left",
                background: active ? "var(--sky)" : "transparent",
                color: active ? "var(--navy)" : "var(--gray-700)",
                fontWeight: active ? 600 : 500, fontSize: 14,
                borderLeft: `3px solid ${active ? r.accent : "transparent"}`,
                transition: "all 140ms",
              }}>
              <Icon name={n.icon} size={18} color={active ? r.accent : "currentColor"}/>
              <span>{n.label}</span>
            </button>
          );
        })}

        <div className="t-label" style={{ color: "var(--gray-500)", padding: "20px 8px 6px" }}>Switch Role</div>
        <button onClick={onSwitchRole} style={{ width: "100%", textAlign: "left", padding: "10px 12px", borderRadius: 10, background: "var(--gray-100)", display: "flex", alignItems: "center", gap: 10, fontSize: 13, color: "var(--gray-700)" }}>
          <Icon name={r.icon} size={16} color={r.accent}/>
          <span style={{ flex: 1 }}>{r.label}</span>
          <Icon name="chev-right" size={14}/>
        </button>
      </div>

      <div style={{ borderTop: "1px solid var(--gray-200)", padding: 12 }}>
        <div className="row" style={{ padding: "6px 6px" }}>
          <Avatar name="Alex Rivera"/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>Alex Rivera</div>
            <div style={{ fontSize: 11, color: "var(--gray-500)" }}>alex@aquaflow.app</div>
          </div>
          <button className="btn-icon" onClick={onLogout} title="Log out"><Icon name="logout" size={16}/></button>
        </div>
      </div>
    </aside>
  );
}

// ====== Top bar ======
function TopBar({ role, onOpenNotifs, notifCount, onSwitchRole, onSearchToggle, mobileMenuOpen, onMobileMenu, title }) {
  const r = ROLES[role];
  return (
    <div style={{
      height: 64, background: "white", borderBottom: "1px solid var(--gray-200)",
      padding: "0 20px", display: "flex", alignItems: "center", gap: 12, position: "sticky", top: 0, zIndex: 50,
    }}>
      <button className="btn-icon mobile-only" onClick={onMobileMenu}><Icon name="menu" size={20}/></button>
      <div className="mobile-only" style={{ flex: 1, fontWeight: 600, fontFamily: "var(--f-display)", fontSize: 16 }}>{title || ROLES[role].label}</div>

      <div className="desktop-only" style={{ flex: 1, maxWidth: 420 }}>
        <div style={{ position: "relative" }}>
          <Icon name="search" size={16} color="var(--gray-500)" style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)" }}/>
          <input className="input" placeholder="Search students, classes, sessions…" style={{ paddingLeft: 36, width: "100%", background: "var(--gray-100)", border: "none" }}/>
        </div>
      </div>

      <div className="row" style={{ gap: 8 }}>
        <button className="btn-icon" onClick={onOpenNotifs} style={{ position: "relative" }}>
          <Icon name="bell" size={18}/>
          {notifCount > 0 && <span style={{ position: "absolute", top: 6, right: 6, width: 8, height: 8, background: "var(--red)", borderRadius: "50%", border: "2px solid white" }}/>}
        </button>
        <div className="desktop-only">
          <button onClick={onSwitchRole} className="row" style={{ background: "var(--gray-100)", padding: "6px 10px 6px 6px", borderRadius: 999, gap: 8 }}>
            <Avatar name="Alex Rivera" size="sm"/>
            <span style={{ fontSize: 13, fontWeight: 600 }}>{r.short}</span>
            <Icon name="chev-down" size={14}/>
          </button>
        </div>
      </div>
    </div>
  );
}

// ====== Bottom tabs (mobile) ======
function BottomTabs({ role, current, onNav }) {
  const r = ROLES[role];
  const nav = NAVS[role].slice(0, 5);
  return (
    <nav style={{
      position: "sticky", bottom: 0, background: "white", borderTop: "1px solid var(--gray-200)",
      display: "flex", padding: "8px 0 12px", paddingBottom: "max(12px, env(safe-area-inset-bottom))",
      zIndex: 50,
    }}>
      {nav.map(n => {
        const active = current === n.id;
        return (
          <button key={n.id} onClick={() => onNav(n.id)}
            style={{
              flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4,
              color: active ? r.accent : "var(--gray-500)",
              fontSize: 10, fontWeight: 600,
              padding: "6px 4px",
            }}>
            <Icon name={n.icon} size={22} color={active ? r.accent : "var(--gray-500)"}/>
            <span>{n.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// ====== Notifications panel ======
const SAMPLE_NOTIFS = [
  { id: 1, type: "achievement", icon: "trophy", title: "PB set: 100m Freestyle", body: "Your new personal best is 1:07.42", time: "2m", tone: "mint" },
  { id: 2, type: "class", icon: "calendar", title: "Class reminder", body: "Stingrays Level 3 starts in 1 hour", time: "12m", tone: "aqua" },
  { id: 3, type: "billing", icon: "credit-card", title: "Invoice due", body: "April dues $185 due in 3 days", time: "1h", tone: "amber" },
  { id: 4, type: "msg", icon: "msg", title: "Coach Maria", body: "Great work this morning — let's chat about meet prep.", time: "3h", tone: "default" },
];

function NotificationsPanel({ open, onClose }) {
  if (!open) return null;
  const [tab, setTab] = useState("all");
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(10,15,30,0.4)", zIndex: 800, display: "flex", justifyContent: "flex-end" }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 380, maxWidth: "92vw", background: "white", height: "100%", overflow: "auto", animation: "fade-up 220ms ease-out", boxShadow: "var(--sh-16)" }}>
        <div className="between" style={{ padding: 16, borderBottom: "1px solid var(--gray-200)" }}>
          <div className="t-h2">Notifications</div>
          <button className="btn-icon" onClick={onClose}><Icon name="x" size={18}/></button>
        </div>
        <div style={{ padding: "12px 16px" }}>
          <Tabs tabs={[{ id: "all", label: "All" }, { id: "activity", label: "Activity" }, { id: "billing", label: "Billing" }, { id: "system", label: "System" }]} value={tab} onChange={setTab}/>
        </div>
        <div style={{ padding: "0 16px 16px", display: "flex", flexDirection: "column", gap: 8 }}>
          {SAMPLE_NOTIFS.map(n => (
            <div key={n.id} className="row" style={{ padding: 12, borderRadius: 12, background: "var(--gray-50)", alignItems: "flex-start", gap: 12 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: `var(--${n.tone === "mint" ? "mint-50" : n.tone === "aqua" ? "aqua-50" : n.tone === "amber" ? "amber-50" : "gray-100"})`, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <Icon name={n.icon} size={18} color={n.tone === "mint" ? "var(--mint)" : n.tone === "aqua" ? "var(--aqua)" : n.tone === "amber" ? "var(--amber)" : "var(--gray-700)"}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="between">
                  <div style={{ fontWeight: 600, fontSize: 13 }}>{n.title}</div>
                  <div style={{ fontSize: 11, color: "var(--gray-500)" }}>{n.time}</div>
                </div>
                <div style={{ fontSize: 12, color: "var(--gray-600)", marginTop: 2 }}>{n.body}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ====== Role switcher modal ======
function RoleSwitcher({ open, onClose, onPick, current }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(10,15,30,0.6)", zIndex: 800, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: "white", borderRadius: 20, padding: 24, maxWidth: 720, width: "100%", maxHeight: "85vh", overflow: "auto", animation: "fade-up 220ms" }}>
        <div className="between" style={{ marginBottom: 20 }}>
          <div>
            <div className="t-h1">Switch portal</div>
            <div className="muted">AquaFlow is one app, every swim role. Pick a context to explore.</div>
          </div>
          <button className="btn-icon" onClick={onClose}><Icon name="x" size={18}/></button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))", gap: 12 }}>
          {Object.entries(ROLES).map(([id, r]) => {
            const active = current === id;
            return (
              <button key={id} onClick={() => onPick(id)} style={{
                textAlign: "left", padding: 16, borderRadius: 14,
                background: active ? "var(--sky)" : "var(--gray-50)",
                border: `1.5px solid ${active ? r.accent : "transparent"}`,
                display: "flex", flexDirection: "column", gap: 10,
                transition: "all 160ms",
              }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: `${r.accent}22`, display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name={r.icon} size={20} color={r.accent}/>
                </div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{r.label}</div>
                  <div style={{ fontSize: 12, color: "var(--gray-600)", marginTop: 2 }}>{ROLE_DESCRIPTIONS[id]}</div>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

const ROLE_DESCRIPTIONS = {
  admin: "Manage classes, instructors & billing",
  club: "Roster, meets & analytics",
  coach: "Track attendance, assess swimmers",
  competitive: "Lap timer, splits & PB tracking",
  openwater: "GPS routes & triathlon training",
  recreation: "Guided workouts & streaks",
  student: "Class schedule & level progress",
  parent: "Monitor children, pay bills",
  developer: "API keys, webhooks & docs",
};

Object.assign(window, { Sidebar, TopBar, BottomTabs, NotificationsPanel, RoleSwitcher });
