// Main app shell — history routing + page mounting.

const { useState: useState_App, useEffect: useEffect_App } = React;

function getPageScroller() {
  const root = document.scrollingElement;
  if (root && root.scrollHeight > root.clientHeight) return root;
  return document.body || root;
}

function scrollPageToTop() {
  const scroller = getPageScroller();
  if (scroller && typeof scroller.scrollTo === 'function') {
    scroller.scrollTo({ top: 0, left: 0, behavior: 'auto' });
  } else if (scroller) {
    scroller.scrollTop = 0;
  }

  document.documentElement.scrollTop = 0;
  if (document.body) document.body.scrollTop = 0;
  window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
}

function getRouteFromLocation() {
  const legacyHash = window.location.hash || '';
  if (legacyHash.startsWith('#/')) {
    const cleanPath = normalizeRoutePath(legacyHash.slice(1) || '/');
    window.history.replaceState(null, '', cleanPath);
    return cleanPath;
  }
  const cleanPath = normalizeRoutePath(window.location.pathname || '/');
  if (cleanPath !== window.location.pathname) {
    window.history.replaceState(null, '', cleanPath);
  }
  return cleanPath;
}

function normalizeRoutePath(path) {
  if (path === '/course/premium') return '/services/premium-publication-program';
  if (path === '/course/fast-track') return '/services/fast-track-publication-program';
  return path;
}

function usePathRoute() {
  const [route, setRoute] = useState_App(getRouteFromLocation());
  useEffect_App(() => {
    const on = () => setRoute(getRouteFromLocation());
    window.addEventListener('popstate', on);
    return () => window.removeEventListener('popstate', on);
  }, []);
  return route;
}

function isInternalRouteLink(link) {
  if (!link) return false;
  const href = link.getAttribute('href') || '';
  if (!href || href.startsWith('#') || href.startsWith('mailto:') || href.startsWith('tel:')) return false;
  const url = new URL(link.href, window.location.origin);
  return url.origin === window.location.origin;
}

function navigateTo(path) {
  if (path !== window.location.pathname) {
    window.history.pushState(null, '', path);
  }
  window.dispatchEvent(new PopStateEvent('popstate'));
  window.dispatchEvent(new Event('app:navigation'));
}

function App() {
  const route = usePathRoute();
  useEffect_App(() => {
    requestAnimationFrame(scrollPageToTop);
  }, [route]);

  useEffect_App(() => {
    const onInternalRouteClick = (event) => {
      if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
      const link = event.target.closest?.('a[href]');
      if (!isInternalRouteLink(link)) return;
      if (link.target && link.target !== '_self') return;
      const url = new URL(link.href, window.location.origin);
      event.preventDefault();
      navigateTo(url.pathname);
    };

    document.addEventListener('click', onInternalRouteClick);
    return () => document.removeEventListener('click', onInternalRouteClick);
  }, []);

  const parts = route.split('/').filter(Boolean);
  const active = parts[0] || 'home';

  let Screen, label;
  switch (active) {
    case 'services':
      Screen = parts[1]
        ? <CourseDetailPage courseId={parts[1]} />
        : <ServicesPage />;
      label = 'services';
      break;
    case 'about':
      Screen = <AboutPage />;    label = 'about';    break;
    case 'contact':
      Screen = <ContactPage />;  label = 'contact';  break;
    case 'course':
      Screen = <CourseDetailPage courseId={parts[1]} />; label = 'services'; break;
    default:
      Screen = <HomePage />;     label = 'home';
  }

  return (
    <div style={{ background: '#fff', minHeight: '100%' }}>
      <Navigation active={label} />
      <main>{Screen}</main>
      <Footer />
    </div>
  );
}

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