/* global React, ReactDOM, Nav, Footer, MobileNav, Home, Services, Cases, About, Blog, Contact, Tweaks */
const { useEffect: aUseEffect, useState: aUseState } = React;
const { createPortal } = ReactDOM;

const GM_ROUTES = (window.GM_CONFIG && window.GM_CONFIG.routes) || {
  home: '/', services: '/servicios/', cases: '/casos/',
  about: '/nosotros/', blog: '/blog-gm/', contact: '/contacto/',
};
const VALID_ROUTES = Object.keys(GM_ROUTES);

function routeFromUrl() {
  const path = window.location.pathname.replace(/\/$/, '') || '/';
  for (const [key, url] of Object.entries(GM_ROUTES)) {
    const urlPath = url.replace(/\/$/, '') || '/';
    if (path === urlPath) return key;
  }
  return null;
}

function App() {
  const [route, setRoute] = aUseState(() => {
    if (window.GM_CONFIG && window.GM_CONFIG.initialRoute) return window.GM_CONFIG.initialRoute;
    return routeFromUrl() || 'home';
  });

  aUseEffect(() => {
    const t = window.TWEAKS || {};
    document.documentElement.style.setProperty('--accent', t.accent || '#EC4E3C');
    document.documentElement.setAttribute('data-theme', t.theme || 'light');
    document.documentElement.setAttribute('data-density', t.density || 'comfortable');

    // Reservar espacio para la bottom nav en mobile
    const applyBodyPad = () => {
      if (window.innerWidth <= 880) {
        document.body.style.paddingBottom = 'calc(72px + env(safe-area-inset-bottom, 0px))';
      } else {
        document.body.style.paddingBottom = '';
      }
    };
    applyBodyPad();
    window.addEventListener('resize', applyBodyPad);
    return () => window.removeEventListener('resize', applyBodyPad);
  }, []);

  aUseEffect(() => {
    const url = GM_ROUTES[route] || '/';
    if (window.location.pathname !== new URL(url, window.location.origin).pathname) {
      window.history.pushState({ route }, '', url);
    }
    window.scrollTo({ top: 0, behavior: 'instant' });
    try { localStorage.setItem('gm:route', route); } catch (e) {}
  }, [route]);

  aUseEffect(() => {
    const onPop = (e) => {
      const r = (e.state && e.state.route) || routeFromUrl() || 'home';
      setRoute(r);
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const pages = { home: Home, services: Services, cases: Cases, about: About, blog: Blog, contact: Contact };
  const Page = pages[route] || Home;

  return (
    <>
      <div data-screen-label={`Page · ${route}`}>
        <Nav route={route} setRoute={setRoute} />
        <Page setRoute={setRoute} />
        <Footer setRoute={setRoute} />
        <Tweaks />
      </div>
      {createPortal(
        <MobileNav route={route} setRoute={setRoute} />,
        document.body
      )}
    </>
  );
}

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