// App entrypoint
const SCROLL_Y_STORAGE_KEY = 'kiroshi_landing_scroll_y';

const App = () => {
  React.useEffect(() => {
    if ('scrollRestoration' in window.history) {
      window.history.scrollRestoration = 'manual';
    }
  }, []);

  React.useLayoutEffect(() => {
    const savedScroll = window.sessionStorage.getItem(SCROLL_Y_STORAGE_KEY);
    if (!savedScroll) return;

    const y = Number(savedScroll);
    if (!Number.isFinite(y) || y < 0) return;

    let attempts = 0;
    const maxAttempts = 24;

    const restoreScroll = () => {
      attempts += 1;
      window.scrollTo({ top: y, behavior: 'auto' });

      const closeEnough = Math.abs(window.scrollY - y) < 2;
      if (closeEnough || attempts >= maxAttempts) return true;
      return false;
    };

    const rafId = window.requestAnimationFrame(() => {
      if (restoreScroll()) return;

      const timerId = window.setInterval(() => {
        if (restoreScroll()) {
          window.clearInterval(timerId);
        }
      }, 50);

      window.setTimeout(() => window.clearInterval(timerId), 1500);
    });

    const onPageShow = () => {
      window.requestAnimationFrame(() => {
        restoreScroll();
      });
    };

    window.addEventListener('pageshow', onPageShow);

    return () => {
      window.cancelAnimationFrame(rafId);
      window.removeEventListener('pageshow', onPageShow);
    };
  }, []);

  React.useEffect(() => {
    const saveScroll = () => {
      window.sessionStorage.setItem(SCROLL_Y_STORAGE_KEY, String(window.scrollY));
    };

    window.addEventListener('scroll', saveScroll, { passive: true });
    window.addEventListener('beforeunload', saveScroll);

    return () => {
      window.removeEventListener('scroll', saveScroll);
      window.removeEventListener('beforeunload', saveScroll);
    };
  }, []);

  return (
    <div id="page">
      <Header />
      <main>
        <Hero />
        <Problem />
        <Showcase />
        <SearchExamples />
        <Timeline />
        <Privacy />
        <UseCases />
        <InDevelopment />
        <Pricing />
        <Roadmap />
        <Founder />
        <FinalCTA />
      </main>
      <Footer />
    </div>
  );
};

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