// app.jsx — orchestrator. Routes between screens, persists progress & settings.

const DEFAULT_SETTINGS = {
  mascot: true,
  sound: true,
  haptics: true,
  speed: 'NORMAL',
  themeKey: 'risoLight',
};

function App() {
  // Settings (with theme).
  const [settings, setSettingsState] = React.useState(() => ({
    ...DEFAULT_SETTINGS, ...(loadSettings() || {}),
  }));
  const setSettings = React.useCallback((s) => {
    setSettingsState(s); saveSettings(s);
  }, []);
  const setThemeKey = (key) => setSettings({ ...settings, themeKey: key });

  const theme = THEMES[settings.themeKey] || THEMES.risoLight;

  // Progress. Real values from day 1 — no more SEEDED demo data.
  const [progress, setProgressState] = React.useState(() => {
    const loaded = loadProgress();
    if (loaded) return loaded;
    return { ...DEFAULT_PROGRESS };
  });
  const setProgress = (updater) => {
    setProgressState((prev) => {
      const next = typeof updater === 'function' ? updater(prev) : updater;
      saveProgress(next);
      return next;
    });
  };

  // Routing.
  const [screen, setScreen] = React.useState(() => progress.onboarded ? 'home' : 'onboarding');
  const [params, setParams] = React.useState({});

  const nav = (s, p = {}) => {
    if (p.onboarded) setProgress((pr) => ({ ...pr, onboarded: true }));
    setScreen(s);
    setParams(p);
    window.scrollTo?.(0, 0);
  };
  const onTab = (t) => { setScreen(t); setParams({}); };
  const onReset = () => {
    const ok = window.confirm('Reset all progress?\n\nThis wipes your XP, coins, streak, completed lessons, and stars. The OpenRouter key in Settings stays.');
    if (!ok) return;
    setProgress({ ...DEFAULT_PROGRESS, onboarded: true });
    // Clear any cached scroll positions so the user lands at top of Home.
    if (window._chopstickScroll) window._chopstickScroll = {};
  };

  // Award XP / coins / streak on lesson complete.
  // Streak is day-based: same day = no change, +1 next day, reset if gap > 1.
  // First time completing a lesson awards full XP+coins; replays award half.
  const onLessonComplete = ({ lesson, score, hearts }) => {
    const stars = score >= Math.max(700, lesson.exercises.length * 80) ? 3 : score >= 400 ? 2 : 1;
    setProgress((pr) => {
      const wasCompleted = pr.completedLessons.includes(lesson.id);
      const completed = wasCompleted ? pr.completedLessons : [...pr.completedLessons, lesson.id];
      const prevStars = pr.lessonStars[lesson.id] || 0;
      const xpGain = wasCompleted ? Math.round(lesson.xp / 2) : lesson.xp;
      const coinGain = wasCompleted ? Math.round(lesson.coins / 2) : lesson.coins;
      const streakUpdate = bumpStreak(pr);
      return {
        ...pr,
        xp: pr.xp + xpGain,
        coins: pr.coins + coinGain,
        streak: streakUpdate.streak,
        lastActiveDate: streakUpdate.lastActiveDate,
        highScore: Math.max(pr.highScore, score),
        completedLessons: completed,
        lessonStars: { ...pr.lessonStars, [lesson.id]: Math.max(prevStars, stars) },
        lastPlayed: lesson.id,
      };
    });
  };

  // Hide splash on first render.
  React.useEffect(() => {
    const sp = document.getElementById('splash');
    if (sp) { sp.classList.add('hide'); setTimeout(() => sp.remove(), 300); }
  }, []);

  // Update theme-color meta to match active theme.
  React.useEffect(() => {
    const meta = document.querySelector('meta[name="theme-color"]:not([media])') ||
                 document.querySelectorAll('meta[name="theme-color"]')[0];
    if (meta) meta.setAttribute('content', theme.bg);
  }, [theme]);

  const common = {
    theme,
    mascotOn: settings.mascot !== false,
    progress, nav, onTab,
  };

  let body;
  if (screen === 'onboarding') body = <OnboardingScreen {...common} />;
  else if (screen === 'home')    body = <HomeScreen {...common} />;
  else if (screen === 'player')  body = <LessonPlayerScreen {...common} params={params} onLessonComplete={onLessonComplete}/>;
  else if (screen === 'drill')   body = <DrillScreen {...common} />;
  else if (screen === 'complete')body = <CompleteScreen {...common} params={params} />;
  else if (screen === 'profile') body = <ProfileScreen {...common} />;
  else if (screen === 'tutor')   body = <TutorScreen {...common} />;
  else if (screen === 'roleplay')body = <RolePlayScreen {...common} />;
  else if (screen === 'settings')body = <SettingsScreen {...common}
                                          settings={settings} setSettings={setSettings}
                                          themeKey={settings.themeKey} setThemeKey={setThemeKey}
                                          onReset={onReset}/>;
  else body = <HomeScreen {...common} />;

  return (
    <AppShell theme={theme}>
      <div style={{
        width: '100%', height: '100%',
        background: theme.bg, color: theme.fg,
        fontFamily: theme.fontBody,
        position: 'relative', overflow: 'hidden',
      }}>
        {theme.grain !== 'none' && (
          <div style={{
            position: 'absolute', inset: 0,
            backgroundImage: grainBg(theme),
            mixBlendMode: theme.grain === 'dark' ? 'screen' : 'multiply',
            opacity: theme.grain === 'dark' ? 0.5 : 0.6,
            pointerEvents: 'none', zIndex: 100,
          }}/>
        )}
        {body}
      </div>
    </AppShell>
  );
}

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