// App.jsx — Main app shell with friend bar + tab navigation (updated with 7 new features)
const { useState, useRef, useEffect } = React;
const { useApp } = window;

const DASHBOARD_TABS = [
  { id: 'home', label: 'Home',    icon: 'home' },
  { id: 'pool', label: 'My Pool', icon: 'pool' },
];

const TEAM_TABS = [
  { id: 'home',  label: 'Home',     icon: 'home' },
  { id: 'pool',  label: 'My Pool',  icon: 'pool' },
  { id: 'comp',  label: 'Comp',     icon: 'comp' },
  { id: 'draft', label: 'Draft',    icon: 'draft' },
  { id: 'scout', label: 'Scout',    icon: 'scout' },
  { id: 'learn', label: 'Learning', icon: 'learn' },
  { id: 'vod',   label: 'VOD',      icon: 'vod' },
];

// Removed legacy FriendBar — window.FriendBarV2 (in FriendBarV2.jsx) is used.

// Removed Tab groups — single bar with 7 tabs

function TabBar() {
  const { currentTab, setTab, lobbyCode } = useApp();
  const tabs = lobbyCode ? TEAM_TABS : DASHBOARD_TABS;

  return (
    <div style={{
      position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 200,
      background: 'var(--surface-card)', borderTop: '2.5px solid var(--border-emphasis)',
    }}>
      {/* Tab buttons */}
      <div style={{
        display: 'flex', padding: '6px 12px 8px 12px', gap: lobbyCode ? 2 : 16,
        justifyContent: lobbyCode ? 'stretch' : 'center',
        maxWidth: lobbyCode ? '100%' : 360, margin: '0 auto',
        overflowX: 'hidden',
      }}>
        {tabs.map(tab => {
          const active = currentTab === tab.id;
          return (
            <button
              key={tab.id}
              onClick={() => setTab(tab.id)}
              className="cozy-btn"
              style={{
                flex: lobbyCode ? '1 1 0' : '0 1 120px', minWidth: 40, display: 'flex', flexDirection: 'column',
                alignItems: 'center', gap: 2, padding: '4px 2px 6px 2px',
                background: active ? 'var(--surface-nested)' : 'transparent',
                border: 'none',
                borderTop: `3px solid ${active ? 'var(--accent-orange)' : 'transparent'}`,
                borderRadius: '6px 6px 10px 10px', cursor: 'pointer',
                transition: 'all 0.2s cubic-bezier(0.34, 1.56, 0.64, 1)',
                transform: active ? 'scale(1.04)' : 'scale(1)',
              }}
            >
              <window.LolIcon name={tab.icon} size={20} color={active ? 'var(--accent-orange)' : '#C8AA6E'} />
              <span style={{
                fontSize: 10, fontFamily: 'Nunito', fontWeight: active ? 900 : 700,
                color: active ? 'var(--accent-orange)' : 'var(--text-muted)',
                whiteSpace: 'nowrap',
              }}>
                {tab.label}
              </span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function CompScreen() {
  const [subTab, setSubTab] = React.useState('build');
  const TeamComp = window.TeamComp;
  const Synergy = window.Synergy;
  const SavedDrafts = window.SavedDrafts;
  const subs = [
    { id: 'build',   label: '🍲 Build' },
    { id: 'synergy', label: '🤝 Synergy' },
    { id: 'saved',   label: '📦 Saved' },
  ];
  return (
    <div>
      <div style={{ padding: '12px 20px 0', display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {subs.map(s => (
          <button key={s.id} onClick={() => setSubTab(s.id)} className="cozy-btn" style={{
            padding: '6px 14px', border: `2px solid ${subTab === s.id ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
            borderRadius: 18, fontFamily: 'Nunito', fontSize: 13, fontWeight: 800,
            background: subTab === s.id ? 'var(--accent-orange)' : 'var(--surface-nested)',
            color: subTab === s.id ? 'white' : 'var(--text-primary)', cursor: 'pointer',
          }}>{s.label}</button>
        ))}
      </div>
      {subTab === 'build' && TeamComp && <TeamComp />}
      {subTab === 'synergy' && Synergy && <Synergy />}
      {subTab === 'saved' && SavedDrafts && <SavedDrafts />}
    </div>
  );
}

function DraftScreen() {
  const isDraftActive = window.isLiveDraftInProgress ? window.isLiveDraftInProgress() : false;
  const [subTab, setSubTab] = React.useState(() => (isDraftActive ? 'sim' : 'lab'));
  const DraftSimulator = window.DraftSimulator;
  const DraftLab = window.DraftLab;
  const subs = [
    { id: 'sim', label: '🎲 Draft Simulator' },
    { id: 'lab', label: '🧪 Draft Lab (beta)' },
  ];
  return (
    <div>
      <div style={{ padding: '12px 20px 0', display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {subs.map(s => (
          <button key={s.id} onClick={() => setSubTab(s.id)} className="cozy-btn" style={{
            padding: '6px 14px', border: `2px solid ${subTab === s.id ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
            borderRadius: 18, fontFamily: 'Nunito', fontSize: 13, fontWeight: 800,
            background: subTab === s.id ? 'var(--accent-orange)' : 'var(--surface-nested)',
            color: subTab === s.id ? 'white' : 'var(--text-primary)', cursor: 'pointer',
          }}>{s.label}</button>
        ))}
      </div>
      {subTab === 'sim' && DraftSimulator && <DraftSimulator />}
      {subTab === 'lab' && DraftLab       && <DraftLab />}
    </div>
  );
}

function ScoutScreen() {
  const [subTab, setSubTab] = React.useState('report');
  const SummonerLookup = window.SummonerLookup;
  const EnemyScouter = window.EnemyScouter;
  const ScoutingReport = window.ScoutingReport;
  const subs = [
    { id: 'report',   label: '👁️ Scouting Report' },
    { id: 'summoner', label: '🔎 Summoner Lookup' },
    { id: 'enemy',    label: '🕵️ Enemies' },
  ];
  return (
    <div>
      <div style={{ padding: '12px 20px 0', display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {subs.map(s => (
          <button key={s.id} onClick={() => setSubTab(s.id)} className="cozy-btn" style={{
            padding: '6px 14px', border: `2px solid ${subTab === s.id ? 'var(--border-emphasis)' : 'var(--border-default)'}`,
            borderRadius: 18, fontFamily: 'Nunito', fontSize: 13, fontWeight: 800,
            background: subTab === s.id ? 'var(--accent-orange)' : 'var(--surface-nested)',
            color: subTab === s.id ? 'white' : 'var(--text-primary)', cursor: 'pointer',
          }}>{s.label}</button>
        ))}
      </div>
      {subTab === 'report' && ScoutingReport && <ScoutingReport />}
      {subTab === 'summoner' && SummonerLookup && <SummonerLookup />}
      {subTab === 'enemy' && EnemyScouter && <EnemyScouter />}
    </div>
  );
}

function AppContent() {
  const { currentTab, toast, onboarded, setOnboarded, players, myUserId, sessionUserId, isSynced, setLobbyCode, lobbyCode } = useApp();
  const [showOnboarding, setShowOnboarding] = useState(false);
  const [authUser, setAuthUser] = useState(() => (window.firebase && window.firebase.auth ? window.firebase.auth().currentUser : null));

  useEffect(() => {
    if (window.firebase && window.firebase.auth) {
      const unsubscribe = window.firebase.auth().onAuthStateChanged((user) => {
        if (user) {
          user.reload().then(() => {
            setAuthUser(user);
          }).catch((err) => {
            console.warn("Auth user invalid or deleted server-side:", err);
            try {
              window.firebase.auth().signOut().then(() => {
                setAuthUser(null);
                setOnboarded(false);
                setLobbyCode(null);
              });
            } catch (e) {
              setAuthUser(null);
              setOnboarded(false);
              setLobbyCode(null);
            }
          });
        } else {
          setAuthUser(null);
          setOnboarded(false);
        }
      });
      return () => unsubscribe();
    }
  }, [setOnboarded, setLobbyCode]);

  const screens = {
    home:    window.HomeScreen,
    pool:    window.MyPool,
    comp:    CompScreen,
    draft:   DraftScreen,
    scout:   ScoutScreen,
    meta:    window.MetaAlerts,
    vod:     window.PostGameNotes,
    learn:   window.ChampsToLearn,
  };

  const Screen = screens[currentTab] || window.HomeScreen;

  const isAuth = !!(authUser || (window.firebase && window.firebase.auth && window.firebase.auth().currentUser));

  // Show onboarding when user hasn't onboarded/completed profile setup, or explicitly asked to revisit it.
  if (!onboarded || showOnboarding) {
    return (
      <window.OnboardingFlow
        onComplete={() => {
          window.profileSetupPending = false;
          setLobbyCode(null);
          setOnboarded(true);
          setShowOnboarding(false);
        }}
      />
    );
  }

  const HeaderComponent = window.FriendBarV2;

  return (
    <div style={{ minHeight: '100vh', background: 'var(--surface-page)' }}>
      {HeaderComponent && <HeaderComponent onOpenOnboarding={() => setShowOnboarding(true)} />}
      <div style={{ paddingTop: 56, paddingBottom: 88 }}>
        <Screen />
      </div>
      <TabBar />
      <window.Toast message={toast} />
    </div>
  );
}

function App() {
  return (
    <window.AppProvider>
      <AppContent />
    </window.AppProvider>
  );
}

Object.assign(window, { App });
