// Small History API router for the no-build frontend.
(function() {
  const VIEW_TO_PATH = {
    home: '/',
    chat: '/chat',
    saved: '/saved',
    calendar: '/calendar',
    profile: '/profile',
  };

  const PATH_TO_VIEW = Object.fromEntries(
    Object.entries(VIEW_TO_PATH).map(([view, path]) => [path, view])
  );

  function normalizePath(pathname) {
    if (!pathname || pathname === '/') return '/';
    const withoutTrailing = pathname.replace(/\/+$/, '');
    return withoutTrailing || '/';
  }

  function pathToView(pathname = window.location.pathname) {
    return PATH_TO_VIEW[normalizePath(pathname)] || null;
  }

  function viewToPath(view) {
    return VIEW_TO_PATH[view] || '/';
  }

  function currentView() {
    return pathToView(window.location.pathname) || 'home';
  }

  function notify(view) {
    window.dispatchEvent(new CustomEvent('snatch:route', { detail: { view } }));
  }

  function navigate(view, { replace = false } = {}) {
    const nextView = VIEW_TO_PATH[view] ? view : 'home';
    const path = viewToPath(nextView);
    const samePath = normalizePath(window.location.pathname) === path;

    if (!samePath || replace) {
      const method = replace ? 'replaceState' : 'pushState';
      window.history[method]({ view: nextView }, '', path);
    }

    notify(nextView);
    return nextView;
  }

  function normalizeCurrentPath() {
    const view = pathToView(window.location.pathname);
    if (view) return view;

    const suffix = window.location.search + window.location.hash;
    window.history.replaceState({ view: 'home' }, '', '/' + suffix);
    return 'home';
  }

  window.SnatchRouter = {
    pathToView,
    viewToPath,
    currentView,
    navigate,
    normalizeCurrentPath,
  };
})();
