/**
 * 247ChatMate — Intro Controller (LOCKED v1.1 — MIN FIX)
 * --------------------------------------------------
 * • Plays intro bubbles once on widget open
 * • Removes intro after completion
 * • Reveals Task 1 (intent)
 * • NO chip handling
 * • NO scroll ownership
 */

(function () {
  'use strict';

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

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

    const T = window.MATEWA_TEMPO || {};

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

    const introBubbles = Array.from(
      intro.querySelectorAll('.matewa-bubble')
    );

    const intentTask = widget.querySelector('[data-task="intent"]');

    const INTRO_STEP = T.INTRO_STEP || 1750;
    const INTRO_POST_DELAY = T.INTRO_POST_DELAY || 300;

    let played = false;

    function playIntro() {
      if (played) return;
      played = true;

      introBubbles.forEach((bubble, i) => {
        setTimeout(() => {
          bubble.classList.add('is-visible');
        }, i * INTRO_STEP);
      });

      setTimeout(() => {
        // 🔒 Remove intro completely (no spacing left)
        intro.remove();

        // 🔒 Reveal Task 1 (bubble + chips)
        if (intentTask) {
          intentTask.hidden = false;
        }
      }, introBubbles.length * INTRO_STEP + INTRO_POST_DELAY);
    }

    new MutationObserver(() => {
      if (widget.classList.contains('is-open')) {
        playIntro();
      }
    }).observe(widget, {
      attributes: true,
      attributeFilter: ['class']
    });

    // Safety: if widget is already open
    if (widget.classList.contains('is-open')) {
      playIntro();
    }
  }
})();
