/**
 * Settings → WhatsApp (Meta Business API)
 */
(function () {
  function authHeaders() {
    const h = { 'Content-Type': 'application/json' };
    if (window.auth && window.auth.authHeader) Object.assign(h, window.auth.authHeader());
    return h;
  }

  function notify(msg, type) {
    if (window.modernUI && window.modernUI.showNotification) {
      window.modernUI.showNotification(msg, type || 'info');
    } else {
      alert(msg);
    }
  }

  function showAlert(msg, type) {
    const el = document.getElementById('waStatusAlert');
    if (!el) return;
    el.className = 'alert alert-' + (type || 'info');
    el.textContent = msg;
    el.classList.remove('d-none');
  }

  async function loadWhatsAppSettings() {
    try {
      const res = await fetch('/api/v1/whatsapp/settings', { headers: authHeaders() });
      if (!res.ok) return;
      const s = await res.json();
      document.getElementById('waEnabled').checked = !!s.whatsapp_enabled;
      document.getElementById('waPhoneId').value = s.whatsapp_business_phone_id || '';
      const hint = document.getElementById('waTokenHint');
      if (hint) {
        hint.textContent = s.whatsapp_business_token_set
          ? 'Token is saved. Enter a new value only to replace it.'
          : 'Paste your Meta permanent access token.';
      }
    } catch (e) {
      console.warn('WhatsApp settings:', e);
    }
  }

  async function saveWhatsAppSettings() {
    const btn = document.getElementById('waSaveBtn');
    if (btn) btn.disabled = true;
    try {
      const body = {
        whatsapp_enabled: document.getElementById('waEnabled').checked,
        whatsapp_api_provider: 'whatsapp_business',
        whatsapp_business_phone_id: document.getElementById('waPhoneId').value.trim(),
      };
      const token = document.getElementById('waToken').value.trim();
      if (token) body.whatsapp_business_token = token;

      const res = await fetch('/api/v1/whatsapp/settings', {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || 'Save failed');
      showAlert(
        data.configured ? 'WhatsApp saved and ready.' : 'Saved — add phone ID and token to enable.',
        data.configured ? 'success' : 'warning'
      );
      notify('WhatsApp settings saved', 'success');
      document.getElementById('waToken').value = '';
      loadWhatsAppSettings();
    } catch (e) {
      showAlert(e.message, 'danger');
      notify(e.message, 'error');
    } finally {
      if (btn) btn.disabled = false;
    }
  }

  async function testWhatsApp() {
    const btn = document.getElementById('waTestBtn');
    if (btn) btn.disabled = true;
    try {
      const res = await fetch('/api/v1/whatsapp/test', { method: 'POST', headers: authHeaders() });
      const data = await res.json();
      if (!res.ok || !data.success) throw new Error(data.message || data.detail || 'Test failed');
      showAlert(
        'Connected' + (data.display_phone_number ? ' — ' + data.display_phone_number : ''),
        'success'
      );
      notify('WhatsApp API connection OK', 'success');
    } catch (e) {
      showAlert(e.message, 'danger');
      notify(e.message, 'error');
    } finally {
      if (btn) btn.disabled = false;
    }
  }

  document.addEventListener('DOMContentLoaded', () => {
    loadWhatsAppSettings();
    document.getElementById('waSaveBtn')?.addEventListener('click', saveWhatsAppSettings);
    document.getElementById('waTestBtn')?.addEventListener('click', testWhatsApp);
  });
})();
