(function () {
  'use strict';

  var cfg = window.CUSTAUSU_ADMIN_EMAIL || {};

  function dispatchDirtyEvents(el) {
    if (!el) return;
    el.dispatchEvent(new Event('input', { bubbles: true }));
    el.dispatchEvent(new Event('change', { bubbles: true }));
  }

  function initColorPicker() {
    if (!window.jQuery) return;
    var $ = window.jQuery;

    if (!($.fn && $.fn.wpColorPicker)) return;

    $('.custausu-color').wpColorPicker({
      change: function (event) {
        var el = event && event.target ? event.target : null;
        if (!el) return;
        setTimeout(function () {
          dispatchDirtyEvents(el);
          refreshAllPreviews();
        }, 0);
      },
      clear: function (event) {
        var el = event && event.target ? event.target : null;
        if (!el) return;
        setTimeout(function () {
          dispatchDirtyEvents(el);
          refreshAllPreviews();
        }, 0);
      }
    });
  }

  function getEditorHtml(editorId) {
    if (window.tinymce) {
      var ed = tinymce.get(editorId);
      if (ed && !ed.isHidden()) {
        return ed.getContent() || '';
      }
    }

    var ta = document.getElementById(editorId);
    return ta ? (ta.value || '') : '';
  }

  function insertAtCursorTextarea(el, text) {
    if (!el) return;

    var start = el.selectionStart || 0;
    var end = el.selectionEnd || 0;
    var v = el.value || '';

    el.value = v.slice(0, start) + text + v.slice(end);
    el.focus();
    el.selectionStart = el.selectionEnd = start + text.length;

    dispatchDirtyEvents(el);
  }

  function insertVar(btn) {
    var wrap = btn.closest('.custausu-email-type');
    if (!wrap) return;

    var editorId = wrap.getAttribute('data-editor-id');
    var v = btn.getAttribute('data-var') || '';
    if (!editorId || !v) return;

    if (window.tinymce) {
      var ed = tinymce.get(editorId);
      if (ed && !ed.isHidden()) {
        ed.focus();
        ed.selection.setContent(v);

        if (typeof ed.save === 'function') ed.save();
        if (typeof ed.fire === 'function') ed.fire('change');

        var taSync = document.getElementById(editorId);
        if (taSync) {
          dispatchDirtyEvents(taSync);
        }
        return;
      }
    }

    var ta = document.getElementById(editorId);
    insertAtCursorTextarea(ta, v);
  }

  function applyVars(html, vars) {
    Object.keys(vars).forEach(function (k) {
      html = html.split('{{' + k + '}}').join(String(vars[k]));
    });
    return html;
  }

  function getThemeValue(name, fallback) {
    var el = document.querySelector('input[name="custausu_global_settings[email_theme][' + name + ']"]');
    return el && el.value ? el.value : fallback;
  }

  function refreshPreview(root) {
    var wrap = root && root.closest ? root.closest('.custausu-email-type') : null;

    if (!wrap && root && root.classList && root.classList.contains('custausu-email-type')) {
      wrap = root;
    }
    if (!wrap) return;

    var editorId = wrap.getAttribute('data-editor-id');
    var subjectEl = wrap.querySelector('input[data-role="subject"]');
    var prevBox = wrap.querySelector('.custausu-email-preview');
    if (!prevBox || !editorId) return;

    var html = getEditorHtml(editorId);

    var vars = {
      site_name: cfg.site_name || 'Site',
      username: 'demo_user',
      first_name: 'Demo',
      verify_link: cfg.home_url || '/',
      support_url: cfg.home_url || '/',
      profile_url: cfg.profile_url || '',
      year: String(new Date().getFullYear())
    };

    var theme = {
      wrap_bg: getThemeValue('wrap_bg', '#f7f7f7'),
      wrap_border: getThemeValue('wrap_border', '#222222'),
      wrap_text: getThemeValue('wrap_text', '#222222'),
      h2_color: getThemeValue('h2_color', '#222222'),
      btn_bg: getThemeValue('btn_bg', '#222222'),
      btn_text: getThemeValue('btn_text', '#ffffff')
    };

    var out = applyVars(html, Object.assign({}, vars, theme));

    prevBox.innerHTML =
      '<div style="font-family:Arial;background:' + theme.wrap_bg + ';border:4px solid ' + theme.wrap_border + ';padding:20px;border-radius:15px;max-width:650px;margin:auto;color:' + theme.wrap_text + ';text-align:center;">' +
        out +
      '</div>';

    if (subjectEl) {
      var s = subjectEl.value || '';
      var subj = applyVars(s, vars);
      var subjBox = wrap.querySelector('.custausu-email-preview-subject');
      if (subjBox) subjBox.textContent = subj;
    }
  }

  function refreshAllPreviews() {
    document.querySelectorAll('.custausu-email-type').forEach(function (x) {
      refreshPreview(x);
    });
  }

  function initEmailAccordion() {
    function qa(sel, root) {
      return Array.prototype.slice.call((root || document).querySelectorAll(sel));
    }

    var KEY = 'custausu_acc_state:' + location.host + ':custausu-settings:email-customizer:v1';

    function readState() {
      try {
        var raw = localStorage.getItem(KEY);
        if (!raw) return null;
        var obj = JSON.parse(raw);
        return (obj && typeof obj === 'object') ? obj : null;
      } catch (e) {
        return null;
      }
    }

    function writeState(state) {
      try {
        localStorage.setItem(KEY, JSON.stringify(state || {}));
      } catch (e) {}
    }

    function getAllDetails() {
      return qa('details.custausu-email-acc');
    }

    function collectState() {
      var state = {};
      qa('details.custausu-email-acc[data-email-lang]').forEach(function (d) {
        var lang = d.getAttribute('data-email-lang') || '';
        if (!lang) return;
        state[lang] = !!d.open;
      });
      return state;
    }

    function applyState(state) {
      if (!state) return false;
      var touched = false;

      qa('details.custausu-email-acc[data-email-lang]').forEach(function (d) {
        var lang = d.getAttribute('data-email-lang') || '';
        if (!lang) return;

        if (Object.prototype.hasOwnProperty.call(state, lang)) {
          d.open = !!state[lang];
          touched = true;
        }
      });

      return touched;
    }

    function computeAllOpenState() {
      var all = getAllDetails();
      if (!all.length) {
        return { allOpen: false, allClosed: false };
      }

      var openCount = 0;
      all.forEach(function (d) {
        if (d.open) openCount++;
      });

      return {
        allOpen: openCount === all.length,
        allClosed: openCount === 0
      };
    }

    function setBtnDisabled(btn, disabled) {
      if (!btn) return;
      btn.disabled = !!disabled;
      btn.classList.toggle('is-disabled', !!disabled);
      btn.setAttribute('aria-disabled', disabled ? 'true' : 'false');
    }

    function updateButtonsState() {
      var st = computeAllOpenState();
      qa('.custausu-email-acc-expand').forEach(function (b) {
        setBtnDisabled(b, st.allOpen);
      });
      qa('.custausu-email-acc-collapse').forEach(function (b) {
        setBtnDisabled(b, st.allClosed);
      });
    }

    function setAll(open) {
      getAllDetails().forEach(function (d) {
        d.open = !!open;
      });
      writeState(collectState());
      updateButtonsState();
    }

    var saved = readState();
    var applied = applyState(saved);
    if (!applied) {
      writeState(collectState());
    }

    qa('details.custausu-email-acc').forEach(function (d) {
      d.addEventListener('toggle', function () {
        writeState(collectState());
        updateButtonsState();
      }, { passive: true });
    });

    document.addEventListener('click', function (ev) {
      var ex = ev.target.closest && ev.target.closest('.custausu-email-acc-expand');
      var co = ev.target.closest && ev.target.closest('.custausu-email-acc-collapse');

      if (ex) {
        ev.preventDefault();
        var st = computeAllOpenState();
        if (!st.allOpen) setAll(true);
        return;
      }

      if (co) {
        ev.preventDefault();
        var st2 = computeAllOpenState();
        if (!st2.allClosed) setAll(false);
      }
    });

    updateButtonsState();
  }

  function sendTest(sendBtn) {
    var wrap = sendBtn.closest('.custausu-email-type');
    if (!wrap) return;

    var toEl = wrap.querySelector('input[data-role="test_to"]');
    var subjectEl = wrap.querySelector('input[data-role="subject"]');

    var to = (toEl && toEl.value ? toEl.value : '').trim();
    if (!to) {
      alert(cfg.msg_insert_test_email || 'Insert a test email');
      return;
    }

    var editorId = wrap.getAttribute('data-editor-id');
    var lang = wrap.getAttribute('data-lang') || '';
    var type = wrap.getAttribute('data-type') || '';
    var subj = (subjectEl && subjectEl.value ? subjectEl.value : '').trim();
    var body = getEditorHtml(editorId);

    var payload = new FormData();
    payload.append('action', 'custausu_send_test_email');
    payload.append('nonce', cfg.nonce || '');
    payload.append('to', to);
    payload.append('lang', lang);
    payload.append('type', type);
    payload.append('subject', subj);
    payload.append('body', body);

    ['wrap_bg','wrap_border','wrap_text','h2_color','btn_bg','btn_text'].forEach(function (k) {
      var el = document.querySelector('input[name="custausu_global_settings[email_theme][' + k + ']"]');
      payload.append('theme[' + k + ']', el && el.value ? el.value : '');
    });

    sendBtn.disabled = true;
    sendBtn.textContent = cfg.msg_sending || 'Sending...';

    fetch(cfg.ajax_url || '', {
      method: 'POST',
      credentials: 'same-origin',
      body: payload
    })
      .then(function (r) { return r.json(); })
      .then(function (json) {
        if (json && json.success) {
          alert(cfg.msg_sent || 'Test email sent!');
        } else {
          alert((cfg.msg_error_prefix || 'Error: ') + (json && json.data ? json.data : 'unknown'));
        }
      })
      .catch(function () {
        alert(cfg.msg_network_error || 'Network error');
      })
      .finally(function () {
        sendBtn.disabled = false;
        sendBtn.textContent = cfg.msg_send_test || 'Send test';
      });
  }

  document.addEventListener('click', function (ev) {
    var vb = ev.target.closest && ev.target.closest('.custausu-insert-var');
    if (vb) {
      ev.preventDefault();
      insertVar(vb);
      refreshPreview(vb);
      return;
    }

    var sendBtn = ev.target.closest && ev.target.closest('.custausu-send-test');
    if (sendBtn) {
      ev.preventDefault();
      sendTest(sendBtn);
    }
  });

  document.addEventListener('input', function (ev) {
    var wrap = ev.target.closest && ev.target.closest('.custausu-email-type');
    if (wrap) {
      refreshPreview(ev.target);
    }

    if (ev.target.classList && ev.target.classList.contains('custausu-color')) {
      refreshAllPreviews();
    }
  });

  document.addEventListener('tinymce-editor-init', function (e) {
    var ed = e.detail && e.detail.editor;
    if (!ed) return;

    ed.on('Change KeyUp SetContent Undo Redo', function () {
      var wrap = document.querySelector('[data-editor-id="' + ed.id + '"]');
      if (wrap) refreshPreview(wrap);
    });
  });

  window.addEventListener('load', function () {
    initColorPicker();
    refreshAllPreviews();
    initEmailAccordion();
  });
})();