// App shell: welcome screen, top bar, routing, persistence, tweaks
const { useState, useEffect, useRef, useMemo } = React;

const SAVE_KEY = 'sbl-state-v1';
const SCREEN_LIST = [
  { id: 'words', label: 'Words' },
  { id: 'match', label: 'Match' },
  { id: 'spell', label: 'Spell' },
  { id: 'build', label: 'Build' },
  { id: 'gaps',  label: 'Gaps' },
  { id: 'quiz',  label: 'Quiz' },
  { id: 'bucket', label: 'My List' },
];

const SBL_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#FFC23E", "#3FA9E0", "#FF6F59", "#FFF8EA", "#24405B"],
  "confetti": true,
  "buddy": true,
  "textScale": 100
}/*EDITMODE-END*/;

const SBL_PALETTES = [
  ["#FFC23E", "#3FA9E0", "#FF6F59", "#FFF8EA", "#24405B"], // sunny
  ["#F2C94C", "#7FD8BE", "#F2994A", "#FBF6EC", "#3D4A3E"], // beachy pastel
  ["#FF8A3D", "#2E9B5B", "#F25C9B", "#FFF4E8", "#33272A"], // tropical bold
];

function App() {
  const [t, setTweak] = useTweaks(SBL_TWEAK_DEFAULTS);
  const [state, setState] = useState(() => {
    try {
      const s = JSON.parse(localStorage.getItem(SAVE_KEY));
      if (s && typeof s.screen === 'number') return s;
    } catch (e) {}
    return { name: '', screen: -1, stars: 0, done: {} };
  });
  const [soundOn, setSoundOn] = useState(true);

  useEffect(() => {
    try { localStorage.setItem(SAVE_KEY, JSON.stringify(state)); } catch (e) {}
  }, [state]);
  useEffect(() => { SFX.enabled = soundOn; }, [soundOn]);
  useEffect(() => { window.__sblConfettiOn = !!t.confetti; }, [t.confetti]);
  useEffect(() => {
    const [sun, sky, coral, bg, ink] = t.palette;
    const r = document.documentElement.style;
    r.setProperty('--sun', sun);
    r.setProperty('--sky', sky);
    r.setProperty('--coral', coral);
    r.setProperty('--bg', bg);
    r.setProperty('--ink', ink);
    r.setProperty('--text-scale', (t.textScale || 100) / 100);
  }, [t.palette, t.textScale]);

  const { name, screen, stars, done } = state;
  const patch = (p) => setState((s) => ({ ...s, ...p }));

  // Stars are only earnable the first time you play an activity
  const earnFor = (id) => (n) => {
    setState((s) => (s.done[id] ? s : { ...s, stars: s.stars + n }));
  };
  const completeScreen = (id) => () => {
    setState((s) => ({
      ...s,
      done: { ...s.done, [id]: true },
      screen: Math.min(s.screen + 1, SCREEN_LIST.length - 1),
    }));
    window.scrollTo(0, 0);
  };

  // ---------- Welcome ----------
  if (screen < 0) {
    return (
      <div className="welcome" data-screen-label="Welcome">
        <div className="welcome-sun">
          <div className="welcome-sun-core"></div>
        </div>
        {t.buddy && <Mascot className="welcome-mascot" />}
        <p className="welcome-kicker">An English adventure for summer</p>
        <h1 className="welcome-title">My Summer<br />Bucket List</h1>
        <div className="welcome-form">
          <label className="welcome-label" htmlFor="name-input">What is your name?</label>
          <input id="name-input" type="text" className="welcome-input" maxLength={20}
            placeholder="Type your name&#8230;" value={name}
            onChange={(e) => patch({ name: e.target.value })}
            onKeyDown={(e) => { if (e.key === 'Enter' && name.trim()) { SFX.win(); patch({ screen: 0 }); } }} />
          <button type="button" className="btn btn-next btn-go" disabled={!name.trim()}
            onClick={() => { SFX.win(); burstConfetti(20); patch({ screen: 0 }); }}>
            Let&#8217;s go! &#9728;
          </button>
        </div>
        <Tweaks t={t} setTweak={setTweak} onReset={() => resetAll()} />
      </div>
    );
  }

  function resetAll() {
    try {
      localStorage.removeItem(SAVE_KEY);
      localStorage.removeItem('sbl-bucket-v1');
    } catch (e) {}
    window.location.reload();
  }

  const cur = SCREEN_LIST[screen];
  const earn = earnFor(cur.id);

  return (
    <div className="app" data-screen-label={cur.label}>
      <header className="topbar no-print">
        <button type="button" className="topbar-back" aria-label="Back"
          disabled={screen <= 0 && false}
          onClick={() => { SFX.click(); patch({ screen: screen - 1 }); }}>
          &#8592;
        </button>
        <div className="topbar-steps">
          {SCREEN_LIST.map((s, i) => (
            <button key={s.id} type="button"
              className={'step-dot' + (i === screen ? ' step-dot-now' : '') + (done[s.id] ? ' step-dot-done' : '')}
              disabled={!done[s.id] && i > screen}
              aria-label={s.label}
              onClick={() => { SFX.click(); patch({ screen: i }); }}>
            </button>
          ))}
        </div>
        <div className="topbar-right">
          <div className="star-count">★ {stars}</div>
          <button type="button" className="sound-btn" aria-label="Sound on/off"
            onClick={() => { setSoundOn(!soundOn); }}>
            {soundOn ? '♪' : '✕'}
          </button>
        </div>
      </header>

      <main className="screen-wrap">
        {cur.id === 'words' && <WordsActivity earn={earn} onComplete={completeScreen('words')} />}
        {cur.id === 'match' && <MatchActivity key={'m' + screen} earn={earn} onComplete={completeScreen('match')} />}
        {cur.id === 'spell' && <SpellActivity key={'s' + screen} earn={earn} onComplete={completeScreen('spell')} />}
        {cur.id === 'build' && <BuildActivity key={'b' + screen} earn={earn} onComplete={completeScreen('build')} />}
        {cur.id === 'gaps' && <GapsActivity key={'g' + screen} earn={earn} onComplete={completeScreen('gaps')} />}
        {cur.id === 'quiz' && <QuizActivity key={'q' + screen} earn={earn} onComplete={completeScreen('quiz')} />}
        {cur.id === 'bucket' && <BucketActivity name={name.trim()} stars={stars} earn={earn} buddy={t.buddy} />}
      </main>

      {t.buddy && (
        <Mascot className="walker no-print" key="walker" />
      )}

      <Tweaks t={t} setTweak={setTweak} onReset={resetAll} />
    </div>
  );
}

function Tweaks({ t, setTweak, onReset }) {
  return (
    <TweaksPanel>
      <TweakSection label="Look" />
      <TweakColor label="Color theme" value={t.palette} options={SBL_PALETTES}
        onChange={(v) => setTweak('palette', v)} />
      <TweakSlider label="Text size" value={t.textScale} min={90} max={125} step={5} unit="%"
        onChange={(v) => setTweak('textScale', v)} />
      <TweakSection label="Fun" />
      <TweakToggle label="Confetti" value={t.confetti} onChange={(v) => setTweak('confetti', v)} />
      <TweakToggle label="Walking buddy" value={t.buddy} onChange={(v) => setTweak('buddy', v)} />
      <TweakSection label="Class" />
      <TweakButton label="Reset all progress" onClick={onReset} />
    </TweaksPanel>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
