/**
 * 247ChatMate — CTA Controller (MODE-AWARE PRESENTER)
 * ---------------------------------------------------
 * Pure presenter. No flow mutation.
 * Emits selection state only.
 *
 * Free: Chat now only
 * Trial / Pro / Master: Chat now + Chat later
 */

(function () {
  'use strict';

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

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

    const cta = widget.querySelector('.matewa-cta');
    if (!cta) return;

    let locked = false;
    let isResetting = false;

    const CONFIRM_DELAY = 450;
    const MICRO_DELAY = 120;

    /* ============================================
       Mode helpers
    ============================================ */

    function getMode() {
      const fromWidgetData =
        widget.getAttribute('data-mode') ||
        widget.dataset.mode ||
        '';

      const fromDocData =
        document.documentElement.getAttribute('data-matewa-mode') ||
        document.body?.getAttribute('data-matewa-mode') ||
        '';

      const fromConfig =
        (window.MATEWA_SETTINGS && window.MATEWA_SETTINGS.mode) ||
        (window.MATEWA_CONFIG && window.MATEWA_CONFIG.mode) ||
        (window.matewaConfig && window.matewaConfig.mode) ||
        (window.MATEWA && window.MATEWA.mode) ||
        '';

      const mode = String(fromWidgetData || fromDocData || fromConfig || 'free').toLowerCase().trim();

      return mode || 'free';
    }

    function hasExtendedCTA() {
      const mode = getMode();
      return mode === 'trial_active' || mode === 'pro' || mode === 'master';
    }

    /* ============================================
       Render CTA
    ============================================ */

    function renderCTA() {

      const extendedCTA = hasExtendedCTA();

      cta.innerHTML = `
        <div class="matewa-bubble matewa-cta-prompt">
          Ready to continue on WhatsApp?
        </div>

        <div class="matewa-chip-group matewa-chip-group--cta">
          <button type="button"
            class="matewa-chip matewa-cta-chip"
            data-cta="now"
            aria-label="Chat now on WhatsApp"
            aria-pressed="false">
            <span class="matewa-cta-whatsapp" aria-hidden="true"></span>
            <span class="matewa-cta-copy">
              <strong>Chat now</strong>
            </span>
          </button>

          ${extendedCTA ? `
          <button type="button"
            class="matewa-chip matewa-cta-chip"
            data-cta="later"
            aria-label="Chat later on WhatsApp"
            aria-pressed="false">
            <span class="matewa-cta-whatsapp" aria-hidden="true"></span>
            <span class="matewa-cta-copy">
              <strong>Chat later</strong>
            </span>
          </button>
          ` : ''}
        </div>
      `;

      bindChips();
    }

    function getActiveRail() {
      return 'WhatsApp';
    }

    function buildConfirmationCopy(rail, method) {
      if (method === 'later') {
        return `
          Your message is ready in ${rail}.<br>
          You can continue the conversation there when you're ready.
        `;
      }

      return `
        Your message is ready in ${rail}.<br>
        We’ll continue the conversation there.
      `;
    }

    /* ============================================
       Bind CTA Chips
    ============================================ */

    function bindChips() {

      const chips = cta.querySelectorAll('.matewa-cta-chip');

      chips.forEach(chip => {
        chip.addEventListener('click', function () {

          if (locked) return;
          locked = true;

          const method = chip.dataset.cta || 'now';
          const detail = { method };

          widget.dispatchEvent(new CustomEvent('matewa:cta-selected', {
            detail
          }));

          setTimeout(() => {
            chips.forEach(c => {
              c.classList.remove('is-selected');
              c.setAttribute('aria-pressed', 'false');
            });
            chip.classList.add('is-selected');
            chip.setAttribute('aria-pressed', 'true');
          }, MICRO_DELAY);

          setTimeout(() => {

            const rail = getActiveRail();

            cta.innerHTML = `
              <div class="matewa-bubble matewa-cta-confirm">
                ${buildConfirmationCopy(rail, method)}
              </div>
            `;

          }, CONFIRM_DELAY);

        });
      });
    }

    /* ============================================
       Visibility logic
    ============================================ */

    function updateCTAVisibility() {

      const isContactActive =
        widget.querySelector('.matewa-contact.is-active');

      const shouldBeActive = !!isContactActive;
      const isActive = cta.classList.contains('is-active');

      if (shouldBeActive && !isActive) {
        locked = false;
      }

      cta.setAttribute('aria-hidden', shouldBeActive ? 'false' : 'true');

      if (!isResetting && shouldBeActive !== isActive) {
        cta.classList.toggle('is-active', shouldBeActive);
      }
    }

    const observer = new MutationObserver(updateCTAVisibility);

    observer.observe(widget, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['class']
    });

    updateCTAVisibility();

    /* ============================================
       Reset On Close
    ============================================ */

    function resetCTAState() {

      isResetting = true;
      locked = false;

      renderCTA();

      setTimeout(() => {
        isResetting = false;
      }, 0);
    }

    widget.addEventListener('matewa:reset', resetCTAState);

    const closeBtn = widget.querySelector('.matewa-close');
    if (closeBtn) {
      closeBtn.addEventListener('click', resetCTAState);
    }

    renderCTA();

  });

})();