// app.jsx — Root React component + hash router for EasyLife V2
const { useState: useAppState, useEffect: useAppEffect } = React;

// ── i18next init ──
(function initI18n() {
  if (!window.i18next) return;
  const savedLang = localStorage.getItem('el-lang') || 'no';
  window.i18next.init({
    lng: savedLang,
    fallbackLng: 'no',
    resources: {
      no: { translation: {} },
      en: { translation: {} },
    },
    interpolation: { escapeValue: false },
  }).then(() => {
    // Locales are fetched async and merged
    function loadLocale(lang) {
      fetch(`./locales/${lang}.json`)
        .then(r => r.json())
        .then(data => {
          window.i18next.addResourceBundle(lang, 'translation', data, true, true);
          if (window.i18next.language === lang) {
            window.i18next.changeLanguage(lang);
          }
        })
        .catch(() => {});
    }
    loadLocale('no');
    loadLocale('en');
  });
})();

// ── Theme init ──
(function initTheme() {
  const t = localStorage.getItem('el-theme') || 'dark';
  document.documentElement.setAttribute('data-theme', t);
})();

// ── Hash router ──
function getRouteFromHash(hash) {
  const map = {
    '#/dashboard': 'dashboard',
    '#/tasks': 'tasks',
    '#/projects': 'projects',
    '#/journal': 'journal',
    '#/routines': 'routines',
    '#/goals': 'goals',
    '#/balance': 'balance',
    '#/notes': 'notes',
    '#/prompts': 'prompts',
  };
  return map[hash] || 'dashboard';
}

function App() {
  const [gamifyEnabled, setGamifyEnabled] = useAppState(() => localStorage.getItem('el-gamify') === 'true');

  // Listen for toggle from AvatarMenu
  useAppEffect(() => {
    const handler = (e) => setGamifyEnabled(e.detail);
    window.addEventListener('el-gamify-change', handler);
    return () => window.removeEventListener('el-gamify-change', handler);
  }, []);

  return (
    <GamifyProvider enabled={gamifyEnabled}>
      <AppInner />
      <FocusModeRoot />
    </GamifyProvider>
  );
}

function AppInner() {
  const [route, setRoute] = useAppState(() => {
    const h = window.location.hash;
    if (!h || h === '#' || h === '#/') {
      window.location.hash = '#/dashboard';
      return 'dashboard';
    }
    return getRouteFromHash(h);
  });
  const [session, setSession] = useAppState(null);
  const [authChecked, setAuthChecked] = useAppState(false);
  const [uiMode, setUiMode] = useAppState(() => localStorage.getItem('el-uimode') || 'easy');
  const demoMode = !!window.EASYLIFE_DEMO?.enabled;

  // Listen to hash changes
  useAppEffect(() => {
    function onHashChange() {
      const r = getRouteFromHash(window.location.hash);
      setRoute(r);
    }
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);

  // Auth check
  useAppEffect(() => {
    supabaseClient.auth.getSession().then(({ data }) => {
      setSession(data.session);
      setAuthChecked(true);

      // Redirect to login if not authenticated
      if (!data.session && !demoMode) {
        window.location.href = '/login.html';
      }
    });

    const { data: { subscription } } = supabaseClient.auth.onAuthStateChange((_event, sess) => {
      setSession(sess);
      if (!sess && authChecked && !demoMode) {
        window.location.href = '/login.html';
      }
    });

    return () => subscription.unsubscribe();
  }, []);

  // UI mode storage sync
  useAppEffect(() => {
    const onStorage = () => {
      setUiMode(localStorage.getItem('el-uimode') || 'easy');
    };
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }, []);

  function navigate(key) {
    setRoute(key);
    const hashMap = {
      dashboard: '#/dashboard',
      tasks: '#/tasks',
      projects: '#/projects',
      journal: '#/journal',
      routines: '#/routines',
      goals: '#/goals',
      balance: '#/balance',
      notes: '#/notes',
      prompts: '#/prompts',
    };
    window.location.hash = hashMap[key] || '#/dashboard';
  }

  // Show nothing while auth is being checked
  if (!authChecked) {
    return (
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        minHeight: '100vh', background: 'var(--bg)',
      }}>
        <div style={{ textAlign: 'center', color: 'var(--sec)' }}>
          <div style={{
            width: 40, height: 40, borderRadius: '50%',
            border: '3px solid var(--accent)', borderTopColor: 'transparent',
            animation: 'spin 1s linear infinite', margin: '0 auto 16px',
          }} />
          <p style={{ fontSize: 13, fontWeight: 500 }}>Laster EasyLife…</p>
        </div>
        <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
      </div>
    );
  }

  // Render current page
  function renderPage() {
    switch (route) {
      case 'dashboard':  return <Dashboard uiMode={uiMode} onToggleMode={handleToggleMode} />;
      case 'tasks':      return <Tasks uiMode={uiMode} />;
      case 'projects':   return <Projects uiMode={uiMode} />;
      case 'journal':    return <Journal />;
      case 'routines':   return <Routines />;
      case 'goals':      return <Goals />;
      case 'balance':    return <Balance />;
      case 'notes':      return <Notes />;
      case 'prompts':    return <Prompts />;
      default:           return <Dashboard uiMode={uiMode} />;
    }
  }

  function handleToggleMode(mode) {
    setUiMode(mode);
    localStorage.setItem('el-uimode', mode);
    window.dispatchEvent(new CustomEvent('el-uimode-change', { detail: mode }));
  }

  return (
    <AppShell currentRoute={route} onNavigate={navigate} uiMode={uiMode} onToggleMode={handleToggleMode}>
      {renderPage()}
    </AppShell>
  );
}

// ── Mount ──
ReactDOM.createRoot(document.getElementById('app')).render(<App />);
