/**
 * 247ChatMate — Pro Lead Routing Frontend Trigger
 * PROLEADROLLBACKWHATSAPPMINLEADS4E
 *
 * Lead-only frontend capture.
 * Does not change WhatsApp handoff behaviour.
 * Sends visitor-submitted widget fields to the local WordPress Ajax handler.
 * Phase 5-A-14G1 adds phone-only abandoned lead capture after a short delay.
 * No remote services. No IP collection. No visitor IDs. No lifecycle calls. No raw payload logging.
 */

(function () {
  'use strict';

  const config = window.MATEWA_PRO_LEAD || null;
  if (!config || !config.enabled || !config.ajaxUrl || !config.nonce || !config.action) return;

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

  let sent = false;
  let phoneOnlySent = false;
  let widgetOpenRecorded = false;
  let phoneOnlyTimer = null;
  const phoneOnlyDelayMs = Math.max(15000, parseInt(config.phoneOnlyDelayMs || 45000, 10));

  const captured = {
    name: '',
    phone: '',
    email: '',
    phoneMeta: {}
  };

  widget.addEventListener('matewa:opened', recordWidgetOpen, true);

  if (widget.classList && widget.classList.contains('is-open')) {
    recordWidgetOpen();
  }

  if (window.MutationObserver) {
    const openObserver = new MutationObserver(function () {
      if (widget.classList && widget.classList.contains('is-open')) {
        recordWidgetOpen();
      }
    });
    openObserver.observe(widget, { attributes: true, attributeFilter: ['class'] });
  }

  widget.addEventListener('input', cacheFromEvent, true);
  widget.addEventListener('change', cacheFromEvent, true);
  widget.addEventListener('blur', cacheFromEvent, true);

  widget.addEventListener('matewa:phone-complete', function () {
    captureCurrentInputs();
    schedulePhoneOnlyLead();
  }, true);

  widget.addEventListener('matewa:cta-selected', function () {
    captureCurrentInputs();
  }, true);

  widget.addEventListener('matewa:intentReady', function (event) {
    if (sent) return;

    captureCurrentInputs();
    cancelPhoneOnlyTimer();

    const payload = buildPayload(event && event.detail ? event.detail : {});

    if (!payload.phone && !payload.email) {
      return;
    }

    sent = true;
    sendLead(payload);
  }, true);

  widget.addEventListener('matewa:reset', function () {
    sent = false;
    captured.name = '';
    captured.phone = '';
    captured.email = '';
    captured.phoneMeta = {};
    phoneOnlySent = false;
    cancelPhoneOnlyTimer();
  });

  function cacheFromEvent(event) {
    const target = event && event.target ? event.target : null;
    if (!target || !target.classList) return;

    if (target.classList.contains('matewa-phone-input')) {
      captured.phone = getPreparedPhone(target);
      captured.phoneMeta = getPhoneMetadataFromInput(target);
      schedulePhoneOnlyLead();
    }

    if (target.classList.contains('matewa-contact-name')) {
      captured.name = cleanValue(target.value);
    }

    if (target.classList.contains('matewa-contact-email')) {
      captured.email = cleanValue(target.value);
    }

    if (isValidPhoneForPhoneOnly(captured.phone || readPhoneValue())) {
      schedulePhoneOnlyLead();
    }
  }


  function recordWidgetOpen() {
    if (widgetOpenRecorded || !config.widgetOpenAction) return;

    widgetOpenRecorded = true;
    sendLead(Object.assign({ event_type: 'widget_open' }, getSafePageContext()), config.widgetOpenAction);
  }

  function cancelPhoneOnlyTimer() {
    if (phoneOnlyTimer) {
      clearTimeout(phoneOnlyTimer);
      phoneOnlyTimer = null;
    }
  }

  function schedulePhoneOnlyLead() {
    if (sent || phoneOnlySent || !config.phoneOnlyAction) return;

    captureCurrentInputs();

    if (!isValidPhoneForPhoneOnly(captured.phone || readPhoneValue())) {
      cancelPhoneOnlyTimer();
      return;
    }

    cancelPhoneOnlyTimer();
    phoneOnlyTimer = window.setTimeout(function () {
      if (sent || phoneOnlySent) return;

      captureCurrentInputs();
      const phone = captured.phone || readPhoneValue();

      if (!isValidPhoneForPhoneOnly(phone)) return;

      const payload = buildPayload({ method: 'phone_only' });
      payload.handoff_method = 'phone_only';
      phoneOnlySent = true;
      sent = true;
      sendLead(payload, config.phoneOnlyAction);
    }, phoneOnlyDelayMs);
  }

  function isValidPhoneForPhoneOnly(phone) {
    const digits = String(phone || '').replace(/\D+/g, '');
    return digits.length >= 7 && digits.length <= 15;
  }

  function captureCurrentInputs() {
    const phoneInput = widget.querySelector('.matewa-phone-input');
    const phone = phoneInput ? getPreparedPhone(phoneInput) : readPhoneValue();
    const name = readValue('.matewa-contact-name');
    const email = readValue('.matewa-contact-email');

    if (phone) captured.phone = phone;
    if (phoneInput) captured.phoneMeta = getPhoneMetadataFromInput(phoneInput);
    if (name) captured.name = name;
    if (email) captured.email = email;
  }

  function readValue(selector) {
    const el = widget.querySelector(selector);
    return el && typeof el.value === 'string' ? cleanValue(el.value) : '';
  }


  function readPhoneValue() {
    const el = widget.querySelector('.matewa-phone-input');
    return el ? getPreparedPhone(el) : '';
  }

  function getPreparedPhone(input) {
    if (!input) return '';
    const normalised = input.dataset && input.dataset.matewaNormalisedPhone
      ? cleanValue(input.dataset.matewaNormalisedPhone)
      : '';
    return normalised || cleanValue(input.value);
  }

  function getPhoneMetadataFromInput(input) {
    const data = input && input.dataset ? input.dataset : {};

    return {
      phone_original: cleanValue(data.matewaOriginalPhone || (input ? input.value : '')),
      phone_country_iso2: cleanValue(data.matewaCountry || ''),
      phone_country_flag: cleanValue(data.matewaCountryFlag || ''),
      phone_country_name: cleanValue(data.matewaCountryName || ''),
      phone_dial_display: cleanValue(data.matewaDialDisplay || ''),
      phone_dial_prefix: cleanValue(data.matewaDialPrefix || ''),
      phone_national_display: cleanValue(data.matewaNationalDisplay || ''),
      phone_normalisation_status: cleanValue(data.matewaNormalisationStatus || ''),
      phone_country_user_selected: cleanValue(data.matewaCountryUserSelected || '')
    };
  }

  function readPhoneMetadata() {
    const input = widget.querySelector('.matewa-phone-input');

    if (input) {
      return getPhoneMetadataFromInput(input);
    }

    return Object.assign({
      phone_original: '',
      phone_country_iso2: '',
      phone_country_flag: '',
      phone_country_name: '',
      phone_dial_display: '',
      phone_dial_prefix: '',
      phone_national_display: '',
      phone_normalisation_status: '',
      phone_country_user_selected: ''
    }, captured.phoneMeta || {});
  }

  function getSafePageContext() {
    const path = window.location && typeof window.location.pathname === 'string'
      ? cleanValue(window.location.pathname)
      : '';

    return {
      page_path: path || '/',
      page_title: cleanValue(document.title || '')
    };
  }

  function readWidgetLanguage() {
    const fromWidget = widget && widget.dataset ? cleanValue(widget.dataset.widgetLanguage || '') : '';
    if (fromWidget) return fromWidget;

    if (window.MATEWA_SETTINGS && typeof window.MATEWA_SETTINGS.siteLang === 'string') {
      return cleanValue(window.MATEWA_SETTINGS.siteLang);
    }

    return '';
  }

  function cleanValue(value) {
    return String(value || '').replace(/\s+/g, ' ').trim();
  }

  function normaliseSpaces(value) {
    return String(value || '').replace(/\s+/g, ' ').trim();
  }

  function getIntentMemory() {
    if (typeof widget._matewaIntentMemory === 'function') {
      const memory = widget._matewaIntentMemory();
      if (memory && typeof memory === 'object') {
        return memory;
      }
    }

    return {};
  }

  function escapeCssValue(value) {
    const raw = String(value || '');
    if (window.CSS && typeof window.CSS.escape === 'function') {
      return window.CSS.escape(raw);
    }
    return raw.replace(/["\\]/g, '\\$&');
  }

  function resolveIntentLabels(intents) {
    if (!Array.isArray(intents)) return '';

    const labels = intents
      .map(intent => String(intent || '').trim().toLowerCase().replace(/^intent\./, ''))
      .filter(Boolean)
      .map(intent => {
        const liveLabelEl = widget.querySelector('.matewa-chip[data-intent="' + escapeCssValue(intent) + '"] .matewa-chip-label');
        if (liveLabelEl && liveLabelEl.textContent.trim()) {
          return normaliseSpaces(liveLabelEl.textContent);
        }

        return normaliseSpaces(intent.replace(/[_-]+/g, ' '));
      })
      .filter(Boolean);

    return labels.join(', ');
  }

  function resolveLeadIntentLabel(intents, notes) {
    const cleanedIntents = Array.isArray(intents)
      ? intents.map(intent => String(intent || '').trim().toLowerCase().replace(/^intent\./, '')).filter(Boolean)
      : [];

    const cleanedNotes = normaliseSpaces(notes || '');
    const visibleIntents = cleanedIntents.filter(intent => intent !== 'other');

    /*
     * 5-A-30 / 5-A14Q:
     * If the visitor uses the final Other/Something else chip, the lead email
     * must carry the typed request through as the useful subject/context.
     * Do not reduce the lead to weak wording such as “Interested in other”.
     */
    if (cleanedNotes && cleanedIntents.includes('other') && visibleIntents.length === 0) {
      return 'Custom request: ' + cleanedNotes.slice(0, 120);
    }

    return resolveIntentLabels(intents);
  }

  function buildPayload(detail) {
    const memory = getIntentMemory();
    const intents = Array.isArray(memory.intents) ? memory.intents : [];
    const phoneMeta = readPhoneMetadata();

    return Object.assign({
      name: captured.name || readValue('.matewa-contact-name'),
      phone: captured.phone || readPhoneValue(),
      email: captured.email || readValue('.matewa-contact-email'),
      location: '',
      intent_label: resolveLeadIntentLabel(intents, typeof memory.notes === 'string' ? memory.notes.trim() : ''),
      intent_keys: intents.map(intent => String(intent || '').trim()).filter(Boolean).join(','),
      message: typeof memory.notes === 'string' ? memory.notes.trim() : '',
      handoff_method: detail.method || 'unknown',
      widget_language: readWidgetLanguage()
    }, getSafePageContext(), phoneMeta);
  }

  function buildFormBody(payload, actionName) {
    const params = new URLSearchParams();
    params.set('action', actionName || config.action);
    params.set('nonce', config.nonce);

    Object.keys(payload).forEach(key => {
      params.set(key, payload[key] || '');
    });

    return params.toString();
  }

  function sendLead(payload, actionName) {
    const body = buildFormBody(payload, actionName);

    if (navigator.sendBeacon) {
      const blob = new Blob([body], {
        type: 'application/x-www-form-urlencoded; charset=UTF-8'
      });

      if (navigator.sendBeacon(config.ajaxUrl, blob)) {
        return;
      }
    }

    if (window.fetch) {
      window.fetch(config.ajaxUrl, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: body,
        keepalive: true
      }).catch(function () {});
    }
  }
})();
