import { useState, useEffect } from "react";

/**
 * Einfaches Hash-basiertes Routing System
 * Verwendet URL Hash (#/path) für Navigation ohne Page Reload
 */

export function useHashRoute() {
  const [route, setRoute] = useState(() => {
    // Initial route aus Hash extrahieren
    const hash = window.location.hash.slice(1) || "/";
    return hash.startsWith("/") ? hash : `/${hash}`;
  });

  useEffect(() => {
    const handleHashChange = () => {
      const hash = window.location.hash.slice(1) || "/";
      const newRoute = hash.startsWith("/") ? hash : `/${hash}`;
      setRoute(newRoute);
    };

    // Event Listener für Hash-Änderungen
    window.addEventListener("hashchange", handleHashChange);

    // Initial check
    handleHashChange();

    return () => {
      window.removeEventListener("hashchange", handleHashChange);
    };
  }, []);

  const navigate = (path) => {
    const newPath = path.startsWith("/") ? path : `/${path}`;
    window.location.hash = newPath;
  };

  return { route, navigate };
}