/***
 * 247ChatMate — Flow Controller (BASELINE RESTORED)
 * --------------------------------------------------
 * Stable wizard lifecycle
 * - Fresh mount every init
 * - Tasks removed during progression
 * - Reset fully reboots flow
 *
 * FIX APPLIED:
 * - Reset listener registered ONCE in boot()
 * - Removed recursive listener from initFlow()
 * - Clears pending commit timer when "other" is selected
 * - Prevents progression when all chips are deselected
 * - Notes path commits directly after idle lock
 *
 * MIN TIMING POLISH:
 * - Contact name/email remain soft-confirm only
 * - Increased contact confirm delay to allow more natural typing
 * - Increased blur confirm delay to avoid instant soft-confirm feel
 *
 * MIN RECOVERY PASS:
 * - Gentle phone soft-check restored
 * - Gentle name/email soft-check restored
 * - Phone can be corrected after warning, then locks and proceeds
 */

(function () {
  'use strict';

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

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

    window.__matewaInitFlow = initFlow;

    function waitForOpenThenIntro(force) {
      if (widget.__matewaFlowStarted && !force) return;

      if (!window.MATEWA_LANGUAGE_READY) {
        widget.addEventListener('matewa:languageReady', function () {
          waitForOpenThenIntro(force);
        }, { once: true });
        return;
      }

      if (!widget.classList.contains('is-open')) {
        widget.addEventListener('matewa:opened', function () {
          waitForOpenThenIntro(force);
        }, { once: true });
        return;
      }

      if (widget.querySelector('.matewa-intro')) {
        widget.addEventListener('matewa:introComplete', function () {
          waitForOpenThenIntro(force);
        }, { once: true });
        return;
      }

      widget.__matewaFlowStarted = true;
      initFlow(widget);
    }

    widget.addEventListener('matewa:reset', function (evt) {
      var reason = evt && evt.detail ? evt.detail.reason : '';
      widget.__matewaFlowStarted = false;
      if (reason === 'languageHardResetComplete' || reason === 'languageChanged') {
        waitForOpenThenIntro(true);
        return;
      }
      if (typeof window.__matewaInitFlow === 'function') {
        window.__matewaInitFlow(widget);
      }
    });

    widget.addEventListener('matewa:languageReady', function () {
      waitForOpenThenIntro(false);
    });

    widget.addEventListener('matewa:introComplete', function () {
      waitForOpenThenIntro(false);
    });

    waitForOpenThenIntro(false);
  }

  function initFlow(widget) {

    function t(key, fallback) {
      if (typeof window.matewa_get_i18n_label === 'function') {
        return window.matewa_get_i18n_label(key) || fallback;
      }
      if (window.MATEWA_I18N && window.MATEWA_I18N[key]) {
        return window.MATEWA_I18N[key];
      }
      return fallback;
    }

    const T = window.MATEWA_TEMPO || {};
    const INTRO_PACE = T.INTRO_STEP || 1750;
    const INTENT_COMMIT_DELAY = INTRO_PACE * 1.6;
    const IDLE_LOCK_DELAY = 3000;
    const PHONE_CONFIRM_DELAY = 550;
    const PHONE_MIN_DIGITS = 10;

    const CONTACT_CONFIRM_DELAY = 1500;
    const CONTACT_BLUR_CONFIRM_DELAY = 450;

    const PHONE_SOFT_CHECK_DELAY = 650;
    const PHONE_BLUR_CONFIRM_DELAY = 450;

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

    // 🔒 Fresh mount every time
    stream.innerHTML = '';

    function mount(id) {
      const tpl = document.getElementById(id);
      if (!tpl) return null;
      const node = tpl.content.firstElementChild.cloneNode(true);
      node.style.opacity = '0';
      stream.appendChild(node);
      return node;
    }

    const intentTask  = mount('matewa-task-intent-template');
    const phoneTask   = mount('matewa-task-phone-template');
    const contactTask = mount('matewa-task-contact-template');
    const notesNode   = mount('matewa-task-notes-template');

    const chips = Array.from(intentTask.querySelectorAll('.matewa-chip'));
    const notesInput  = notesNode.querySelector('.matewa-notes-textarea');
    const charCounter = notesNode.querySelector('.matewa-char-counter');
    const phoneInput  = phoneTask.querySelector('.matewa-phone-input');
    const phoneHint   = phoneTask.querySelector('.matewa-char-counter');
    const phoneCountrySelect = phoneTask.querySelector('.matewa-phone-country');
    const phoneCountryPicker = phoneTask.querySelector('.matewa-phone-country-picker');
    const phoneCountryButton = phoneTask.querySelector('.matewa-phone-country-button');
    const phoneCountryMenu = phoneTask.querySelector('.matewa-phone-country-menu');

    const contactNameInput  = contactTask.querySelector('.matewa-contact-name');
    const contactEmailInput = contactTask.querySelector('.matewa-contact-email');
    const contactNameHint   = contactNameInput ? contactNameInput.nextElementSibling : null;
    const contactEmailHint  = contactEmailInput ? contactEmailInput.nextElementSibling : null;

    let selectedIntents = [];
    let committed = false;
    let currentTask = null;
    let commitTimer = null;
    let phoneIdleTimer = null;
    let phoneWarnTimer = null;
    let phoneBlurTimer = null;
    let notesIdleTimer = null;
    let contactNameIdleTimer = null;
    let contactEmailIdleTimer = null;
    let notesMemory = '';
    let phoneAdvanced = false;

    function normalize(v) {
      return (v || '').toLowerCase();
    }

    function getPhoneDigits(value) {
      return (value || '').replace(/\D/g, '');
    }


    const MATEWA_PHONE_FALLBACK_PACK = {
      defaultCountry: 'gb',
      defaultDialPrefix: '44',
      fallbackCountries: ['gb', 'au', 'us', 'ie', 'nz', 'ca'],
      countries: [
        { iso2: 'gb', name: 'United Kingdom', flag: '🇬🇧', countryCallingCode: '44', dialPrefix: '44', dialDisplay: '+44', nationalPrefix: '0', priority: 1, enabled: true },
        { iso2: 'au', name: 'Australia', flag: '🇦🇺', countryCallingCode: '61', dialPrefix: '61', dialDisplay: '+61', nationalPrefix: '0', priority: 2, enabled: true },
        { iso2: 'us', name: 'United States', flag: '🇺🇸', countryCallingCode: '1', dialPrefix: '1', dialDisplay: '+1', nationalPrefix: '', priority: 3, enabled: true },
        { iso2: 'ie', name: 'Ireland', flag: '🇮🇪', countryCallingCode: '353', dialPrefix: '353', dialDisplay: '+353', nationalPrefix: '0', priority: 4, enabled: true },
        { iso2: 'nz', name: 'New Zealand', flag: '🇳🇿', countryCallingCode: '64', dialPrefix: '64', dialDisplay: '+64', nationalPrefix: '0', priority: 5, enabled: true },
        { iso2: 'ca', name: 'Canada', flag: '🇨🇦', countryCallingCode: '1', dialPrefix: '1', dialDisplay: '+1', nationalPrefix: '', priority: 6, enabled: true }
      ]
    };

    let phoneCountryPack = null;
    let selectedPhoneCountry = null;
    let phoneCountryUserSelected = false;

    function getPhoneCountryConfig() {
      return window.MATEWA_PHONE_COUNTRIES && typeof window.MATEWA_PHONE_COUNTRIES === 'object'
        ? window.MATEWA_PHONE_COUNTRIES
        : {};
    }

    function isPhoneCountrySelectorVisible() {
      const config = getPhoneCountryConfig();
      return config.showSelector !== false && config.showSelector !== '0';
    }

    function fetchJsonWithTimeout(url, timeoutMs) {
      if (!url || !window.fetch) {
        return Promise.reject(new Error('fetch_unavailable'));
      }

      const controller = window.AbortController ? new AbortController() : null;
      const timer = controller ? window.setTimeout(function () {
        controller.abort();
      }, timeoutMs || 1800) : null;

      return window.fetch(url, {
        method: 'GET',
        credentials: 'omit',
        cache: 'force-cache',
        referrerPolicy: 'no-referrer',
        signal: controller ? controller.signal : undefined
      }).then(function (response) {
        if (timer) window.clearTimeout(timer);
        if (!response || !response.ok) {
          throw new Error('bad_response');
        }
        return response.json();
      }).catch(function (error) {
        if (timer) window.clearTimeout(timer);
        throw error;
      });
    }

    function validatePhonePack(pack) {
      if (!pack || typeof pack !== 'object' || !Array.isArray(pack.countries)) {
        return null;
      }

      const countries = pack.countries
        .filter(function (country) {
          return country && country.enabled !== false && country.iso2 && (country.countryCallingCode || country.dialPrefix);
        })
        .map(function (country) {
          const code = String(country.countryCallingCode || country.dialPrefix || '').replace(/\D/g, '');
          return {
            iso2: String(country.iso2 || '').toLowerCase(),
            name: String(country.name || '').trim(),
            flag: String(country.flag || '').trim(),
            countryCallingCode: code,
            dialPrefix: code,
            dialDisplay: country.dialDisplay ? String(country.dialDisplay) : (code ? '+' + code : ''),
            nationalPrefix: country.nationalPrefix === null || typeof country.nationalPrefix === 'undefined' ? '' : String(country.nationalPrefix),
            priority: Number(country.priority || 9999),
            enabled: true
          };
        })
        .filter(function (country) {
          return country.iso2 && country.countryCallingCode;
        });

      if (!countries.length) {
        return null;
      }

      return {
        defaultCountry: String(pack.defaultCountry || getPhoneCountryConfig().defaultCountry || 'gb').toLowerCase(),
        defaultDialPrefix: String(pack.defaultDialPrefix || getPhoneCountryConfig().defaultDialPrefix || '44').replace(/\D/g, ''),
        fallbackCountries: Array.isArray(pack.fallbackCountries) ? pack.fallbackCountries : ['gb', 'au', 'us', 'ie', 'nz', 'ca'],
        countries: countries
      };
    }

    function loadPhoneCountryPack() {
      if (window.__matewaPhoneCountryPackPromise) {
        return window.__matewaPhoneCountryPackPromise;
      }

      const cfg = getPhoneCountryConfig();

      window.__matewaPhoneCountryPackPromise = fetchJsonWithTimeout(cfg.remoteUrl, 1800)
        .then(validatePhonePack)
        .then(function (pack) {
          if (!pack) throw new Error('invalid_remote_pack');
          return pack;
        })
        .catch(function () {
          return fetchJsonWithTimeout(cfg.localUrl, 1200)
            .then(validatePhonePack)
            .then(function (pack) {
              if (!pack) throw new Error('invalid_local_pack');
              return pack;
            });
        })
        .catch(function () {
          return validatePhonePack(MATEWA_PHONE_FALLBACK_PACK);
        });

      return window.__matewaPhoneCountryPackPromise;
    }

    function sortPhoneCountries(countries) {
      return countries.slice().sort(function (a, b) {
        if (a.priority !== b.priority) return a.priority - b.priority;
        return String(a.name || a.iso2).localeCompare(String(b.name || b.iso2));
      });
    }

    function findPhoneCountry(iso2) {
      if (!phoneCountryPack || !Array.isArray(phoneCountryPack.countries)) return null;
      const needle = String(iso2 || '').toLowerCase();
      return phoneCountryPack.countries.find(function (country) {
        return country.iso2 === needle;
      }) || null;
    }

    function chooseDefaultPhoneCountry(pack) {
      /*
       * Always start from the configured/site default.
       * Do not make a fresh visitor session inherit a previous country choice,
       * because that can make local-trade installs appear to default to the
       * last country selected during testing.
       */
      return findPhoneCountry(pack && pack.defaultCountry)
        || findPhoneCountry(getPhoneCountryConfig().defaultCountry)
        || findPhoneCountry('gb')
        || (pack && pack.countries ? pack.countries[0] : null);
    }

    function closePhoneCountryMenu() {
      if (!phoneCountryMenu || !phoneCountryButton || !phoneCountryPicker) return;
      phoneCountryMenu.hidden = true;
      phoneCountryMenu.classList.remove('is-open');
      phoneCountryButton.setAttribute('aria-expanded', 'false');
      phoneCountryPicker.classList.remove('is-open');
    }

    function openPhoneCountryMenu() {
      if (!phoneCountryMenu || !phoneCountryButton || !phoneCountryPicker) return;
      if (!isPhoneCountrySelectorVisible()) return;
      if (phoneAdvanced) return;
      phoneCountryButton.removeAttribute('disabled');
      phoneCountryMenu.hidden = false;
      phoneCountryMenu.classList.add('is-open');
      phoneCountryButton.setAttribute('aria-expanded', 'true');
      phoneCountryPicker.classList.add('is-open');
    }

    function updateSelectedPhoneCountry() {
      if (!phoneCountrySelect) return;
      selectedPhoneCountry = findPhoneCountry(phoneCountrySelect.value) || selectedPhoneCountry;

      if (selectedPhoneCountry) {
        const flag = selectedPhoneCountry.flag || '🌐';
        const dial = selectedPhoneCountry.dialDisplay || ('+' + selectedPhoneCountry.countryCallingCode);
        const title = (selectedPhoneCountry.name || selectedPhoneCountry.iso2.toUpperCase()) + ' ' + dial;

        phoneCountrySelect.dataset.dialPrefix = selectedPhoneCountry.countryCallingCode;
        phoneCountrySelect.title = title;

        if (phoneCountryButton && !phoneAdvanced) {
          if (isPhoneCountrySelectorVisible()) {
            phoneCountryButton.removeAttribute('disabled');
          } else {
            phoneCountryButton.setAttribute('disabled', true);
          }
          phoneCountryButton.classList.remove('is-locked');
        }

        if (phoneCountryButton) {
          phoneCountryButton.title = title;
          phoneCountryButton.setAttribute('aria-label', 'Phone country code, ' + title);
          let flagNode = phoneCountryButton.querySelector('.matewa-phone-country-flag');
          let dialNode = phoneCountryButton.querySelector('.matewa-phone-country-dial');

          if (!flagNode || !dialNode) {
            phoneCountryButton.textContent = '';
            flagNode = document.createElement('span');
            flagNode.className = 'matewa-phone-country-flag';
            dialNode = document.createElement('span');
            dialNode.className = 'matewa-phone-country-dial';
            phoneCountryButton.appendChild(flagNode);
            phoneCountryButton.appendChild(dialNode);
          }

          flagNode.textContent = flag;
          dialNode.textContent = dial;
        }

        if (phoneCountryMenu) {
          Array.from(phoneCountryMenu.querySelectorAll('.matewa-phone-country-option')).forEach(function (option) {
            const active = option.dataset.iso2 === selectedPhoneCountry.iso2;
            option.classList.toggle('is-selected', active);
            option.setAttribute('aria-selected', active ? 'true' : 'false');
          });
        }
      }
    }

    function renderPhoneCountryMenu(countries, selectedIso) {
      if (!phoneCountryMenu) return;

      phoneCountryMenu.innerHTML = '';

      countries.forEach(function (country) {
        const option = document.createElement('button');
        const dial = country.dialDisplay || ('+' + country.countryCallingCode);

        option.type = 'button';
        option.className = 'matewa-phone-country-option';
        option.dataset.iso2 = country.iso2;
        option.dataset.dialPrefix = country.countryCallingCode;
        option.setAttribute('role', 'option');
        option.setAttribute('aria-selected', country.iso2 === selectedIso ? 'true' : 'false');
        option.setAttribute('aria-label', (country.name || country.iso2.toUpperCase()) + ' ' + dial);
        if (country.iso2 === selectedIso) option.classList.add('is-selected');

        const flagNode = document.createElement('span');
        const nameNode = document.createElement('span');
        const dialNode = document.createElement('span');

        flagNode.className = 'matewa-phone-country-option-flag';
        nameNode.className = 'matewa-phone-country-option-name';
        dialNode.className = 'matewa-phone-country-option-dial';

        flagNode.textContent = country.flag || '🌐';
        nameNode.textContent = country.name || country.iso2.toUpperCase();
        dialNode.textContent = dial;

        option.appendChild(flagNode);
        option.appendChild(nameNode);
        option.appendChild(dialNode);

        phoneCountryMenu.appendChild(option);
      });
    }

    function populatePhoneCountrySelect(pack) {
      if (!phoneCountrySelect || !pack) return;

      phoneCountryPack = pack;
      const countries = sortPhoneCountries(pack.countries || []);
      const selected = chooseDefaultPhoneCountry(pack);
      const selectedIso = selected ? selected.iso2 : 'gb';

      phoneCountrySelect.innerHTML = '';

      countries.forEach(function (country) {
        const option = document.createElement('option');
        option.value = country.iso2;
        option.dataset.dialPrefix = country.countryCallingCode;
        option.textContent = (country.flag ? country.flag + ' ' : '') + country.dialDisplay;
        option.label = (country.flag ? country.flag + ' ' : '') + (country.name || country.iso2.toUpperCase()) + ' ' + country.dialDisplay;
        if (country.iso2 === selectedIso) option.selected = true;
        phoneCountrySelect.appendChild(option);
      });

      renderPhoneCountryMenu(countries, selectedIso);
      updateSelectedPhoneCountry();
    }

    function normaliseVisitorPhone(value) {
      const raw = String(value || '').trim();
      const original = raw;
      let digits = getPhoneDigits(raw);

      if (!raw || !digits) {
        return { original: original, normalised: original, status: 'empty' };
      }

      const country = selectedPhoneCountry || findPhoneCountry('gb');
      const code = country && country.countryCallingCode ? String(country.countryCallingCode).replace(/\D/g, '') : '';
      const nationalPrefix = country && country.nationalPrefix ? String(country.nationalPrefix).replace(/\D/g, '') : '';

      if (digits.indexOf('00') === 0 && digits.length > 2) {
        digits = digits.substring(2);
      }

      if (code && digits.indexOf(code) === 0 && digits.length > code.length + 3) {
        return { original: original, normalised: digits, status: 'normalised' };
      }

      if (code && nationalPrefix && digits.indexOf(nationalPrefix) === 0 && digits.length > nationalPrefix.length + 3) {
        digits = code + digits.substring(nationalPrefix.length);
        return { original: original, normalised: digits, status: 'normalised' };
      }

      if (code && /^[1-9]/.test(digits) && digits.length >= 6 && digits.length <= 12) {
        return { original: original, normalised: code + digits, status: 'normalised' };
      }

      return { original: original, normalised: original, status: 'failed' };
    }

    function phoneHasMinValidLength(value) {
      return getPhoneDigits(value).length >= PHONE_MIN_DIGITS;
    }

    function looksDubiousPhone(value) {
      const digits = getPhoneDigits(value);

      if (!digits.length) return false;
      if (/^0+$/.test(digits)) return true;
      if (/^(\d)\1+$/.test(digits)) return true;
      if (digits === '0123456789') return true;
      if (digits === '1234567890') return true;
      if (digits === '9876543210') return true;

      return false;
    }

    function looksEmailLikePhoneInput(value) {
      const raw = String(value || '').trim();
      if (!raw) return false;
      if (raw.indexOf('@') !== -1) return true;
      if (/[A-Za-z]/.test(raw)) return true;
      return false;
    }

    function phoneNeedsSoftCheck(value) {
      const raw = String(value || '').trim();
      const digits = getPhoneDigits(raw);

      if (!raw) return false;
      if (looksEmailLikePhoneInput(raw)) return true;
      if (digits.length < PHONE_MIN_DIGITS) return true;
      if (digits.length > 15) return true;
      if (looksDubiousPhone(raw)) return true;

      // UK-friendly soft checks without being too aggressive
      if (/^07/.test(digits) && digits.length < 11) return true;
      if (/^447/.test(digits) && digits.length < 12) return true;

      return false;
    }

    function looksValidEmail(value) {
      return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(value || '').trim());
    }

    function looksFakeName(value) {
      const n = normalize(String(value || '').trim());

      if (n.length < 2) return true;
      if (['test', 'mr test', 'asdf', 'name'].includes(n)) return true;

      return false;
    }

    function updateCounter() {
      if (!notesInput || !charCounter) return;
      const max = notesInput.maxLength || 140;
      const used = notesInput.value ? notesInput.value.length : 0;
      charCounter.textContent = `${used} / ${max}`;
    }

    function setSoftConfirmed(input) {
      if (!input) return;
      if (!input.value.trim()) return;
      input.classList.add('is-soft-confirmed');
    }

    function clearSoftConfirmed(input) {
      if (!input) return;
      input.classList.remove('is-soft-confirmed');
    }

    function resetPhoneHint() {
      if (!phoneHint) return;
      phoneHint.textContent = t(
        'phone.mobile_only_hint',
        'Mobile/cell number only.'
      );
    }

    function showPhoneWarning() {
      if (!phoneHint) return;
      phoneHint.textContent = t(
        'phone.soft_check',
        'Just checking — is this number correct?'
      );
    }

    function resetOptionalHint(hint) {
      if (!hint) return;
      hint.textContent = t('contact.optional', 'Optional');
    }

    function applyOptionalSoftWarning(input, hint) {
      if (!input || !hint) return;

      const value = String(input.value || '').trim();

      if (!value) {
        resetOptionalHint(hint);
        return;
      }

      if (input.type === 'email') {
        if (!looksValidEmail(value)) {
          hint.textContent = t(
            'contact.email_soft_check',
            'Looks incomplete — please check'
          );
          return;
        }
      }

      if (input.type === 'text') {
        if (looksFakeName(value)) {
          hint.textContent = t(
            'contact.name_soft_check',
            'Looks unusual — please check'
          );
          return;
        }
      }

      resetOptionalHint(hint);
    }

    function lockPhoneAndAdvance() {
      if (phoneAdvanced) return;
      if (!phoneInput) return;

      const value = String(phoneInput.value || '').trim();
      if (!value) return;

      if (phoneNeedsSoftCheck(value)) {
        showPhoneWarning();
        return;
      }

      const preparedPhone = normaliseVisitorPhone(value);
      phoneInput.dataset.matewaOriginalPhone = preparedPhone.original || value;
      phoneInput.dataset.matewaNormalisedPhone = preparedPhone.normalised || value;
      phoneInput.dataset.matewaNormalisationStatus = preparedPhone.status || 'failed';
      if (selectedPhoneCountry) {
        const dialPrefix = String(selectedPhoneCountry.countryCallingCode || '').replace(/\D/g, '');
        const normalisedDigits = getPhoneDigits(preparedPhone.normalised || '');
        const nationalDisplay = dialPrefix && normalisedDigits.indexOf(dialPrefix) === 0
          ? normalisedDigits.substring(dialPrefix.length)
          : getPhoneDigits(preparedPhone.original || value);

        phoneInput.dataset.matewaCountry = selectedPhoneCountry.iso2;
        phoneInput.dataset.matewaCountryFlag = selectedPhoneCountry.flag || '';
        phoneInput.dataset.matewaCountryName = selectedPhoneCountry.name || '';
        phoneInput.dataset.matewaDialPrefix = dialPrefix;
        phoneInput.dataset.matewaDialDisplay = selectedPhoneCountry.dialDisplay || (dialPrefix ? '+' + dialPrefix : '');
        phoneInput.dataset.matewaNationalDisplay = nationalDisplay;
        phoneInput.dataset.matewaCountryUserSelected = phoneCountryUserSelected ? '1' : '';
      }

      phoneAdvanced = true;
      resetPhoneHint();
      phoneInput.classList.add('is-locked');
      phoneInput.setAttribute('readonly', true);
      if (phoneCountrySelect) {
        phoneCountrySelect.classList.add('is-locked');
        phoneCountrySelect.setAttribute('disabled', true);
      }

      if (phoneCountryButton) {
        phoneCountryButton.classList.add('is-locked');
        phoneCountryButton.setAttribute('disabled', true);
        phoneCountryButton.setAttribute('aria-expanded', 'false');
      }

      closePhoneCountryMenu();

      setTimeout(() => {
        widget.dispatchEvent(new CustomEvent('matewa:phone-complete'));
        showTask(contactTask);
      }, PHONE_CONFIRM_DELAY);
    }

    updateCounter();
    resetPhoneHint();
    resetOptionalHint(contactNameHint);
    resetOptionalHint(contactEmailHint);

    function showTask(task) {
      if (currentTask && currentTask !== task) {
        currentTask.remove();
      }
      task.classList.add('is-active');
      requestAnimationFrame(() => {
        task.style.opacity = '1';
      });
      currentTask = task;
    }

    function hideNotes() {
      notesNode.classList.remove('is-active');
      notesNode.style.opacity = '0';
    }

    function notesRequired() {
      return selectedIntents.some(v => v.includes('other'));
    }

    function syncNotesRequirement() {
      if (notesRequired()) {
        widget.dispatchEvent(new CustomEvent('matewa:notes-required'));
      } else {
        widget.dispatchEvent(new CustomEvent('matewa:notes-complete'));
      }
    }

    function commit() {
      if (committed) return;

      const hasSelection = selectedIntents.length > 0;
      if (!hasSelection) return;

      if (notesRequired() && !notesMemory.trim()) {
        return;
      }

      committed = true;

      hideNotes();
      showTask(phoneTask);
      widget.dispatchEvent(new CustomEvent('matewa:chips-complete'));
    }

    function scheduleCommit() {
      clearTimeout(commitTimer);
      commitTimer = setTimeout(commit, INTENT_COMMIT_DELAY);
    }

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

          if (committed) return;

          const intent = normalize(chip.dataset.intent);
          const idx = selectedIntents.indexOf(intent);

          if (idx !== -1) {
            selectedIntents.splice(idx, 1);
            chip.classList.remove('is-selected');
            chip.setAttribute('aria-pressed', 'false');
            clearTimeout(commitTimer);
          } else {
            if (selectedIntents.length === 2) {
              const removed = selectedIntents.shift();
              const old = chips.find(c => normalize(c.dataset.intent) === removed);
              if (old) {
                old.classList.remove('is-selected');
                old.setAttribute('aria-pressed', 'false');
              }
            }
            selectedIntents.push(intent);
            chip.classList.add('is-selected');
            chip.setAttribute('aria-pressed', 'true');
          }

          syncNotesRequirement();

          if (notesRequired()) {
            clearTimeout(commitTimer);
            notesNode.classList.add('is-active');
            notesNode.style.opacity = '1';
          } else {
            notesMemory = '';
            if (notesInput) {
              notesInput.value = '';
              notesInput.classList.remove('is-locked');
              notesInput.removeAttribute('readonly');
              updateCounter();
            }
            hideNotes();
            scheduleCommit();
          }

        });
      });
    }

    if (notesInput) {
      notesInput.addEventListener('input', () => {

        updateCounter();
        clearTimeout(notesIdleTimer);

        notesIdleTimer = setTimeout(() => {
          notesMemory = notesInput.value || '';

          if (notesMemory.trim()) {
            notesInput.classList.add('is-locked');
            notesInput.setAttribute('readonly', true);
            widget.dispatchEvent(new CustomEvent('matewa:notes-complete'));
          } else {
            widget.dispatchEvent(new CustomEvent('matewa:notes-required'));
          }

          clearTimeout(commitTimer);

          setTimeout(() => {
            commit();
          }, 450);
        }, IDLE_LOCK_DELAY);

      });
    }

    if (phoneCountrySelect) {
      phoneCountrySelect.addEventListener('change', () => {
        phoneCountryUserSelected = true;
        updateSelectedPhoneCountry();
        resetPhoneHint();
      });
    }

    function togglePhoneCountryMenu(event) {
      if (event) {
        event.preventDefault();
        event.stopPropagation();
      }

      if (phoneAdvanced) return;

      if (phoneCountryMenu && !phoneCountryMenu.hidden) {
        closePhoneCountryMenu();
      } else {
        openPhoneCountryMenu();
      }
    }

    if (phoneCountryPicker && phoneCountryButton) {
      phoneCountryButton.addEventListener('click', function (event) {
        event.preventDefault();
        event.stopPropagation();
        togglePhoneCountryMenu();
      });

      phoneCountryButton.addEventListener('mousedown', function (event) {
        event.stopPropagation();
      });

      phoneCountryButton.addEventListener('touchstart', function (event) {
        event.stopPropagation();
      }, { passive: true });

      phoneCountryPicker.addEventListener('click', function (event) {
        event.stopPropagation();
      });

      phoneCountryButton.addEventListener('keydown', function (event) {
        if (event.key === 'ArrowDown' || event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          event.stopPropagation();
          openPhoneCountryMenu();
          const selected = phoneCountryMenu ? phoneCountryMenu.querySelector('.matewa-phone-country-option.is-selected') : null;
          const first = phoneCountryMenu ? phoneCountryMenu.querySelector('.matewa-phone-country-option') : null;
          (selected || first || phoneCountryButton).focus();
        }
      });
    }

    if (phoneCountryMenu) {
      phoneCountryMenu.addEventListener('click', function (event) {
        const option = event.target && event.target.closest ? event.target.closest('.matewa-phone-country-option') : null;
        if (!option || !phoneCountrySelect) return;

        event.preventDefault();
        event.stopPropagation();

        phoneCountrySelect.value = option.dataset.iso2 || phoneCountrySelect.value;
        phoneCountrySelect.dispatchEvent(new Event('change', { bubbles: true }));
        closePhoneCountryMenu();
        if (phoneCountryButton) phoneCountryButton.focus();
      });

      phoneCountryMenu.addEventListener('keydown', function (event) {
        const current = event.target && event.target.closest ? event.target.closest('.matewa-phone-country-option') : null;
        if (!current) return;

        if (event.key === 'Escape') {
          event.preventDefault();
          closePhoneCountryMenu();
          if (phoneCountryButton) phoneCountryButton.focus();
          return;
        }

        if (event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          current.click();
          return;
        }

        if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
          event.preventDefault();
          const options = Array.from(phoneCountryMenu.querySelectorAll('.matewa-phone-country-option'));
          const index = options.indexOf(current);
          const nextIndex = event.key === 'ArrowDown'
            ? Math.min(options.length - 1, index + 1)
            : Math.max(0, index - 1);
          if (options[nextIndex]) options[nextIndex].focus();
        }
      });
    }

    document.addEventListener('click', function (event) {
      if (!phoneCountryPicker || phoneCountryPicker.contains(event.target)) return;
      closePhoneCountryMenu();
    });

    document.addEventListener('keydown', function (event) {
      if (event.key === 'Escape') closePhoneCountryMenu();
    });

    populatePhoneCountrySelect(validatePhonePack(MATEWA_PHONE_FALLBACK_PACK));

    loadPhoneCountryPack().then(populatePhoneCountrySelect).catch(function () {
      populatePhoneCountrySelect(validatePhonePack(MATEWA_PHONE_FALLBACK_PACK));
    });

    if (phoneInput) {
      phoneInput.addEventListener('input', () => {
        if (phoneAdvanced) return;

        clearTimeout(phoneIdleTimer);
        clearTimeout(phoneWarnTimer);
        clearTimeout(phoneBlurTimer);
        resetPhoneHint();

        const raw = String(phoneInput.value || '').trim();
        if (!raw) {
          return;
        }

        phoneWarnTimer = setTimeout(() => {
          if (phoneNeedsSoftCheck(phoneInput.value)) {
            showPhoneWarning();
          }
        }, PHONE_SOFT_CHECK_DELAY);

        phoneIdleTimer = setTimeout(() => {
          lockPhoneAndAdvance();
        }, IDLE_LOCK_DELAY);
      });

      phoneInput.addEventListener('focus', () => {
        if (phoneAdvanced) return;

        clearTimeout(phoneIdleTimer);
        clearTimeout(phoneWarnTimer);
        clearTimeout(phoneBlurTimer);
        resetPhoneHint();
      });

      phoneInput.addEventListener('blur', () => {
        if (phoneAdvanced) return;

        clearTimeout(phoneIdleTimer);
        clearTimeout(phoneWarnTimer);
        clearTimeout(phoneBlurTimer);

        const raw = String(phoneInput.value || '').trim();
        if (!raw) {
          resetPhoneHint();
          return;
        }

        phoneBlurTimer = setTimeout(() => {
          lockPhoneAndAdvance();
        }, PHONE_BLUR_CONFIRM_DELAY);
      });
    }

    if (contactNameInput) {
      contactNameInput.addEventListener('input', () => {
        clearTimeout(contactNameIdleTimer);
        clearSoftConfirmed(contactNameInput);
        resetOptionalHint(contactNameHint);

        contactNameIdleTimer = setTimeout(() => {
          if (!contactNameInput.value.trim()) return;
          applyOptionalSoftWarning(contactNameInput, contactNameHint);
          setSoftConfirmed(contactNameInput);
        }, CONTACT_CONFIRM_DELAY);
      });

      contactNameInput.addEventListener('focus', () => {
        clearTimeout(contactNameIdleTimer);
        clearSoftConfirmed(contactNameInput);
        resetOptionalHint(contactNameHint);
      });

      contactNameInput.addEventListener('blur', () => {
        clearTimeout(contactNameIdleTimer);

        if (!contactNameInput.value.trim()) {
          resetOptionalHint(contactNameHint);
          return;
        }

        contactNameIdleTimer = setTimeout(() => {
          applyOptionalSoftWarning(contactNameInput, contactNameHint);
          setSoftConfirmed(contactNameInput);
        }, CONTACT_BLUR_CONFIRM_DELAY);
      });
    }

    if (contactEmailInput) {
      contactEmailInput.addEventListener('input', () => {
        clearTimeout(contactEmailIdleTimer);
        clearSoftConfirmed(contactEmailInput);
        resetOptionalHint(contactEmailHint);

        contactEmailIdleTimer = setTimeout(() => {
          if (!contactEmailInput.value.trim()) return;
          applyOptionalSoftWarning(contactEmailInput, contactEmailHint);
          setSoftConfirmed(contactEmailInput);
        }, CONTACT_CONFIRM_DELAY);
      });

      contactEmailInput.addEventListener('focus', () => {
        clearTimeout(contactEmailIdleTimer);
        clearSoftConfirmed(contactEmailInput);
        resetOptionalHint(contactEmailHint);
      });

      contactEmailInput.addEventListener('blur', () => {
        clearTimeout(contactEmailIdleTimer);

        if (!contactEmailInput.value.trim()) {
          resetOptionalHint(contactEmailHint);
          return;
        }

        contactEmailIdleTimer = setTimeout(() => {
          applyOptionalSoftWarning(contactEmailInput, contactEmailHint);
          setSoftConfirmed(contactEmailInput);
        }, CONTACT_BLUR_CONFIRM_DELAY);
      });
    }

    widget._matewaIntentMemory = () => ({
      intents: selectedIntents.slice(),
      notes: notesMemory
    });

    requestAnimationFrame(() => {
      showTask(intentTask);
      bindChips();
      syncNotesRequirement();
    });
  }

})();