// Tiny in-app router for connected prototypes.
// Exposes <Router>, useNav() hook, and a NavContext.

const NavContext = React.createContext(null);

function useNav() {
  return React.useContext(NavContext);
}

function Router({ initial, initialState = {}, routes, theme, lang, fallback = null }) {
  const [stack, setStack] = React.useState([initial]);
  const [state, setState] = React.useState(initialState);

  const route = stack[stack.length - 1];

  const api = React.useMemo(() => ({
    route,
    state,
    nav: (to, patch) => {
      setStack(s => [...s, to]);
      if (patch) setState(st => ({ ...st, ...patch }));
    },
    back: () => setStack(s => s.length > 1 ? s.slice(0, -1) : s),
    reset: (to, patch) => {
      setStack([to || initial]);
      if (patch) setState(st => ({ ...st, ...patch }));
    },
    set: (patch) => setState(st => ({ ...st, ...patch })),
  }), [route, state, initial]);

  const Comp = routes[route] || routes[initial];
  return (
    <NavContext.Provider value={api}>
      {Comp ? <Comp theme={theme} lang={lang} {...state}/> : fallback}
    </NavContext.Provider>
  );
}

Object.assign(window, { NavContext, useNav, Router });
