/* ========================================================================
   demo.jsx — Presenter controls (Story 8)
   The panel is for whoever is running the demo, never for a prospect: it
   renders only when the app was opened with ?presenter, and the unlock is
   remembered for that browser so it survives navigation mid-presentation.
   ======================================================================== */

/* Every store the prototype writes. Reset Demo clears the lot, so no preset
   can leave the estate in a state the next demo inherits. */
const DEMO_KEYS = [
  "mp_users_v1",             /* created, edited and deleted users, SIM attachments */
  "mp_estate_requests_v3",   /* SIM requests and status overrides */
  "mp_travel_plans_v1",      /* bought travel plans */
  "mp_batches_v1",           /* CSV batches */
  "mp_esim_install_v1",      /* install states and activation emails */
  "mp_sso_v1",               /* single sign-on connection and enforcement */
  "mp_support_tickets_v1",   /* support tickets */
  "mp_pool_name",            /* renamed data pool */
  "mp_estate_month_offset",  /* rolled usage month */
  "mp-sim-state"             /* per-SIM service and IMEI edits (one key per id) */
];

/* Presenter gating. No visible unlock of any kind: ?presenter in the URL is
   the only way in, and it is remembered afterwards. */
const PRESENTER_KEY = "mp_presenter";
function isPresenter() {
  try {
    const q = (location.search || "") + (location.hash || "");
    if (/[?&]presenter\b/.test(q)) { localStorage.setItem(PRESENTER_KEY, "1"); return true; }
    return localStorage.getItem(PRESENTER_KEY) === "1";
  } catch (e) { return /[?&]presenter\b/.test(location.search || ""); }
}

function resetDemo() {
  try {
    DEMO_KEYS.forEach((k) => localStorage.removeItem(k));
    /* Per-SIM keys are written one per id, so clear anything in that family. */
    Object.keys(localStorage).forEach((k) => { if (k.indexOf("mp-sim-state") === 0) localStorage.removeItem(k); });
  } catch (e) {}
  location.reload();
}

/* The panel is opened by the host's __activate_edit_mode message. On a plain
   deployment nothing sends it, so presenter mode sends it itself: one
   mechanism, so the panel cannot open one way in the tool and another way
   outside it. */
if (isPresenter()) {
  const activate = () => window.postMessage({ type: "__activate_edit_mode" }, "*");
  if (document.readyState === "complete") setTimeout(activate, 300);
  else window.addEventListener("load", () => setTimeout(activate, 300));
}

window.MP_DEMO = { isPresenter, resetDemo, DEMO_KEYS };
