/* Router.jsx — hash-based router + in-memory store + toast bus.
   Hash routing gives real browser history entries, so Back/Forward work for
   every screen and modal transition. Exposes globals used across the kit:
     window.navigate(path)      — push a new route (#/...)
     window.closeOverlay(fb)    — pop the current modal (history.back, else fallback)
     window.useRoute()          — hook returning { segments, path }
     window.PTStore / useStore  — re-render subscribers after data mutations
     window.pushToast / useToast— transient confirmation toasts
*/
const { useState, useEffect } = React;

function parseRoute() {
  const raw = (window.location.hash || "").replace(/^#\/?/, "");
  const segments = raw.length ? raw.split("/").filter(Boolean).map(decodeURIComponent) : [];
  return { segments, path: "/" + segments.join("/") };
}

function navigate(path, opts) {
  const clean = "#/" + String(path).replace(/^\/+/, "");
  if (opts && opts.replace) window.location.replace(clean);
  else window.location.hash = clean;
}

/* Close a modal: pop history so Back/close are symmetric; fall back to a base
   path when there's no history to pop (e.g. a deep link opened cold). */
function closeOverlay(fallback) {
  if (window.history.length > 1) window.history.back();
  else navigate(fallback || "/properties");
}

function useRoute() {
  const [route, setRoute] = useState(parseRoute());
  useEffect(() => {
    const on = () => setRoute(parseRoute());
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  return route;
}

/* Minimal pub/sub store. Mutations to window.PT_DATA call PTStore.bump() to
   re-render the app so added/edited records show up live. */
const PTStore = (function () {
  let listeners = [];
  return {
    bump() { listeners.slice().forEach((f) => f()); },
    subscribe(fn) { listeners.push(fn); return () => { listeners = listeners.filter((x) => x !== fn); }; },
  };
})();
function useStore() {
  const [, set] = useState(0);
  useEffect(() => PTStore.subscribe(() => set((n) => n + 1)), []);
}

const ToastBus = (function () {
  let listeners = [];
  return {
    push(t) { listeners.slice().forEach((f) => f(t)); },
    subscribe(fn) { listeners.push(fn); return () => { listeners = listeners.filter((x) => x !== fn); }; },
  };
})();
function pushToast(t) { ToastBus.push(t); }
function useToast() {
  const [toast, setToast] = useState(null);
  useEffect(() => ToastBus.subscribe((t) => setToast(t)), []);
  useEffect(() => {
    if (!toast) return;
    const id = setTimeout(() => setToast(null), 3400);
    return () => clearTimeout(id);
  }, [toast]);
  return [toast, setToast];
}

Object.assign(window, { navigate, closeOverlay, useRoute, PTStore, useStore, pushToast, useToast });
