// MULTIPLIER — main app shell
const { useState, useEffect, useCallback } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "space",
  "soundOn": true,
  "musicOn": false,
  "defaultDifficulty": "auto"
}/*EDITMODE-END*/;

const App = () => {
  const t = window.MP_I18N.t;
  const [profile, setProfile] = useState(() => window.MP_DATA.loadProfile());
  const [screen, setScreen] = useState('home'); // home | ranking | profile | game | resultado | diploma
  const [game, setGame] = useState(null);
  const [result, setResult] = useState(null);
  const [share, setShare] = useState(false);
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);

  // Load language preference
  useEffect(() => {
    if (profile?.lang) window.MP_I18N.setLang(profile.lang);
    window.MP_SOUND.setEnabled(tweaks.soundOn);
  }, [profile?.lang, tweaks.soundOn]);

  // Tweaks integration
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') {
        window.dispatchEvent(new CustomEvent('mp-tweaks-show'));
      } else if (e.data?.type === '__deactivate_edit_mode') {
        window.dispatchEvent(new CustomEvent('mp-tweaks-hide'));
      }
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  // Service worker
  useEffect(() => {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('./sw.js').catch(() => {});
    }
  }, []);

  // Onboarding
  if (!profile || !profile.firstName) {
    return (
      <div className="app">
        <StarsBg />
        <Onboarding onDone={(data) => {
          const p = { ...window.MP_DATA.emptyProfile(), ...data };
          window.MP_DATA.saveProfile(p);
          setProfile(p);
          // Register on backend (fire and forget)
          window.MP_API.register({
            first_name: p.firstName,
            last_initial: p.lastInitial,
            school_code: p.schoolCode,
            school_name: p.schoolName,
            grade: p.grade
          });
        }} />
      </div>
    );
  }

  const updateProfile = (p) => {
    window.MP_DATA.saveProfile(p);
    setProfile({ ...p });
  };

  const playMode = (id) => {
    setGame(id);
    setScreen('game');
  };

  const finishGame = (gameResult) => {
    const isBestTA = gameResult.mode === 'time_attack' && gameResult.score > (profile.bestTimeAttack || 0);
    const isBestES = gameResult.mode === 'escalera' && gameResult.score > (profile.bestEscalera || 0);
    const { profile: newProfile, newBadges, newMascots } = window.MP_DATA.applyResult(profile, gameResult);
    window.MP_DATA.saveProfile(newProfile);
    setProfile(newProfile);
    // Submit to server
    window.MP_API.submitScore({
      first_name: newProfile.firstName,
      last_initial: newProfile.lastInitial,
      school_code: newProfile.schoolCode,
      school_name: newProfile.schoolName,
      grade: newProfile.grade,
      mode: gameResult.mode,
      score: gameResult.score,
      correct: gameResult.correct,
      total: gameResult.total
    });
    setResult({ ...gameResult, isBest: isBestTA || isBestES, newBadges, newMascots });
    setScreen('resultado');
    if (newBadges.length || newMascots.length) {
      setTimeout(() => window.MP_SOUND.unlock(), 800);
    }
  };

  const goHome = () => { setScreen('home'); setGame(null); setResult(null); };

  // Game router
  const renderGame = () => {
    const props = { profile, onFinish: finishGame, onQuit: goHome };
    switch (game) {
      case 'time_attack': return <TimeAttack {...props} />;
      case 'memorama':    return <Memorama {...props} />;
      case 'escalera':    return <Escalera {...props} />;
      case 'mision':      return <Mision {...props} />;
      case 'tabla':       return <TablaEspecifica {...props} />;
      case 'tf':          return <VerdaderoFalso {...props} />;
      case 'blank':       return <CompletaHueco {...props} />;
      default: return null;
    }
  };

  return (
    <div className="app">
      <StarsBg />
      {screen === 'home' && (
        <Home
          profile={profile}
          onPlay={playMode}
          onMission={() => playMode('mision')}
        />
      )}
      {screen === 'ranking' && <Ranking profile={profile} />}
      {screen === 'profile' && (
        <Perfil
          profile={profile}
          onUpdate={updateProfile}
          onLogout={() => { localStorage.removeItem('mp_profile'); setProfile(null); }}
          onDiploma={() => setScreen('diploma')}
        />
      )}
      {screen === 'game' && renderGame()}
      {screen === 'resultado' && result && (
        <Resultado
          profile={profile}
          result={result}
          onAgain={() => { setScreen('game'); setResult(null); }}
          onHome={goHome}
          onShare={() => setShare(true)}
          onDiploma={() => setScreen('diploma')}
        />
      )}
      {screen === 'diploma' && (
        <Diploma profile={profile} onClose={() => setScreen(result ? 'resultado' : 'profile')} />
      )}

      {share && <ShareModal profile={profile} score={result?.score} mode={result?.mode} onClose={() => setShare(false)} />}

      {/* Bottom navigation */}
      {(screen === 'home' || screen === 'ranking' || screen === 'profile') && (
        <nav className="bottom-nav">
          <div className="bottom-nav-inner">
            <button className={'nav-btn' + (screen === 'home' ? ' active' : '')} onClick={() => setScreen('home')}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12l9-9 9 9M5 10v10h14V10" /></svg>
              {t('home_nav')}
            </button>
            <button className={'nav-btn' + (screen === 'ranking' ? ' active' : '')} onClick={() => setScreen('ranking')}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M6 9V4h12v5M5 22h14M9 14v8M15 14v8M5 9h14a3 3 0 01-3 3H8a3 3 0 01-3-3z" /></svg>
              {t('ranking_nav')}
            </button>
            <button className="nav-btn" onClick={() => setShare(true)}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.6" y1="13.5" x2="15.4" y2="17.5"/><line x1="15.4" y1="6.5" x2="8.6" y2="10.5"/></svg>
              {t('friends')}
            </button>
            <button className={'nav-btn' + (screen === 'profile' ? ' active' : '')} onClick={() => setScreen('profile')}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
              {t('profile_nav')}
            </button>
          </div>
        </nav>
      )}
    </div>
  );
};

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