(function () {
  function renderPreviewHtml(source) {
    var sampleBody =
      '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0">' +
      '<tr><td style="padding:24px;font-family:Arial,sans-serif;color:#0E1B42;">' +
      '<h2 style="margin:0 0 12px;font-size:24px;line-height:1.3;">本期電子報標題</h2>' +
      '<p style="margin:0 0 12px;font-size:16px;line-height:1.7;">這是預覽用的假內容，實際寄送時會替換成文章列表。</p>' +
      '<p style="margin:0;font-size:16px;line-height:1.7;"><a href="https://example.com" target="_blank">瞭解更多</a></p>' +
      '</td></tr></table>';
    var html = source || '';
    var hasBodySlot = /\{\{(?:email_body|html_body|text_body)\}\}/.test(html);
    return {
      html: html
        .replace(/\{\{email_body\}\}/g, sampleBody)
        .replace(/\{\{html_body\}\}/g, sampleBody)
        .replace(/\{\{text_body\}\}/g, sampleBody),
      hasBodySlot: hasBodySlot,
    };
  }

  function insertAtCursor(textarea, text) {
    if (!textarea) {
      return;
    }
    var start = typeof textarea.selectionStart === 'number' ? textarea.selectionStart : textarea.value.length;
    var end = typeof textarea.selectionEnd === 'number' ? textarea.selectionEnd : textarea.value.length;
    var before = textarea.value.slice(0, start);
    var after = textarea.value.slice(end);
    textarea.value = before + text + after;
    var nextPos = start + text.length;
    textarea.focus();
    textarea.setSelectionRange(nextPos, nextPos);
    textarea.dispatchEvent(new Event('input', { bubbles: true }));
  }

  function collectWarnings(html, hasBodySlot) {
    var warnings = [];
    if (!hasBodySlot) {
      warnings.push('Missing {{email_body}} placeholder.');
    }
    if (/<p\b[^>]*>\s*<(?:ul|ol|table)\b/i.test(html || '')) {
      warnings.push('Avoid wrapping ul, ol, or table directly inside p tags.');
    }
    if (/\b(?:src|href)=["']\/(?!\/)/i.test(html || '')) {
      warnings.push('Relative src/href detected; email templates should use absolute URLs.');
    }
    return warnings;
  }

  function setStatus(statusNode, messages) {
    if (!statusNode) {
      return;
    }
    if (!messages || !messages.length) {
      statusNode.hidden = true;
      statusNode.textContent = '';
      return;
    }
    statusNode.hidden = false;
    statusNode.textContent = messages.join(' ');
  }

  function openPreviewInFrame(frame, shell, html) {
    if (!frame || !shell) {
      return false;
    }
    shell.hidden = false;
    var doc = frame.contentDocument || (frame.contentWindow && frame.contentWindow.document);
    if (!doc) {
      return false;
    }
    doc.open();
    doc.write('<!doctype html><html><head><meta charset="utf-8"><title>Newsletter Preview</title></head><body style="margin:0;">' + html + '</body></html>');
    doc.close();
    return true;
  }

  function createEditorShell() {
    var shell = document.createElement('div');
    shell.className = 'newsletter-editor-shell';
    shell.innerHTML =
      '<div class="newsletter-editor-status" data-newsletter-editor-status hidden></div>' +
      '<div class="newsletter-editor-toolbar">' +
      '<button type="button" class="button button-small button-secondary" data-newsletter-insert="{{email_body}}">Insert {{email_body}}</button>' +
      '<button type="button" class="button button-small button-secondary" data-newsletter-preview>Preview with sample content</button>' +
      '</div>' +
      '<div class="newsletter-preview-shell" data-newsletter-preview-shell hidden>' +
      '<div class="newsletter-preview-shell__head">' +
      '<strong>Preview</strong>' +
      '<button type="button" class="button button-small button-secondary" data-newsletter-preview-close>Close</button>' +
      '</div>' +
      '<iframe class="newsletter-preview-frame" data-newsletter-preview-frame title="Newsletter preview"></iframe>' +
      '</div>';
    return shell;
  }

  function bindEditor(textarea) {
    if (!textarea || textarea.dataset.newsletterEditorBound === '1') {
      return;
    }
    textarea.dataset.newsletterEditorBound = '1';

    var shell = createEditorShell();
    textarea.parentNode.insertBefore(shell, textarea);

    var statusNode = shell.querySelector('[data-newsletter-editor-status]');
    var previewButton = shell.querySelector('[data-newsletter-preview]');
    var previewShell = shell.querySelector('[data-newsletter-preview-shell]');
    var previewFrame = shell.querySelector('[data-newsletter-preview-frame]');
    var previewCloseButton = shell.querySelector('[data-newsletter-preview-close]');
    var insertButtons = shell.querySelectorAll('[data-newsletter-insert]');

    for (var i = 0; i < insertButtons.length; i++) {
      insertButtons[i].addEventListener('click', function () {
        insertAtCursor(textarea, this.getAttribute('data-newsletter-insert') || '');
      });
    }

    if (previewButton) {
      previewButton.addEventListener('click', function () {
        var preview = renderPreviewHtml(textarea.value || '');
        var warnings = collectWarnings(textarea.value || '', preview.hasBodySlot);
        setStatus(statusNode, warnings);
        if (!openPreviewInFrame(previewFrame, previewShell, preview.html)) {
          setStatus(statusNode, ['Unable to render in-page preview.'].concat(warnings));
        }
      });
    }

    if (previewCloseButton && previewShell) {
      previewCloseButton.addEventListener('click', function () {
        previewShell.hidden = true;
      });
    }
  }

  function boot() {
    var textareas = document.querySelectorAll('textarea[data-newsletter-html-input="1"]');
    for (var i = 0; i < textareas.length; i++) {
      bindEditor(textareas[i]);
    }
  }

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