const DEFAULT_ROUTE = 'home';
const DEFAULT_TITLE = 'CLEANEPEL';

const ROUTES = {
  home: {
    title: 'CLEANEPEL — Manutenção têxtil para empresas | Contratos em Portugal',
    file: 'index',
  },
  sobre: {title: 'Sobre — CLEANEPEL', file: 'sobre', navKey: 'sobre'},
  servicos: {title: 'Serviços — CLEANEPEL', file: 'servicos', navKey: 'servicos'},
  setores: {title: 'Setores de atuação — CLEANEPEL', file: 'setores', navKey: 'setores'},
  contratos: {
    title: 'Contratos de manutenção — CLEANEPEL',
    file: 'contratos',
    navKey: 'contratos',
  },
  casos: {
    title: 'Casos de sucesso — CLEANEPEL',
    file: 'casos-de-sucesso',
    navKey: 'casos',
  },
  blog: {title: 'Blog — CLEANEPEL', file: 'blog', navKey: 'blog'},
  diagnostico: {
    title: 'Diagnóstico de Instalação — CLEANEPEL',
    file: 'diagnostico',
    navKey: 'diagnostico',
  },
  contacto: {title: 'Contacto — CLEANEPEL', file: 'contacto', navKey: 'contacto'},
  visita: {
    title: 'Pedido de visita técnica — CLEANEPEL',
    file: 'visita-tecnica',
  },
};

const FILE_TO_ROUTE = Object.fromEntries(
  Object.entries(ROUTES).map(([slug, {file}]) => [file, slug]),
);

function parseHash() {
  const rawRoute = (location.hash || `#${DEFAULT_ROUTE}`).slice(1);
  const [requestedSlug, query = ''] = rawRoute.split('?');
  const slug = window.__PAGES[requestedSlug] ? requestedSlug : DEFAULT_ROUTE;

  return {slug, query};
}

function applyRoute(route, {scroll = false} = {}) {
  window.__ROUTEQ = route.query;
  document.title = ROUTES[route.slug]?.title || DEFAULT_TITLE;
  if (scroll) window.scrollTo(0, 0);
}

function LoadingPage() {
  return <div className="route-loading">A carregar…</div>;
}

function Router() {
  const [route, setRoute] = React.useState(parseHash);

  React.useEffect(() => {
    const updateRoute = ({scroll = false} = {}) => {
      const nextRoute = parseHash();
      applyRoute(nextRoute, {scroll});
      setRoute(nextRoute);
    };

    const handleHashChange = () => updateRoute({scroll: true});
    const handlePageReady = () => updateRoute();

    window.addEventListener('hashchange', handleHashChange);
    window.addEventListener('pageready', handlePageReady);

    return () => {
      window.removeEventListener('hashchange', handleHashChange);
      window.removeEventListener('pageready', handlePageReady);
    };
  }, []);

  const Page = window.__PAGES[route.slug];
  const routeConfig = ROUTES[route.slug];

  return (
    <div>
      <Nav active={routeConfig?.navKey} />
      <main>{Page ? <Page key={`${route.slug}?${route.query}`} /> : <LoadingPage />}</main>
      <Footer />
    </div>
  );
}

function handleInternalNavigation(event) {
  const link = event.target.closest?.('a');
  if (!link) return;

  const href = link.getAttribute('href') || '';
  const match = href.match(/^([a-z0-9-]+)\.html(\?[^#]*)?(#.*)?$/i);
  const slug = match && FILE_TO_ROUTE[match[1]];
  if (!slug) return;

  event.preventDefault();
  location.hash = slug + (match[2] || '');
}

document.addEventListener('click', handleInternalNavigation, true);

if (!location.hash) location.hash = DEFAULT_ROUTE;

const initialRoute = parseHash();
applyRoute(initialRoute);
ReactDOM.createRoot(getRoot()).render(<Router />);
