'use strict';

(function () {
  const config = window.kramarEmailManager || {};
  const { ajaxUrl, nonce, i18n } = config;

  function init() {
    initToggles();
    initPreviewButtons();
    initTestSendButtons();
    initDeleteButtons();
    initAddNewEmail();
    initGlobalSettingsForm();
  }

  // ─── Email Enable/Disable Toggles ──────────────────────────────────

  function initToggles() {
    document.querySelectorAll('.kramar-em-toggle input[type="checkbox"]').forEach(function (toggle) {
      toggle.addEventListener('change', function () {
        const emailId = this.dataset.emailId;
        const enabled = this.checked;

        fetch(ajaxUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: new URLSearchParams({
            action: 'kramar_email_toggle',
            _ajax_nonce: nonce,
            email_id: emailId,
            enabled: enabled ? '1' : '',
          }),
        });
      });
    });
  }

  // ─── Preview ───────────────────────────────────────────────────────

  function initPreviewButtons() {
    document.querySelectorAll('.kramar-em-action--preview').forEach(function (btn) {
      btn.addEventListener('click', function () {
        const emailId = this.dataset.emailId;
        openPreview(emailId);
      });
    });
  }

  function openPreview(emailId) {
    const modal = document.getElementById('kramar-em-preview-modal');
    if (!modal) return;

    modal.style.display = 'flex';
    const iframe = modal.querySelector('.kramar-em-preview-modal__iframe');
    const title = modal.querySelector('.kramar-em-preview-modal__title');

    title.textContent = 'Loading...';
    iframe.srcdoc = '<p style="padding:40px;text-align:center;font-family:sans-serif;color:#787c82;">Loading preview...</p>';

    fetch(ajaxUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        action: 'kramar_email_preview',
        _ajax_nonce: nonce,
        email_id: emailId,
      }),
    })
      .then(function (r) { return r.json(); })
      .then(function (res) {
        if (res.success && res.data.html) {
          iframe.srcdoc = res.data.html;
          title.textContent = emailId;
        } else {
          iframe.srcdoc = '<p style="padding:40px;text-align:center;color:#d63638;">Failed to load preview.</p>';
        }
      });

    // Device toggle.
    modal.querySelectorAll('.kramar-em-preview-modal__device-toggle button').forEach(function (btn) {
      btn.addEventListener('click', function () {
        modal.querySelectorAll('.kramar-em-preview-modal__device-toggle button').forEach(function (b) { b.classList.remove('active'); });
        this.classList.add('active');
        var device = this.dataset.device;
        iframe.style.maxWidth = device === 'mobile' ? '375px' : '100%';
      });
    });

    // Close.
    modal.querySelector('.kramar-em-preview-modal__close').addEventListener('click', function () {
      modal.style.display = 'none';
    });
    modal.querySelector('.kramar-em-preview-modal__overlay').addEventListener('click', function () {
      modal.style.display = 'none';
    });
  }

  // ─── Test Send ─────────────────────────────────────────────────────

  function initTestSendButtons() {
    document.querySelectorAll('.kramar-em-action--test').forEach(function (btn) {
      btn.addEventListener('click', function () {
        var emailId = this.dataset.emailId;
        var dialog = document.getElementById('kramar-em-test-dialog');
        if (!dialog) return;

        dialog.style.display = 'flex';
        dialog.querySelector('.kramar-em-test-dialog__email-id').value = emailId;
        dialog.querySelector('.kramar-em-test-dialog__result').style.display = 'none';
      });
    });

    var dialog = document.getElementById('kramar-em-test-dialog');
    if (!dialog) return;

    dialog.querySelector('.kramar-em-test-dialog__cancel').addEventListener('click', function () {
      dialog.style.display = 'none';
    });
    dialog.querySelector('.kramar-em-test-dialog__overlay').addEventListener('click', function () {
      dialog.style.display = 'none';
    });

    dialog.querySelector('.kramar-em-test-dialog__send').addEventListener('click', function () {
      var emailId = dialog.querySelector('.kramar-em-test-dialog__email-id').value;
      var recipients = dialog.querySelector('.kramar-em-test-dialog__input').value;
      var resultEl = dialog.querySelector('.kramar-em-test-dialog__result');

      this.disabled = true;
      this.textContent = 'Sending...';

      fetch(ajaxUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          action: 'kramar_email_test_send',
          _ajax_nonce: nonce,
          email_id: emailId,
          recipients: recipients,
        }),
      })
        .then(function (r) { return r.json(); })
        .then(function (res) {
          resultEl.style.display = 'block';
          if (res.success) {
            resultEl.className = 'kramar-em-test-dialog__result kramar-em-test-dialog__result--success';
            resultEl.textContent = i18n.testSent;
          } else {
            resultEl.className = 'kramar-em-test-dialog__result kramar-em-test-dialog__result--error';
            resultEl.textContent = i18n.testFailed;
          }
        })
        .finally(function () {
          var btn = dialog.querySelector('.kramar-em-test-dialog__send');
          btn.disabled = false;
          btn.textContent = 'Send Test';
        });
    });
  }

  // ─── Delete Custom Emails ──────────────────────────────────────────

  function initDeleteButtons() {
    document.querySelectorAll('.kramar-em-action--delete').forEach(function (btn) {
      btn.addEventListener('click', function () {
        if (!confirm(i18n.confirmDelete)) return;

        var emailId = this.dataset.emailId;
        var row = this.closest('tr');

        fetch(ajaxUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: new URLSearchParams({
            action: 'kramar_email_delete',
            _ajax_nonce: nonce,
            email_id: emailId,
          }),
        })
          .then(function (r) { return r.json(); })
          .then(function (res) {
            if (res.success && row) {
              row.style.opacity = '0';
              setTimeout(function () { row.remove(); }, 300);
            }
          });
      });
    });
  }

  // ─── Add New Email Dialog ──────────────────────────────────────────

  function initAddNewEmail() {
    var addBtn = document.querySelector('.kramar-em-add-new');
    var dialog = document.getElementById('kramar-em-new-email');
    if (!addBtn || !dialog) return;

    addBtn.addEventListener('click', function (e) {
      e.preventDefault();
      dialog.style.display = 'flex';
      dialog.querySelector('.kramar-em-new-email__step--context').style.display = 'block';
      dialog.querySelector('.kramar-em-new-email__step--details').style.display = 'none';
    });

    dialog.querySelector('.kramar-em-new-email__close').addEventListener('click', function () {
      dialog.style.display = 'none';
    });
    dialog.querySelector('.kramar-em-new-email__overlay').addEventListener('click', function () {
      dialog.style.display = 'none';
    });

    // Context cards.
    var selectedContext = 'order';
    dialog.querySelectorAll('.kramar-em-context-card').forEach(function (card) {
      card.addEventListener('click', function () {
        selectedContext = this.dataset.context;
        dialog.querySelectorAll('.kramar-em-context-card').forEach(function (c) { c.classList.remove('active'); });
        this.classList.add('active');

        dialog.querySelector('.kramar-em-new-email__step--context').style.display = 'none';
        dialog.querySelector('.kramar-em-new-email__step--details').style.display = 'block';

        // Show/hide trigger row based on context.
        var triggerRow = dialog.querySelector('.kramar-new-email-trigger-row--order');
        if (triggerRow) {
          triggerRow.style.display = selectedContext === 'order' ? '' : 'none';
        }

        // Sync trigger sub-fields for the initial state.
        syncTriggerSubfields();
      });
    });

    // Show/hide trigger sub-fields when trigger_type radio changes.
    function syncTriggerSubfields() {
      var checked = dialog.querySelector('input[name="trigger_type"]:checked');
      var val = checked ? checked.value : 'status_change';
      dialog.querySelectorAll('.kramar-new-email-trigger-subfields').forEach(function (el) {
        var isMatch = el.classList.contains('kramar-new-email-trigger-subfields--' + val);
        el.style.display = isMatch ? 'flex' : 'none';
      });
    }

    dialog.querySelectorAll('input[name="trigger_type"]').forEach(function (radio) {
      radio.addEventListener('change', syncTriggerSubfields);
    });

    // Show/hide anchor_status select when anchor select value is/isn't 'status'.
    function syncAnchorStatusSelect() {
      var anchorSel = dialog.querySelector('select[name="anchor"]');
      var anchorStatusSel = dialog.querySelector('select[name="anchor_status"]');
      if (anchorSel && anchorStatusSel) {
        anchorStatusSel.style.display = anchorSel.value === 'status' ? '' : 'none';
      }
    }

    var anchorSelectEl = dialog.querySelector('select[name="anchor"]');
    if (anchorSelectEl) {
      anchorSelectEl.addEventListener('change', syncAnchorStatusSelect);
    }

    // Show/hide custom email input based on recipient radio.
    dialog.querySelectorAll('input[name="recipient_type"]').forEach(function (radio) {
      radio.addEventListener('change', function () {
        var customInput = dialog.querySelector('input[name="custom_recipient"]');
        if (customInput) {
          customInput.style.display = this.value === 'custom' ? '' : 'none';
          if (this.value === 'custom') customInput.focus();
        }
      });
    });

    // Back button.
    dialog.querySelector('.kramar-em-new-email__back').addEventListener('click', function () {
      dialog.querySelector('.kramar-em-new-email__step--details').style.display = 'none';
      dialog.querySelector('.kramar-em-new-email__step--context').style.display = 'block';
    });

    // Create button.
    dialog.querySelector('.kramar-em-new-email__create').addEventListener('click', function () {
      var name = dialog.querySelector('#kramar-new-email-name').value.trim();
      if (!name) {
        dialog.querySelector('#kramar-new-email-name').focus();
        return;
      }

      var params = {
        action: 'kramar_email_create',
        _ajax_nonce: nonce,
        email_name: name,
        context: selectedContext,
        trigger_type: 'manual',
        trigger_from: '',
        trigger_to: '',
        anchor: 'completed',
        anchor_status: '',
        delay_value: '0',
        delay_unit: 'days',
        recipient_type: 'customer',
        custom_recipient: '',
      };

      // Get trigger type.
      var triggerRadio = dialog.querySelector('input[name="trigger_type"]:checked');
      if (triggerRadio) params.trigger_type = triggerRadio.value;

      // Status-change sub-fields.
      var fromSelect = dialog.querySelector('select[name="trigger_from"]');
      if (fromSelect) params.trigger_from = fromSelect.value;
      var toSelect = dialog.querySelector('select[name="trigger_to"]');
      if (toSelect) params.trigger_to = toSelect.value;

      // Delay sub-fields.
      var delayValueInput = dialog.querySelector('input[name="delay_value"]');
      if (delayValueInput) params.delay_value = delayValueInput.value;
      var delayUnitSelect = dialog.querySelector('select[name="delay_unit"]');
      if (delayUnitSelect) params.delay_unit = delayUnitSelect.value;
      var anchorSelect = dialog.querySelector('select[name="anchor"]');
      if (anchorSelect) params.anchor = anchorSelect.value;
      var anchorStatusSelect = dialog.querySelector('select[name="anchor_status"]');
      if (anchorStatusSelect) params.anchor_status = anchorStatusSelect.value;

      // Get recipient.
      var recipientRadio = dialog.querySelector('input[name="recipient_type"]:checked');
      if (recipientRadio) params.recipient_type = recipientRadio.value;
      var customInput = dialog.querySelector('input[name="custom_recipient"]');
      if (customInput) params.custom_recipient = customInput.value;

      fetch(ajaxUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams(params),
      })
        .then(function (r) { return r.json(); })
        .then(function (res) {
          var errBox = dialog.querySelector('.kramar-em-new-email__error');
          if (res.success && res.data.redirect) {
            window.location.href = res.data.redirect;
            return;
          }
          // Surface the reason (e.g. a name that collides with an existing
          // email) instead of leaving the dialog sitting there doing nothing.
          if (errBox) {
            errBox.textContent = typeof res.data === 'string' ? res.data : '';
            errBox.style.display = errBox.textContent ? '' : 'none';
          }
        });
    });
  }

  // ─── Global Settings AJAX Save ─────────────────────────────────────

  function initGlobalSettingsForm() {
    var forms = [
      { selector: '.kramar-em-global-form', action: 'kramar_email_save_global' },
      { selector: '.kramar-em-business-form', action: 'kramar_email_save_business' },
    ];

    forms.forEach(function (cfg) {
      var form = document.querySelector(cfg.selector);
      if (!form) return;

      form.addEventListener('submit', function (e) {
        e.preventDefault();

        var data = new FormData(form);
        data.append('action', cfg.action);
        data.append('_ajax_nonce', nonce);

        var btn = form.querySelector('[type="submit"]');
        var orig = btn ? btn.value : '';

        fetch(ajaxUrl, {
          method: 'POST',
          body: new URLSearchParams(data),
        })
          .then(function (r) { return r.json(); })
          .then(function (res) {
            if (res.success && btn) {
              btn.value = i18n.saved || 'Saved';
              setTimeout(function () { btn.value = orig; }, 2000);
            }
          });
      });
    });
  }

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