/* app.jsx — top-level App: routing, layout, navigation, splash */
const {
  useState: useStateA, useEffect: useEffectA, useRef: useRefA, useCallback: useCallbackA,
} = React;

function TopBar({ currentPage }) {
  const { t, lang, setLang } = window.useI18n();
  const clock = window.useClock();
  return (
    <header className="topbar">
      <div className="traffic"><span></span><span></span><span></span></div>
      <div className="topbar-title">
        <span className="path-segment">david@fontanet</span>
        <span className="path-sep">:</span>
        <span className="path-segment">~</span>
        <span className="path-sep">/</span>
        <span className="path-segment neon">{t(`path.${currentPage}`)}</span>
      </div>
      <div className="topbar-right">
        <span className="clock">{clock}</span>
        <div className="lang-toggle">
          <button className={lang === 'es' ? 'active' : ''} onClick={() => setLang('es')}>ES</button>
          <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
        </div>
      </div>
    </header>
  );
}

function Sidebar({ currentPage }) {
  const { t } = window.useI18n();
  const uptime = window.useUptime();
  const Link = window.Link;
  const items = [
    ['home', 'sh'], ['about', 'md'], ['education', '/'],
    ['skills', 'json'], ['experience', 'log'], ['projects', '/'], ['contact', 'sh'],
  ];
  return (
    <aside className="sidebar">
      <div className="sidebar-heading">{t('side.nav')}</div>
      <ul className="tree">
        <li className="tree-folder">
          <div className="tree-label">~/portfolio</div>
          <ul>
            {items.map(([slug, ext]) => (
              <li key={slug}>
                <Link to={slug} className={currentPage === slug ? 'active' : ''}>
                  <span className="icon">{currentPage === slug ? '▸' : '●'}</span>
                  <span>{t(`path.${slug}`)}</span>
                  <span className="muted">{ext === '/' ? '/' : '.' + ext}</span>
                </Link>
              </li>
            ))}
          </ul>
        </li>
      </ul>
      <div className="sidebar-section">
        <div className="sidebar-heading">{t('side.connect')}</div>
        <ul className="tree">
          <li><a href="https://github.com/DavidFB-creator" target="_blank" rel="noopener noreferrer"><span className="icon">↗</span>github</a></li>
          <li><a href="https://www.linkedin.com/in/david-fontanet-bujald%C3%B3n/" target="_blank" rel="noopener noreferrer"><span className="icon">↗</span>linkedin</a></li>
        </ul>
      </div>
      <div className="sidebar-meta">
        <div><span className="led"></span><span className="val">{t('side.available')}</span></div>
        <div style={{ marginTop: 8 }}><span className="key">loc:</span> <span className="val">{t('side.location')}</span></div>
        <div><span className="key">{t('side.uptime')}</span><span>: </span><span className="val">{uptime}</span></div>
        <div><span className="key">$</span> <span className="val">{t('side.shell')}</span></div>
      </div>
    </aside>
  );
}

function StatusBar({ currentPage, onNavigate, onMatrix }) {
  const { t } = window.useI18n();
  const fileLabel = (window.PAGE_FILE[currentPage] || currentPage);
  const promptPath = (window.PAGE_PROMPT_PATH[currentPage] || '~');
  return (
    <footer className="statusbar">
      <span className="seg accent"><span className="led"></span>{t('status.online')}</span>
      <span className="seg muted">main</span>
      <span className="seg dim">|</span>
      <span className="seg muted">utf-8</span>
      <span className="seg dim">|</span>
      <span className="seg muted">{fileLabel}</span>
      <window.CommandBar pathLabel={promptPath} onNavigate={onNavigate} onMatrix={onMatrix} />
      <span className="seg dim cmd-hint"><span className="kbd">Tab</span> autocomplete</span>
    </footer>
  );
}

function PageView({ currentPage }) {
  const { lang } = window.useI18n();
  const ref = useRefA(null);
  // remount on page or lang change to retrigger stage sequence cleanly
  window.useStageSequence(ref, `${currentPage}-${lang}`);

  const Map = {
    home: window.HomePage,
    about: window.AboutPage,
    education: window.EducationPage,
    skills: window.SkillsPage,
    experience: window.ExperiencePage,
    projects: window.ProjectsPage,
    contact: window.ContactPage,
  };
  const Page = Map[currentPage] || window.HomePage;
  return (
    <main className="content" key={`${currentPage}-${lang}`}>
      <div ref={ref}>
        <Page />
      </div>
    </main>
  );
}

function App() {
  const [currentPage, setCurrentPage] = useStateA(() => window.pageFromPath());
  const [transitionTarget, setTransitionTarget] = useStateA(null);
  const [matrixOn, setMatrixOn] = useStateA(false);

  const navigate = useCallbackA((target) => {
    if (transitionTarget) return;
    if (target === currentPage) return;
    setTransitionTarget(target);
    setTimeout(() => {
      try { history.pushState({}, '', window.pageToPath(target)); } catch (e) {}
      setCurrentPage(target);
      setTransitionTarget(null);
    }, 520);
  }, [transitionTarget, currentPage]);

  // back / forward
  useEffectA(() => {
    function onPop() { setCurrentPage(window.pageFromPath()); }
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  // konami code → matrix
  window.useKonami(useCallbackA(() => {
    setMatrixOn(true);
  }, []));

  return (
    <window.I18nProvider>
      <window.ToastProvider>
        <window.NavContext.Provider value={navigate}>
          <window.Boot />
          <div className="os">
            <TopBar currentPage={currentPage} />
            <Sidebar currentPage={currentPage} />
            <PageView currentPage={currentPage} />
            <StatusBar
              currentPage={currentPage}
              onNavigate={navigate}
              onMatrix={() => setMatrixOn(true)}
            />
          </div>
          <window.RouteLoader target={transitionTarget} />
          <window.MatrixOverlay on={matrixOn} onExit={() => setMatrixOn(false)} />
        </window.NavContext.Provider>
      </window.ToastProvider>
    </window.I18nProvider>
  );
}

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