/**
 * CNP Solutions — contact channels, WhatsApp deep links, and enquiry API.
 */
(function (global) {
  'use strict';

  const DEFAULTS = {
    whatsapp_number: '26774818826',
    whatsapp_display: '+267 74 818 826',
    email_info: 'info@cnpsolutions.co.bw',
    email_sales: 'sales@cnpsolutions.co.bw',
    email_support: 'support@cnpsolutions.co.bw',
    phone: '+26774818826',
    company: 'CNP Solutions',
  };

  let contactInfo = { ...DEFAULTS };

  function waUrl(text) {
    const num = (contactInfo.whatsapp_number || DEFAULTS.whatsapp_number).replace(/\D/g, '');
    const base = 'https://wa.me/' + num;
    if (!text) return base;
    return base + '?text=' + encodeURIComponent(text);
  }

  function mailto(email, subject, body) {
    const e = email || contactInfo.email_sales;
    let url = 'mailto:' + e;
    const params = [];
    if (subject) params.push('subject=' + encodeURIComponent(subject));
    if (body) params.push('body=' + encodeURIComponent(body));
    if (params.length) url += '?' + params.join('&');
    return url;
  }

  function buildEnquiryText(fields) {
    const name = (fields.name || '').trim();
    const email = (fields.email || '').trim();
    const phone = (fields.phone || '').trim();
    const subject = (fields.subject || 'CNPERP enquiry').trim();
    const message = (fields.message || '').trim();
    const source = fields.source || 'CNPERP';
    let text = `Hello ${contactInfo.company || 'CNP Solutions'},\n\n`;
    text += `*${subject}*\n\n`;
    if (message) text += message + '\n\n';
    text += `—\nName: ${name}\nEmail: ${email}\n`;
    if (phone) text += `Phone: ${phone}\n`;
    text += `Sent via: ${source}`;
    return text;
  }

  function pickEmail(subject) {
    const s = (subject || '').toLowerCase();
    if (s.includes('support') || s.includes('technical') || s.includes('license')) {
      return contactInfo.email_info;
    }
    return contactInfo.email_sales;
  }

  async function loadContactInfo() {
    try {
      const res = await fetch('/api/v1/public/contact/info');
      if (res.ok) {
        const data = await res.json();
        contactInfo = { ...DEFAULTS, ...data };
      }
    } catch (_) {}
    return contactInfo;
  }

  async function submitEnquiry(fields, options) {
    options = options || {};
    await loadContactInfo();
    const text = buildEnquiryText(fields);
    const email = pickEmail(fields.subject);
    const payload = {
      name: fields.name,
      email: fields.email,
      phone: fields.phone || null,
      subject: fields.subject,
      message: fields.message,
      source: fields.source || 'CNPERP',
      preferred_channel: options.channel || 'whatsapp',
    };

    let apiResult = null;
    try {
      const res = await fetch('/api/v1/public/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(payload),
      });
      apiResult = await res.json();
      if (!res.ok) throw new Error(apiResult.detail || apiResult.message || 'Submit failed');
    } catch (err) {
      if (options.requireApi) throw err;
    }

    const whatsapp_url = (apiResult && apiResult.whatsapp_url) || waUrl(text);
    const mailto_url = (apiResult && apiResult.mailto_url) || mailto(
      email,
      `[CNPERP] ${fields.subject || 'Enquiry'}`,
      text
    );

    if (options.channel === 'email') {
      window.location.href = mailto_url;
    } else if (options.openWhatsApp !== false) {
      window.open(whatsapp_url, '_blank', 'noopener,noreferrer');
    }

    return {
      success: true,
      whatsapp_url,
      mailto_url,
      api: apiResult,
    };
  }

  function renderContactChannels(containerId) {
    const el = document.getElementById(containerId);
    if (!el) return;
    const info = contactInfo;
    el.innerHTML = `
      <div class="col-md-4">
        <div class="contact-channel">
          <div class="icon icon-wa"><i class="bi bi-whatsapp"></i></div>
          <h6 class="fw-bold">WhatsApp</h6>
          <p class="small text-muted mb-2">Fastest — chat with our team</p>
          <a href="${waUrl('Hello CNP Solutions, I need help with CNPERP.')}" target="_blank" rel="noopener" class="fw-semibold">${info.whatsapp_display}</a>
        </div>
      </div>
      <div class="col-md-4">
        <div class="contact-channel">
          <div class="icon icon-mail"><i class="bi bi-envelope"></i></div>
          <h6 class="fw-bold">Email</h6>
          <p class="small text-muted mb-1">General / support</p>
          <a href="mailto:${info.email_info}" class="d-block small fw-semibold">${info.email_info}</a>
          <p class="small text-muted mb-1 mt-2">Sales &amp; licences</p>
          <a href="mailto:${info.email_sales}" class="d-block small fw-semibold">${info.email_sales}</a>
        </div>
      </div>
      <div class="col-md-4">
        <div class="contact-channel">
          <div class="icon icon-phone"><i class="bi bi-telephone"></i></div>
          <h6 class="fw-bold">Phone</h6>
          <p class="small text-muted mb-2">Sales &amp; support</p>
          <a href="tel:${info.phone}" class="fw-semibold">${info.whatsapp_display}</a>
        </div>
      </div>`;
  }

  global.CNPContact = {
    loadContactInfo,
    submitEnquiry,
    buildEnquiryText,
    waUrl,
    mailto,
    renderContactChannels,
    getInfo: function () { return { ...contactInfo }; },
  };

  loadContactInfo();
})(typeof window !== 'undefined' ? window : globalThis);
