/**
 * 247ChatMate — Launcher Controller (LOCKED v2.4 + RESET v2.4.1)
 * --------------------------------------------------
 * Sole owner of widget open / close state
 * DOM-resilient
 * SINGLE VISIBILITY AXIS: .is-open
 * BODY SCROLL LOCK INCLUDED
 *
 * v2.4.1:
 * • Emits authoritative `matewa:reset` on close
 *
 * PASS 2 — MIN FIX ONLY
 * • Adds one-time deferred interaction loader
 * • No behavioural change while deep scripts still enqueue up front
 *
 * Phase 5-A-22A:
 * • Adds safe auto-open trigger:
 *   - after 8 seconds OR 33% scroll
 *   - never before 4 seconds
 *   - once per session
 *   - suppressed after manual open or close
 */

(function () {
  'use strict';

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  function init() {
    const launcher = document.getElementById('matewa-launcher');
    if (!launcher) return;

    const OPEN_CLASS = 'is-open';
    const AUTO_SESSION_KEY = 'matewa_auto_open_suppressed_v1';
    const AUTO_MIN_DELAY_MS = 4000;
    const AUTO_TIME_DELAY_MS = 8000;
    const AUTO_SCROLL_DEPTH = 0.33;
    const AUTO_SCROLL_MIN_PIXELS = 120;

    let scrollY = 0;
    let deferredReady = false;
    let deferredPromise = null;
    let autoMinReady = false;
    let autoTimeReady = false;
    let autoScrollReady = false;
    let autoOpened = false;
    let manualOpened = false;
    let autoStopped = false;
    let autoMinTimer = null;
    let autoTimeTimer = null;

    function getWidget() {
      return document.getElementById('matewa-widget');
    }

    function lockBodyScroll() {
      scrollY = window.scrollY || window.pageYOffset || 0;
      document.body.style.position = 'fixed';
      document.body.style.top = `-${scrollY}px`;
      document.body.style.left = '0';
      document.body.style.right = '0';
      document.body.style.width = '100%';
    }

    function unlockBodyScroll() {
      document.body.style.position = '';
      document.body.style.top = '';
      document.body.style.left = '';
      document.body.style.right = '';
      document.body.style.width = '';
      window.scrollTo(0, scrollY);
    }

    function safeSessionGet(key) {
      try {
        return window.sessionStorage ? window.sessionStorage.getItem(key) : null;
      } catch (err) {
        return null;
      }
    }

    function safeSessionSet(key, value) {
      try {
        if (window.sessionStorage) {
          window.sessionStorage.setItem(key, value);
        }
      } catch (err) {
        // Storage can be blocked in private modes; in-memory flags still protect the session.
      }
    }

    function hasInteractionLayer() {
      return !!(
        window.MATEWA_TEMPO &&
        typeof window.__matewaInitFlow === 'function'
      );
    }

    function loadScriptOnce(src) {
      return new Promise((resolve, reject) => {
        if (!src) {
          resolve();
          return;
        }

        const existing = document.querySelector(`script[src="${src}"]`);
        if (existing) {
          if (existing.dataset.matewaLoaded === '1') {
            resolve();
            return;
          }

          existing.addEventListener('load', () => resolve(), { once: true });
          existing.addEventListener('error', () => reject(new Error(`Failed to load ${src}`)), { once: true });
          return;
        }

        const script = document.createElement('script');
        script.src = src;
        script.async = false;

        script.addEventListener('load', () => {
          script.dataset.matewaLoaded = '1';
          resolve();
        }, { once: true });

        script.addEventListener('error', () => {
          reject(new Error(`Failed to load ${src}`));
        }, { once: true });

        document.body.appendChild(script);
      });
    }

    function ensureDeferredInteractionLayer() {
      if (deferredReady || hasInteractionLayer()) {
        deferredReady = true;
        return Promise.resolve();
      }

      if (deferredPromise) {
        return deferredPromise;
      }

      const map = window.MATEWA_DEFERRED && window.MATEWA_DEFERRED.scripts
        ? window.MATEWA_DEFERRED.scripts
        : null;

      if (!map) {
        deferredReady = true;
        return Promise.resolve();
      }

      deferredPromise = Promise.resolve()
        .then(() => loadScriptOnce(map.tempo))
        .then(() => loadScriptOnce(map.intro))
        .then(() => loadScriptOnce(map.scroll))
        .then(() => loadScriptOnce(map.flow))
        .then(() => loadScriptOnce(map.intentGate))
        .then(() => loadScriptOnce(map.intentActions))
        .then(() => loadScriptOnce(map.cta))
        .then(() => {
          deferredReady = true;
        })
        .catch((err) => {
          console.error('247ChatMate deferred load failed:', err);
        });

      return deferredPromise;
    }

    function stopAutoOpenWatch() {
      autoStopped = true;

      if (autoMinTimer) {
        window.clearTimeout(autoMinTimer);
        autoMinTimer = null;
      }

      if (autoTimeTimer) {
        window.clearTimeout(autoTimeTimer);
        autoTimeTimer = null;
      }

      window.removeEventListener('scroll', handleAutoScroll, { passive: true });
      window.removeEventListener('resize', handleAutoScroll);
    }

    function isAutoSuppressed() {
      const widget = getWidget();

      return !!(
        autoStopped ||
        autoOpened ||
        manualOpened ||
        safeSessionGet(AUTO_SESSION_KEY) === '1' ||
        (widget && widget.classList && widget.classList.contains(OPEN_CLASS))
      );
    }

    function markAutoSuppressed() {
      safeSessionSet(AUTO_SESSION_KEY, '1');
    }

    function getScrollDepth() {
      const doc = document.documentElement;
      const body = document.body;

      const scrollTop = window.scrollY || window.pageYOffset || doc.scrollTop || body.scrollTop || 0;
      const scrollHeight = Math.max(
        body ? body.scrollHeight : 0,
        doc ? doc.scrollHeight : 0,
        body ? body.offsetHeight : 0,
        doc ? doc.offsetHeight : 0,
        body ? body.clientHeight : 0,
        doc ? doc.clientHeight : 0
      );

      const viewportHeight = window.innerHeight || (doc ? doc.clientHeight : 0) || 0;
      const maxScroll = Math.max(0, scrollHeight - viewportHeight);

      if (maxScroll < AUTO_SCROLL_MIN_PIXELS) {
        return 0;
      }

      return Math.min(1, Math.max(0, scrollTop / maxScroll));
    }

    function handleAutoScroll() {
      if (isAutoSuppressed() || autoScrollReady) return;

      if (getScrollDepth() >= AUTO_SCROLL_DEPTH) {
        autoScrollReady = true;
        tryAutoOpen('auto_scroll');
      }
    }

    function tryAutoOpen(source) {
      if (!autoMinReady || isAutoSuppressed()) return;
      if (!autoTimeReady && !autoScrollReady) return;

      openWidget(null, source || (autoScrollReady ? 'auto_scroll' : 'auto_time'));
    }

    function startAutoOpenWatch() {
      if (safeSessionGet(AUTO_SESSION_KEY) === '1') return;

      autoMinTimer = window.setTimeout(function () {
        autoMinReady = true;
        tryAutoOpen(autoScrollReady ? 'auto_scroll' : 'auto_time');
      }, AUTO_MIN_DELAY_MS);

      autoTimeTimer = window.setTimeout(function () {
        autoTimeReady = true;
        tryAutoOpen('auto_time');
      }, AUTO_TIME_DELAY_MS);

      window.addEventListener('scroll', handleAutoScroll, { passive: true });
      window.addEventListener('resize', handleAutoScroll);
    }

    function openWidget(e, source) {
      const openSource = source || 'launcher';

      if (e) {
        e.preventDefault();
        e.stopPropagation(); // 🔒 CRITICAL
        manualOpened = true;
        stopAutoOpenWatch();
      }

      const widget = getWidget();
      if (!widget) return;

      if (widget.classList.contains(OPEN_CLASS)) return;

      if (openSource.indexOf('auto_') === 0) {
        autoOpened = true;
        markAutoSuppressed();
        stopAutoOpenWatch();
      }

      ensureDeferredInteractionLayer().finally(() => {
        lockBodyScroll();

        widget.classList.add(OPEN_CLASS);
        widget.setAttribute('aria-hidden', 'false');
        document.body.classList.add('matewa-launcher-hidden');

        widget.dispatchEvent(new CustomEvent('matewa:opened', {
          detail: { source: openSource }
        }));
      });
    }

    function closeWidget() {
      const widget = getWidget();
      if (!widget) return;

      markAutoSuppressed();
      stopAutoOpenWatch();

      widget.classList.remove(OPEN_CLASS);
      widget.setAttribute('aria-hidden', 'true');
      document.body.classList.remove('matewa-launcher-hidden');

      unlockBodyScroll();

      // 🔒 STEP 1A — Authoritative lifecycle reset
      widget.dispatchEvent(new CustomEvent('matewa:reset'));
    }

    launcher.addEventListener('click', openWidget);

    // Delegate close safely (header × only)
    document.addEventListener('click', e => {
      const closeBtn = e.target.closest('.matewa-close');
      if (!closeBtn) return;

      e.preventDefault();
      e.stopPropagation();
      closeWidget();
    });

    startAutoOpenWatch();
  }
})();
