// Navigation context for the interactive app
// Provides useNav() = { go(screen), back(), screen, history }

const NavCtx = React.createContext({ go: () => {}, back: () => {}, screen: 'home', history: [] });
window.NavCtx = NavCtx;

function NavProvider({ initial = 'home', children }) {
  const [history, setHistory] = React.useState([initial]);
  const screen = history[history.length - 1];
  const go = React.useCallback((s) => {
    setHistory(h => h[h.length - 1] === s ? h : [...h, s]);
  }, []);
  const back = React.useCallback(() => {
    setHistory(h => h.length > 1 ? h.slice(0, -1) : h);
  }, []);
  const reset = React.useCallback((s) => setHistory([s]), []);
  return <NavCtx.Provider value={{ go, back, reset, screen, history }}>{children}</NavCtx.Provider>;
}

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

window.NavProvider = NavProvider;
window.useNav = useNav;
