/* Tidewell — tiny hash router */

const { useState, useEffect, useCallback } = React;

function parseHash() {
  const h = (window.location.hash || "#/").replace(/^#/, "");
  // route looks like /, /products, /products/:slug, /about, /applications, /contact
  const parts = h.split("/").filter(Boolean);
  if (parts.length === 0) return { name: "home" };
  if (parts[0] === "products") {
    if (parts.length === 1) return { name: "catalog" };
    return { name: "product", slug: parts[1] };
  }
  if (parts[0] === "applications") return { name: "applications" };
  if (parts[0] === "about") return { name: "about" };
  if (parts[0] === "contact") return { name: "contact" };
  return { name: "home" };
}

function useRoute() {
  const [route, setRoute] = useState(parseHash());
  useEffect(() => {
    const onHash = () => {
      setRoute(parseHash());
      // Scroll to top on route change, unless an in-page hash was supplied
      // (route name only — no extra ID). All our routes here are pure.
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}

function navigate(path) {
  window.location.hash = "#" + path;
}

function Link({ to, children, className, onClick, ...rest }) {
  return (
    <a
      href={"#" + to}
      className={className}
      onClick={(e) => {
        if (onClick) onClick(e);
      }}
      {...rest}
    >
      {children}
    </a>
  );
}

window.useRoute = useRoute;
window.navigate = navigate;
window.Link = Link;
