/* router.js — hash router จิ๋ว (ไม่มี build step, ใช้ได้กับ static hosting ทุกแบบ) */ const listeners = new Set(); let routes = {}; let fallback = null; let currentPath = null; export function defineRoutes(map, fallbackRoute) { routes = map; fallback = fallbackRoute || Object.keys(map)[0]; } export function currentRoute() { return parseHash(); } function parseHash() { const raw = window.location.hash.replace(/^#/, ""); const path = raw.split("?")[0] || "/"; const query = new URLSearchParams(raw.split("?")[1] || ""); return { path: path.startsWith("/") ? path : `/${path}`, query }; } export function navigate(path) { if (window.location.hash === `#${path}`) { handleRoute(true); return; } window.location.hash = `#${path}`; } export function onRouteChange(callback) { listeners.add(callback); return () => listeners.delete(callback); } function handleRoute(force = false) { const route = parseHash(); const key = route.path; const resolved = routes[key] ? key : fallback; if (!routes[resolved]) return; if (!force && currentPath === resolved) return; currentPath = resolved; const view = routes[resolved]; listeners.forEach((fn) => fn({ ...route, path: resolved, view })); } export function startRouter() { window.addEventListener("hashchange", () => handleRoute()); if (!window.location.hash) { window.location.replace("#/"); } handleRoute(true); } export function markActiveNav(path) { document.querySelectorAll("[data-nav]").forEach((link) => { const target = link.getAttribute("data-nav"); const isHome = path === "/" && (target === "home" || target === "home-link"); const isAdmin = path === "/admin" && target.startsWith("admin"); if (isHome || isAdmin) link.setAttribute("aria-current", "page"); else link.removeAttribute("aria-current"); }); }