/* DMS app-state provider — single source (used by boot.jsx and the directions canvas).
   Logic identical to state/app.tsx; initialPersonId/initialView are optional and default
   to the original behavior (P02 / lobby), so the running app is unchanged. */
(function () {
  const DMS = window.DMS;
  const { PERSONS, AUDIT_SEED } = DMS;

  const AppCtx = React.createContext(null);
  window.useApp = () => {
    const c = React.useContext(AppCtx);
    if (!c) throw new Error('useApp must be used within AppProvider');
    return c;
  };

  let auditCounter = AUDIT_SEED.length;

  function AppProvider({ children, initialPersonId = 'P02', initialView = { name: 'lobby' } }) {
    const [personId, setPersonId] = React.useState(initialPersonId);
    const [audit, setAudit] = React.useState(AUDIT_SEED);
    const [stepUp, setStepUp] = React.useState(new Set());
    const [history, setHistory] = React.useState([initialView]);
    const person = PERSONS.find((p) => p.id === personId);

    const value = React.useMemo(() => {
      const go = (v) => setHistory((h) => [...h, v]);
      const back = () => setHistory((h) => (h.length > 1 ? h.slice(0, -1) : h));
      return {
        person,
        persons: PERSONS,
        setPersonId: (id) => { setPersonId(id); setStepUp(new Set()); setHistory([{ name: 'lobby' }]); },
        audit,
        logAccess: (o, verb, result, reason, step) => {
          auditCounter += 1;
          const entry = { id: `A-${String(auditCounter).padStart(3, '0')}`, ts: new Date().toISOString(), subjectId: person.id, objectId: o.id, verb, result, reason, step };
          setAudit((a) => [entry, ...a]);
        },
        stepUp,
        confirmStepUp: (recordId) => setStepUp((s) => new Set(s).add(recordId)),
        view: history[history.length - 1],
        go, back, canBack: history.length > 1,
      };
    }, [person, audit, stepUp, history]);

    return <AppCtx.Provider value={value}>{children}</AppCtx.Provider>;
  }

  window.AppProvider = AppProvider;
})();
