// router.jsx — Path-based router (history.pushState)

const { useState, useEffect, useCallback } = React;

function parsePath() {
  const p = window.location.pathname;
  if (!p || p === "/") return ["home"];
  return p.replace(/^\//, "").split("/").filter(Boolean);
}

function useRoute() {
  const [parts, setParts] = useState(parsePath());
  useEffect(() => {
    const handler = () => {
      setParts(parsePath());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("popstate", handler);
    return () => window.removeEventListener("popstate", handler);
  }, []);
  return parts;
}

// Programmatic navigation
function navigate(path) {
  history.pushState(null, "", path);
  window.dispatchEvent(new PopStateEvent("popstate"));
}

// Active route helper
function useIsActive() {
  const parts = useRoute();
  return useCallback(
    (path, exact = false) => {
      const targetParts = path.replace(/^\//, "").split("/").filter(Boolean);
      const cur = parts[0] === "home" && targetParts.length === 0 ? [] : parts;
      if (exact) {
        return cur.length === targetParts.length && cur.every((p, i) => p === targetParts[i]);
      }
      if (targetParts.length === 0) return cur.length === 0;
      return targetParts.every((p, i) => cur[i] === p);
    },
    [parts]
  );
}

// Link component
function Link({ to, className, style, onClick, children, ...rest }) {
  const handle = (e) => {
    e.preventDefault();
    navigate(to);
    if (onClick) onClick(e);
  };
  return (
    <a href={to} className={className} style={style} onClick={handle} {...rest}>
      {children}
    </a>
  );
}

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