/* ==========================================================================
   BookStore - Hash-Based Router System
   Provides React Context + hooks for client-side routing without dependencies
   ========================================================================== */
(function () {
  const { createContext, useContext, useState, useEffect, useCallback, useMemo } = React;

  /* ── Route matching utility ─────────────────────────────────────────── */
  function matchRoute(pattern, path) {
    const patternParts = pattern.split('/').filter(Boolean);
    const pathParts = path.split('/').filter(Boolean);

    if (patternParts.length !== pathParts.length) return null;

    const params = {};
    for (let i = 0; i < patternParts.length; i++) {
      if (patternParts[i].startsWith(':')) {
        params[patternParts[i].slice(1)] = decodeURIComponent(pathParts[i]);
      } else if (patternParts[i] !== pathParts[i]) {
        return null;
      }
    }
    return params;
  }

  /* ── Router Context ─────────────────────────────────────────────────── */
  const RouterContext = createContext(null);

  function useRouter() {
    const ctx = useContext(RouterContext);
    if (!ctx) throw new Error('useRouter must be used within <RouterProvider>');
    return ctx;
  }

  /* ── Router Provider ────────────────────────────────────────────────── */
  function RouterProvider({ children }) {
    const [currentPath, setCurrentPath] = useState(() => {
      return window.location.hash.slice(1) || '/';
    });

    useEffect(() => {
      const onHashChange = () => {
        const newPath = window.location.hash.slice(1) || '/';
        setCurrentPath(newPath);
        window.scrollTo({ top: 0, behavior: 'smooth' });
      };
      window.addEventListener('hashchange', onHashChange);
      return () => window.removeEventListener('hashchange', onHashChange);
    }, []);

    const navigate = useCallback((path) => {
      window.location.hash = path;
    }, []);

    const value = useMemo(() => ({
      currentPath,
      navigate,
      isActive: (path) => currentPath === path,
      startsWith: (prefix) => currentPath.startsWith(prefix),
      match: (pattern) => matchRoute(pattern, currentPath),
    }), [currentPath, navigate]);

    return (
      <RouterContext.Provider value={value}>
        {children}
      </RouterContext.Provider>
    );
  }

  /* ── Link Component ─────────────────────────────────────────────────── */
  function Link({ to, className, activeClass, children, onClick }) {
    const { currentPath, navigate } = useRouter();
    const isActive = currentPath === to;

    const handleClick = (e) => {
      e.preventDefault();
      if (onClick) onClick(e);
      navigate(to);
    };

    return (
      <a
        href={`#${to}`}
        className={`${className || ''} ${isActive && activeClass ? activeClass : ''}`}
        onClick={handleClick}
      >
        {children}
      </a>
    );
  }

  /* ── Export to global scope ─────────────────────────────────────────── */
  window.RouterContext = RouterContext;
  window.RouterProvider = RouterProvider;
  window.useRouter = useRouter;
  window.matchRoute = matchRoute;
  window.Link = Link;
})();
