// Hash-free path routing using HTML5 History API.
// Exposes window.useRoute() and window.navigate() so components can use them
// without prop drilling.

const PATHS = {
  parse(pathname) {
    const segs = pathname.replace(/^\/+|\/+$/g, '').split('/').filter(Boolean);
    if (segs.length === 0) return { route: 'home', slug: null };
    const [first, second] = segs;
    if (first === 'blog') {
      return second ? { route: 'post', slug: second } : { route: 'blog', slug: null };
    }
    if (first === 'about' || first === 'uses' || first === 'connect' || first === 'links') {
      return { route: first, slug: null };
    }
    return { route: 'notfound', slug: pathname };
  },
  build(target) {
    if (typeof target === 'string') return target;
    const { route, slug } = target;
    if (route === 'home') return '/';
    if (route === 'blog') return '/blog';
    if (route === 'post') return `/blog/${slug}`;
    if (route === 'notfound') return slug || '/404';
    return `/${route}`;
  },
};

const useRoute = () => {
  const [state, setState] = React.useState(() => PATHS.parse(window.location.pathname));
  React.useEffect(() => {
    const onPop = () => setState(PATHS.parse(window.location.pathname));
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);
  return state;
};

const navigate = (target, opts = {}) => {
  const path = PATHS.build(target);
  if (window.location.pathname === path && !opts.force) return;
  window.history[opts.replace ? 'replaceState' : 'pushState'](null, '', path);
  window.dispatchEvent(new PopStateEvent('popstate'));
};

window.useRoute = useRoute;
window.navigate = navigate;
window.RouterPaths = PATHS;
