// DiveDex — App root with screen routing + XP toast

function App({ initialScreen = 'welcome', initialId }) {
  const { state } = useDiveDex();
  // Auth gate: if no user is selected, or the app is explicitly locked,
  // render the LockScreen instead of the routed screens. All hooks below
  // still run unconditionally, so this early-return is safe.
  const showLock = state.locked || !state.activeUserId;
  const expedition = state.expeditions.find(e => e.id === state.activeExpeditionId) || state.expeditions[0];
  const expRegion = expedition ? expedition.region : null;

  // Background expedition music — controlled here at the App root so it
  // survives screen navigation (the audio engine de-dupes same-music calls,
  // so re-firing this effect is a no-op while the same track is playing).
  // Stops cleanly when the user locks the app or switches off Japan.
  React.useEffect(() => {
    if (!window.DiveDexAudio) return;
    if (!showLock && expRegion === 'japan') {
      window.DiveDexAudio.playMusic('music.japanExpedition');
    } else {
      window.DiveDexAudio.stopMusic();
    }
  }, [showLock, expRegion]);
  // Returning user: if they've logged dives already, skip the Welcome intro
  // and land on the Dashboard. Computed at mount time so there's no flash.
  const computedInitial = (initialScreen === 'welcome' && state.dives.length > 0)
    ? 'dashboard'
    : initialScreen;
  const [stack, setStack] = React.useState([{ s: computedInitial, id: initialId }]);
  const cur = stack[stack.length - 1];
  const [toast, setToast] = React.useState(null);

  const nav = (s, id) => {
    if (s === 'back') return setStack(stack.length > 1 ? stack.slice(0, -1) : stack);
    setStack([...stack, { s, id }]);
  };
  const setTab = (s) => setStack([{ s }]);

  // Clear any in-flight toast on screen change so a stale message can't bleed
  // into another surface. (Toasts are reserved for real, state-driven events;
  // there's no longer a fake demo toast on Dashboard mount.)
  React.useEffect(() => { setToast(null); }, [cur.s]);

  const tabFor = (s) => ({
    welcome: 'levels', levels: 'levels', dashboard: 'levels',
    log: 'log', sightings: 'log', 'edit-dive': 'log', 'log-similar': 'log',
    dex: 'dex', creature: 'dex',
    team: 'team', achievements: 'team', sidequests: 'team',
    memories: 'memories', story: 'memories',
    recap: 'levels', settings: 'levels', trends: 'levels',
    boutique: 'gear', item: 'gear', locker: 'gear', prestige: 'gear',
  }[s] || 'levels');

  const tab = tabFor(cur.s);
  const onTab = (id) => {
    if (id === 'levels') setTab('dashboard');
    else if (id === 'log') setTab('log');
    else if (id === 'dex') setTab('dex');
    else if (id === 'team') setTab('team');
    else if (id === 'memories') setTab('memories');
    else if (id === 'gear') setTab('boutique');
  };

  const hideNav = cur.s === 'welcome';

  let screen = null;
  switch (cur.s) {
    case 'welcome':    screen = <WelcomeScreen nav={nav}/>; break;
    case 'levels':     screen = <LevelsScreen nav={nav}/>; break;
    case 'dashboard':  screen = <DashboardScreen nav={nav}/>; break;
    case 'log':        screen = <LogDiveScreen nav={nav}/>; break;
    case 'edit-dive':  screen = <LogDiveScreen nav={nav} editDiveId={cur.id}/>; break;
    case 'log-similar': screen = <LogDiveScreen nav={nav} templateDiveId={cur.id}/>; break;
    case 'recap':      screen = <RecapScreen nav={nav} id={cur.id}/>; break;
    case 'dex':        screen = <DexScreen nav={nav}/>; break;
    case 'creature':   screen = <CreatureDetailScreen nav={nav} id={cur.id}/>; break;
    case 'team':       screen = <TeamScreen nav={nav}/>; break;
    case 'achievements': screen = <AchievementsScreen nav={nav}/>; break;
    case 'sidequests': screen = <SideQuestsScreen nav={nav}/>; break;
    case 'memories':   screen = <MemoriesScreen nav={nav}/>; break;
    case 'story':      screen = <StoryCardScreen nav={nav} id={cur.id}/>; break;
    case 'settings':   screen = <SettingsScreen nav={nav}/>; break;
    case 'trends':     screen = <TrendsScreen nav={nav}/>; break;
    case 'boutique':   screen = <BoutiqueScreen nav={nav}/>; break;
    case 'item':       screen = <BoutiqueItemScreen nav={nav} id={cur.id}/>; break;
    case 'locker':     screen = <LockerScreen nav={nav}/>; break;
    case 'prestige':   screen = <PrestigeScreen nav={nav}/>; break;
    default:           screen = <WelcomeScreen nav={nav}/>;
  }

  if (showLock) {
    return <div className="dd-app"><LockScreen/></div>;
  }

  return (
    <div className="dd-app">
      {screen}
      {!hideNav && <BottomNav tab={tab} onTab={onTab}/>}
      {toast && <XpToast {...toast}/>}
    </div>
  );
}

function XpToast({ xp, msg, kind = 'aqua' }) {
  const c = kind === 'gold' ? '#D7B46A' : '#82ECFF';
  return (
    <div className="dd-toast" style={{
      position: 'absolute', left: '50%', bottom: 96, transform: 'translateX(-50%)',
      padding: '8px 14px 8px 12px', borderRadius: 999,
      background: 'linear-gradient(180deg, rgba(12,28,46,0.95), rgba(5,11,20,0.95))',
      border: `1px solid ${c}55`,
      boxShadow: `0 0 22px ${c}55, 0 6px 22px rgba(0,0,0,0.5)`,
      display: 'flex', alignItems: 'center', gap: 8, zIndex: 7,
    }}>
      <div style={{ width: 22, height: 22, borderRadius: 8, background: `${c}22`, color: c, fontSize: 13, fontWeight: 800, display: 'grid', placeItems: 'center', border: `1px solid ${c}66` }}>✦</div>
      <span style={{ fontSize: 12.5, fontWeight: 600, color: '#fff' }}>{msg}</span>
      <span className="dd-num" style={{ fontSize: 13, fontWeight: 700, color: c }}>+{xp}</span>
    </div>
  );
}

Object.assign(window, { App, XpToast });
