// STATE — booking flow, tweaks, tracking hooks
// Uses React context so every variation shares the same booking engine.

const { createContext, useContext, useState, useEffect, useRef, useMemo, useCallback } = React;

const AppContext = createContext(null);

function useApp() { return useContext(AppContext); }

function AppProvider({ children }) {
  const initialTweaks = window.__TWEAKS || {};
  const [tweaks, setTweaks] = useState({
    variation: initialTweaks.variation || 'v1',
    surface: initialTweaks.surface || 'light',
    formMode: initialTweaks.formMode || 'one-step',
    videoMode: initialTweaks.videoMode || 'caption-autoplay',
    scarcity: initialTweaks.scarcity || 'stacked',
    referral: initialTweaks.referral || 'prominent',
    headline: initialTweaks.headline || 'I-have-to-see',
    guarantee: initialTweaks.guarantee || 'stamp',
    formStyle: initialTweaks.formStyle || 'magnet',
    bookingStyle: initialTweaks.bookingStyle || 'classic',
    ticketStyle: initialTweaks.ticketStyle || 'classic',
    stadiumStyle: initialTweaks.stadiumStyle || 'classic',
    stadiumBoxes: initialTweaks.stadiumBoxes || 'on',
    vipBoxCount: initialTweaks.vipBoxCount || '10',
    vipBoxesFull: initialTweaks.vipBoxesFull || 'mostly',
    vipBoxSizer: initialTweaks.vipBoxSizer || 'slider',
    boxLabels: initialTweaks.boxLabels || 'on',
    standardUpsell: initialTweaks.standardUpsell || 'three',
    vipEscape: initialTweaks.vipEscape || 'on',
    seatLegend: initialTweaks.seatLegend || 'cards',
    boxPosition: initialTweaks.boxPosition || 'above',
    vipTheme: initialTweaks.vipTheme || 'onbrand',    invitePreview: initialTweaks.invitePreview || 'boarding',
    vipBoxDesign: initialTweaks.vipBoxDesign || 'suite',
    proofStyle: initialTweaks.proofStyle || 'chip',
  });

  // Booking state — same shape as v3 so GHL wiring can drop in
  const [booking, setBooking] = useState({
    step: 'landing',        // landing | time | confirm
    firstName: '',
    lastName: '',
    phone: '',
    email: '',
    day: 0,
    dayDate: null,
    time: '',
    iso: '',
    cid: null,
  });
  const updateBooking = useCallback((patch) => setBooking(b => ({ ...b, ...patch })), []);

  // Ambassador taken count — animates up slowly so it feels alive
  const [taken, setTaken] = useState(BRAND.ambassadorTaken);
  useEffect(() => {
    const id = setInterval(() => {
      setTaken(t => {
        if (t >= BRAND.ambassadorCap - 20) return t;
        if (Math.random() < 0.35) return t + 1;
        return t;
      });
    }, 9000);
    return () => clearInterval(id);
  }, []);

  // Next-session countdown — cycles through 12/14/16/18 PT like v3
  const [countdown, setCountdown] = useState('—');
  useEffect(() => {
    function nowPT() { const n = new Date(); return new Date(n.getTime() + n.getTimezoneOffset()*60000 - 7*3600000); }
    function nextDate() {
      const pt = nowPT();
      const hours = [12,14,16,18];
      for (const h of hours) {
        if (pt.getHours() < h) return new Date(pt.getFullYear(), pt.getMonth(), pt.getDate(), h, 0, 0);
      }
      return new Date(pt.getFullYear(), pt.getMonth(), pt.getDate() + 1, 12, 0, 0);
    }
    function tick() {
      const diff = Math.max(0, nextDate() - nowPT());
      const h = Math.floor(diff/3600000);
      const m = Math.floor((diff%3600000)/60000);
      const s = Math.floor((diff%60000)/1000);
      setCountdown(h > 0 ? `${h}h ${m}m` : `${m}m ${String(s).padStart(2,'0')}s`);
    }
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);

  // Days-until-deadline countdown for Brand Ambassador rate
  const [daysLeft, setDaysLeft] = useState(0);
  useEffect(() => {
    const cutoff = new Date(BRAND.dealCutoffISO);
    const tick = () => {
      const d = Math.max(0, Math.ceil((cutoff - new Date()) / 86400000));
      setDaysLeft(d);
    };
    tick();
    const id = setInterval(tick, 60000);
    return () => clearInterval(id);
  }, []);

  // Toast stream — only when on landing
  const [toasts, setToasts] = useState([]);
  useEffect(() => {
    if (booking.step !== 'landing') { setToasts([]); return; }
    let cancelled = false;
    function add() {
      if (cancelled) return;
      const p = TOAST_PEOPLE[Math.floor(Math.random()*TOAST_PEOPLE.length)];
      const a = TOAST_ACTIONS[Math.floor(Math.random()*TOAST_ACTIONS.length)];
      const id = Date.now() + Math.random();
      setToasts(prev => [...prev.slice(-2), { id, p, a, ago: ['just now','1 min ago','2 min ago'][Math.floor(Math.random()*3)] }]);
      setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 5200);
    }
    const first = setTimeout(add, 9000);
    const loop = setInterval(add, 22000);
    return () => { cancelled = true; clearTimeout(first); clearInterval(loop); };
  }, [booking.step]);

  // Persist tweaks to disk via host postMessage (so refresh keeps them)
  const persistTweaks = useCallback((patch) => {
    setTweaks(prev => {
      const next = { ...prev, ...patch };
      try {
        window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
      } catch(e) {}
      return next;
    });
  }, []);

  // Surface (CSS vars) — re-applied whenever surface changes
  useEffect(() => {
    const s = SURFACES[tweaks.surface] || SURFACES.light;
    const r = document.documentElement.style;
    r.setProperty('--bg', s.bg);
    r.setProperty('--card', s.card);
    r.setProperty('--ink', s.ink);
    r.setProperty('--mute', s.mute);
    r.setProperty('--dim', s.dim);
    r.setProperty('--border', s.border);
    r.setProperty('--border-strong', s.borderStrong);
    r.setProperty('--shadow', s.shadow);
    r.setProperty('--shadow-lg', s.shadowLg);
    r.setProperty('--glow', s.glow);
    r.setProperty('--hero-bg', s.heroBg);
    r.setProperty('--break-bg', s.breakBg);
    r.setProperty('--gradient', BRAND.gradient);
    r.setProperty('--gradient-soft', BRAND.gradientSoft);
    r.setProperty('--purple', BRAND.purple);
    r.setProperty('--indigo', BRAND.indigo);
    r.setProperty('--blue', BRAND.blue);
    document.body.style.background = s.bg;
    document.body.style.color = s.ink;
  }, [tweaks.surface]);

  const value = {
    tweaks, setTweaks: persistTweaks,
    booking, updateBooking,
    taken, countdown, daysLeft,
    toasts,
  };

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

Object.assign(window, { AppContext, AppProvider, useApp });
