/**
 * 247ChatMate — Intent Gate (LOCKED v1.1 + RESET v1.2)
 * --------------------------------------------------
 * JOB E — CTA Permission + Intent Emission
 *
 * • Sole authority to emit `matewa:intentReady`
 * • Observes readiness signals (read-only)
 * • Listens to CTA selection event (clean wiring)
 * • Emits ONCE, then retires
 *
 * ❌ No UI mutation
 * ❌ No scroll
 * ❌ No routing
 */

(function () {
  'use strict';

  document.addEventListener('DOMContentLoaded', function () {

    const widget = document.getElementById('matewa-widget');
    if (!widget) return;

    let intentEmitted = false;
    let selectedMethod = null;

    // Readiness flags (observed only)
    let chipsReady = false;
    let phoneReady = false;
    let notesReady = true; // notes optional by default

    /* =====================================================
       READINESS OBSERVERS
    ===================================================== */

    widget.addEventListener('matewa:chips-complete', () => {
      chipsReady = true;
    });

    widget.addEventListener('matewa:phone-complete', () => {
      phoneReady = true;
    });

    widget.addEventListener('matewa:notes-required', () => {
      notesReady = false;
    });

    widget.addEventListener('matewa:notes-complete', () => {
      notesReady = true;
    });

    /* =====================================================
       CTA SELECTION LISTENER (CLEAN EVENT-BASED)
    ===================================================== */

    widget.addEventListener('matewa:cta-selected', function (e) {

      if (intentEmitted) return;

      selectedMethod = e.detail?.method || null;

      if (!isReady()) {
        widget.dispatchEvent(new CustomEvent('matewa:intent-blocked'));
        return;
      }

      emitIntent();
    });

    /* =====================================================
       GATE LOGIC
    ===================================================== */

    function isReady() {
      return chipsReady && phoneReady && notesReady;
    }

    function emitIntent() {
      if (intentEmitted) return;
      intentEmitted = true;

      widget.dispatchEvent(new CustomEvent('matewa:intentReady', {
        detail: {
          method: selectedMethod || 'unknown'
        }
      }));
    }

    /* =====================================================
       🔒 STEP 1B — Lifecycle Reset
    ===================================================== */

    widget.addEventListener('matewa:reset', function () {
      intentEmitted = false;
      selectedMethod = null;
      chipsReady = false;
      phoneReady = false;
      notesReady = true;
    });

  });

})();