const { useState: _useState, useEffect: _useEffect } = React;

const ROUTER_LANGS = ['en', 'es', 'ca'];

/* parsePath('/')                       → { view: 'home' }
 * parsePath('/en')                     → { lang: 'en', view: 'home' }
 * parsePath('/es/resorts/foo')         → { lang: 'es', view: 'detail', id: 'foo' }
 * parsePath('/resorts/foo')            → { view: 'detail', id: 'foo' }   (no lang prefix → default) */
function parsePath(pathname) {
  const parts = (pathname || '/').split('/').filter(Boolean);
  let lang = null;
  if (parts[0] && ROUTER_LANGS.includes(parts[0])) lang = parts.shift();
  if (parts.length === 0) return lang ? { lang, view: 'home' } : { view: 'home' };
  if (parts[0] === 'resorts' && parts[1]) {
    const id = decodeURIComponent(parts[1]);
    return lang ? { lang, view: 'detail', id } : { view: 'detail', id };
  }
  return lang ? { lang, view: 'home', unknown: true } : { view: 'home', unknown: true };
}

function useRoute() {
  const [route, setRoute] = _useState(() => parsePath(window.location.pathname));
  _useEffect(() => {
    const update = () => setRoute(parsePath(window.location.pathname));
    window.addEventListener('popstate', update);
    window.addEventListener('neu:navigate', update);
    return () => {
      window.removeEventListener('popstate', update);
      window.removeEventListener('neu:navigate', update);
    };
  }, []);
  return route;
}

function navigate(to) {
  if (window.location.pathname === to) return;
  window.history.pushState({}, '', to);
  window.dispatchEvent(new Event('neu:navigate'));
}

function replaceRoute(to) {
  window.history.replaceState({}, '', to);
  window.dispatchEvent(new Event('neu:navigate'));
}

Object.assign(window, { useRoute, navigate, replaceRoute });
