/**
 * 247ChatMate — Intent Actions (DESKTOP APP ONLY — CLEAN)
 * ------------------------------------------------------
 * • Pulls intent + notes + name from Flow memory
 * • Natural conversational WhatsApp message
 * • Mobile → opens WhatsApp app directly
 * • Desktop → launches WhatsApp Desktop via protocol
 * • No web fallback
 * • No blank tab
 */

(function () {

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

  widget.addEventListener('matewa:intentReady', function (e) {

    const d = e.detail || {};

    let intents = [];
    let notes = '';
    let name = '';

    if (typeof widget._matewaIntentMemory === 'function') {
      const mem = widget._matewaIntentMemory();

      if (Array.isArray(mem?.intents)) {
        intents = mem.intents
          .map(v => String(v || '').trim().toLowerCase())
          .filter(Boolean);
      }

      if (mem?.notes) {
        notes = mem.notes.trim();
      }
    }

    const nameInput = widget.querySelector('.matewa-contact-name');
    if (nameInput && nameInput.value.trim()) {
      name = tidyName(nameInput.value.trim());
    }

    const hasOther = intents.includes('other');
    const visibleIntents = intents.filter(intent => intent !== 'other');

    const lines = [];

    if (name) {
      lines.push(`Hi, my name is ${name}.`);
    } else {
      lines.push('Hi there.');
    }

    const intentBlock = buildIntentBlock(visibleIntents, notes, hasOther);
    if (Array.isArray(intentBlock) && intentBlock.length) {
      intentBlock.forEach(line => lines.push(line));
    } else if (notes) {
      lines.push(formatNotesLine(notes));
    }

    if (d.method === 'now') {
      lines.push(`I'm ready to chat now.`);
      lines.push(`Tap send to start the conversation ➡️`);
    }

    if (d.method === 'later') {
      lines.push(`Please get back to me when you can.`);
      lines.push(`Tap send to start the conversation ➡️`);
    }

    const message = lines.join('\n');

    const phone = widget.dataset.phone;
    if (!phone) return;

    const encoded = encodeURIComponent(message);

    function isMobileDevice() {
      return /Android|iPhone|iPad|iPod|Windows Phone/i.test(navigator.userAgent);
    }

    if (isMobileDevice()) {
      window.location.href =
        `https://api.whatsapp.com/send?phone=${phone}&text=${encoded}`;
    } else {
      window.location.href =
        `whatsapp://send?phone=${phone}&text=${encoded}`;
    }

    fireTelemetry('whatsapp');

  });

  function buildIntentBlock(visibleIntents, notes, hasOther) {
    const lines = [];
    const cleanedNotes = cleanNotesPhrase(notes);

    if (visibleIntents.length === 0) {
      if (cleanedNotes) {
        lines.push(`I'm interested in ${cleanedNotes}.`);
      }
      return lines;
    }

    if (visibleIntents.length === 1) {
      const baseIntent = humaniseIntent(visibleIntents[0]);

      if (hasOther && cleanedNotes) {
        lines.push(`I'm interested in ${baseIntent} and ${cleanedNotes}.`);
      } else {
        lines.push(`I'm interested in ${baseIntent}.`);
        if (cleanedNotes) {
          lines.push(formatNotesLine(notes));
        }
      }

      return lines;
    }

    const humanised = visibleIntents.map(humaniseIntent);
    const intentSentence = buildNaturalListSentence(humanised);

    lines.push(`I'm interested in ${intentSentence}.`);

    if (cleanedNotes) {
      lines.push(formatNotesLine(notes));
    }

    return lines;
  }

  function buildNaturalListSentence(items) {
    if (!Array.isArray(items) || !items.length) return '';

    if (items.length === 1) {
      return items[0];
    }

    if (items.length === 2) {
      return `${items[0]} and ${items[1]}`;
    }

    return `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`;
  }

  function humaniseIntent(text) {
  if (!text) return '';

  const raw = String(text).trim().toLowerCase().replace(/^intent\./, '');
  const selector = '.matewa-chip[data-intent="' + escapeCssValue(raw) + '"] .matewa-chip-label';

  const liveLabelEl = widget.querySelector(selector);
  if (liveLabelEl && liveLabelEl.textContent.trim()) {
    return liveLabelEl.textContent.replace(/\s+/g, ' ').trim();
  }

  const template = document.getElementById('matewa-task-intent-template');
  if (template && template.content) {
    const templateLabelEl = template.content.querySelector(selector);
    if (templateLabelEl && templateLabelEl.textContent.trim()) {
      return templateLabelEl.textContent.replace(/\s+/g, ' ').trim();
    }
  }

  const clean = raw
    .replace(/[_-]+/g, ' ')
    .replace(/\s+/g, ' ')
    .trim();

  const map = {
    quote: 'a quote',
    pricing: 'pricing',
    availability: 'availability'
  };

  return map[clean] || clean.charAt(0).toUpperCase() + clean.slice(1);
}

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 cleanNotesPhrase(text) {
    let clean = String(text || '').trim();
    if (!clean) return '';

    clean = clean.replace(/^[\s.,!?-]+/, '');
    clean = clean.replace(/[.!?]+$/, '');

    const lower = clean.toLowerCase();

    const sentenceStarters = [
      'hi',
      'hello',
      'do you',
      'can you',
      'could you',
      'is there',
      'are there',
      'i need',
      'i want',
      "i'm",
      'im ',
      'we need',
      'we want',
      'looking for'
    ];

    const alreadySentenceLike = sentenceStarters.some(start => lower.startsWith(start));

    if (alreadySentenceLike) {
      return normaliseSentence(clean).replace(/[.!?]+$/, '');
    }

    return clean.charAt(0).toLowerCase() + clean.slice(1);
  }

  function formatNotesLine(text) {
    let clean = String(text || '').trim();
    if (!clean) return '';

    clean = clean.replace(/^[\s.,!?-]+/, '');

    const lower = clean.toLowerCase();

    const sentenceStarters = [
      'hi',
      'hello',
      'do you',
      'can you',
      'could you',
      'is there',
      'are there',
      'i need',
      'i want',
      "i'm",
      'im ',
      'we need',
      'we want',
      'looking for'
    ];

    const alreadySentenceLike = sentenceStarters.some(start => lower.startsWith(start));

    if (alreadySentenceLike) {
      return normaliseSentence(clean);
    }

    clean = clean.charAt(0).toLowerCase() + clean.slice(1);
    clean = ensureEnding(clean);

    return `I'd also like to ask about ${clean}`;
  }

  function normaliseSentence(text) {
    let clean = String(text || '').trim();
    if (!clean) return '';

    clean = clean.charAt(0).toUpperCase() + clean.slice(1);
    clean = ensureEnding(clean);

    return clean;
  }

  function ensureEnding(text) {
    if (!/[.!?]$/.test(text)) {
      text += '.';
    }
    return text;
  }

  function tidyName(text) {
    return String(text)
      .trim()
      .split(/\s+/)
      .map(part => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
      .join(' ');
  }

  function fireTelemetry(channel) {
    const isMobile =
      /Android|iPhone|iPad|iPod|Windows Phone/i.test(navigator.userAgent);

    widget.dispatchEvent(new CustomEvent('matewa:intentFired', {
      detail: {
        channel,
        environment: isMobile ? 'mobile' : 'desktop'
      }
    }));
  }

})();