/* ============================================================
   INDIC LEAGUE NEWS — App shell
   Top-level routing + persistence.
   Routes: splash -> login -> onboarding -> quiz -> feed
   ============================================================ */

const ROUTES = {
  SPLASH: 'splash',
  LOGIN: 'login',
  ONBOARD: 'onboard',
  QUIZ: 'quiz',
  FEED: 'feed',
};

function App() {
  const Storage = window.IL_Util.Storage;
  const KEYS = window.IL_KEYS;

  // Initial route inference. If user already onboarded, go straight to feed.
  const computeInitial = () => {
    const topics = Storage.get(KEYS.topics, null);
    if (Array.isArray(topics) && topics.length >= 3) return ROUTES.FEED;
    return ROUTES.SPLASH;
  };

  const [route, setRoute] = React.useState(computeInitial);
  const [user, setUser] = React.useState(() => Storage.get(KEYS.user, null));
  const [theme, setTheme] = React.useState(() => {
    const stored = Storage.get(KEYS.theme, null);
    if (stored === 'dark' || stored === 'light') return stored;
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) return 'dark';
    return 'light';
  });

  // Quiz-result-on-return-to-onboarding stash
  const [pendingPolitical, setPendingPolitical] = React.useState(null);

  // Apply theme
  React.useEffect(() => {
    window.IL_Util.applyTheme(theme);
    Storage.set(KEYS.theme, theme);
  }, [theme]);

  // Remove pre-react boot splash once mounted
  React.useEffect(() => {
    const boot = document.querySelector('.boot');
    if (boot) {
      boot.style.transition = 'opacity 400ms';
      boot.style.opacity = '0';
      setTimeout(() => boot.remove(), 420);
    }
  }, []);

  // Browser back-button support
  React.useEffect(() => {
    const onPop = (e) => {
      // Always send user to feed if onboarded, else splash
      if (Storage.get(KEYS.topics, []).length >= 3) {
        setRoute(ROUTES.FEED);
      } else {
        setRoute(ROUTES.SPLASH);
      }
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  // Track desktop layout class
  const [wide, setWide] = React.useState(window.matchMedia('(min-width: 1024px)').matches);
  React.useEffect(() => {
    const mq = window.matchMedia('(min-width: 1024px)');
    const handler = (e) => setWide(e.matches);
    if (mq.addEventListener) mq.addEventListener('change', handler);
    else mq.addListener(handler);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', handler);
      else mq.removeListener(handler);
    };
  }, []);

  // -------- handlers --------
  const onSplashContinue = (where) => {
    if (where === 'login') setRoute(ROUTES.LOGIN);
    else setRoute(ROUTES.ONBOARD);
  };

  const onLoggedIn = (u) => {
    setUser(u);
    const topics = Storage.get(KEYS.topics, []);
    if (Array.isArray(topics) && topics.length >= 3) {
      setRoute(ROUTES.FEED);
    } else {
      setRoute(ROUTES.ONBOARD);
    }
  };

  const onOnboardComplete = () => {
    setPendingPolitical(null);
    setRoute(ROUTES.FEED);
  };

  const onStartQuiz = () => setRoute(ROUTES.QUIZ);

  const onQuizComplete = (result) => {
    // result: { position, label, optionId, method }
    setPendingPolitical(result);
    setRoute(ROUTES.ONBOARD);
  };

  const onQuizCancel = () => {
    setPendingPolitical(null);
    // If user came from onboarding, back to onboarding. Otherwise feed.
    const topics = Storage.get(KEYS.topics, []);
    if (Array.isArray(topics) && topics.length >= 3) setRoute(ROUTES.FEED);
    else setRoute(ROUTES.ONBOARD);
  };

  const onLogout = () => {
    Storage.remove(KEYS.user);
    Storage.remove(KEYS.authed);
    setUser(null);
    // Keep topics so they don't have to re-onboard. Just dump to splash.
    setRoute(ROUTES.SPLASH);
  };

  const toggleTheme = () => {
    setTheme(t => (t === 'dark' ? 'light' : 'dark'));
    window.IL_Sounds && window.IL_Sounds.tap();
    window.IL_Util && window.IL_Util.Haptics.light();
  };

  // -------- render --------
  let body;
  switch (route) {
    case ROUTES.SPLASH:
      body = <Splash onContinue={onSplashContinue} />;
      break;
    case ROUTES.LOGIN:
      body = <Login onLoggedIn={onLoggedIn} onBack={() => setRoute(ROUTES.SPLASH)} />;
      break;
    case ROUTES.ONBOARD:
      body = (
        <Onboarding
          initialTopics={Storage.get(KEYS.topics, [])}
          onComplete={onOnboardComplete}
          onStartQuiz={onStartQuiz}
          prefilledPosition={pendingPolitical}
        />
      );
      break;
    case ROUTES.QUIZ:
      body = <Quiz onComplete={onQuizComplete} onCancel={onQuizCancel} />;
      break;
    case ROUTES.FEED:
    default:
      body = (
        <Feed
          articles={window.IL_ARTICLES}
          user={user}
          onLogout={onLogout}
          theme={theme}
          onToggleTheme={toggleTheme}
        />
      );
      break;
  }

  return (
    <div className={'app' + (wide && route === ROUTES.FEED ? ' desktop-layout' : '')}>
      <div className="statusbar">
        <span>9:41</span>
        <span className="statusbar-icons">
          <svg width="17" height="11" viewBox="0 0 17 11"><rect x="0" y="7" width="3" height="4" rx=".7" fill="currentColor"/><rect x="4.5" y="5" width="3" height="6" rx=".7" fill="currentColor"/><rect x="9" y="2.5" width="3" height="8.5" rx=".7" fill="currentColor"/><rect x="13.5" y="0" width="3" height="11" rx=".7" fill="currentColor"/></svg>
          <svg width="15" height="11" viewBox="0 0 17 11"><path d="M8.5 3C10.5 3 12.4 3.8 13.7 5.2L14.7 4.2C13 2.5 10.8 1.5 8.5 1.5C6.2 1.5 4 2.5 2.3 4.2L3.3 5.2C4.6 3.8 6.5 3 8.5 3Z" fill="currentColor"/><circle cx="8.5" cy="9" r="1.5" fill="currentColor"/></svg>
          <svg width="25" height="12" viewBox="0 0 25 12"><rect x="0.5" y="0.5" width="21" height="11" rx="3" stroke="currentColor" strokeOpacity=".4" fill="none"/><rect x="2" y="2" width="18" height="8" rx="1.5" fill="currentColor"/><path d="M23 4v4c.7-.2 1.3-1 1.3-2S23.7 4.2 23 4z" fill="currentColor" fillOpacity=".4"/></svg>
        </span>
      </div>
      <div className="shell">
        {body}
      </div>
    </div>
  );
}

Object.assign(window, { App });
