(function () {
  function resolveFieldContainer(input) {
    if (!input) {
      return null;
    }
    return input.closest('[data-field]') || input.closest('.w-field') || input.parentNode;
  }

  function toggleFieldVisibility(campaignType) {
    var htmlInput = document.getElementById('id_html_template');
    var textInput = document.getElementById('id_text_template');
    var weeklyArticles = document.getElementById('id_weekly_articles');
    var weeklyArticleInput = document.querySelector('input[name="weekly_articles"]');
    var weeklyItemTemplate = document.getElementById('id_item_template_html');

    var htmlField = resolveFieldContainer(htmlInput);
    var textField = resolveFieldContainer(textInput);
    var weeklyArticlesField = resolveFieldContainer(weeklyArticles || weeklyArticleInput);
    var weeklyItemTemplateField = resolveFieldContainer(weeklyItemTemplate);

    var isWeekly = (campaignType || 'general') === 'weekly_news';
    var generalOnlyBlocks = document.querySelectorAll('.newsletter-general-only');
    var weeklyOnlyBlocks = document.querySelectorAll('.newsletter-weekly-only');
    for (var gi = 0; gi < generalOnlyBlocks.length; gi++) {
      generalOnlyBlocks[gi].style.display = isWeekly ? 'none' : '';
    }
    for (var wi = 0; wi < weeklyOnlyBlocks.length; wi++) {
      weeklyOnlyBlocks[wi].style.display = isWeekly ? '' : 'none';
    }

    // Fallback for markup without classname bindings.
    if (htmlField) htmlField.style.display = isWeekly ? 'none' : '';
    if (textField) textField.style.display = isWeekly ? 'none' : '';
    if (weeklyArticlesField) weeklyArticlesField.style.display = isWeekly ? '' : 'none';
    if (weeklyItemTemplateField) weeklyItemTemplateField.style.display = isWeekly ? '' : 'none';
  }

  function renderPreviewHtml(composedHtml) {
    return (composedHtml || '')
      .replace(/\{\{token\}\}/g, 'sample-token-123')
      .replace(/\{\{email\}\}/g, 'demo@example.com')
      .replace(/\{\{list_id\}\}/g, 'sample-list')
      .replace(/\{\{tenant_id\}\}/g, 'sample-tenant')
      .replace(/\{\{confirm_url\}\}/g, 'https://example.com/newsletter/confirm?token=sample-token-123')
      .replace(/\{\{unsubscribe_url\}\}/g, 'https://example.com/newsletter/unsubscribe?token=sample-token-123');
  }

  function createPreviewShell() {
    var shell = document.createElement('div');
    shell.className = 'newsletter-campaign-preview-shell';
    shell.setAttribute('data-newsletter-preview-shell', '1');
    shell.hidden = true;
    shell.innerHTML =
      '<div class="newsletter-campaign-preview-head">' +
      '<strong>Preview</strong>' +
      '<button type="button" class="button button-small button-secondary" data-campaign-preview-close>Close</button>' +
      '</div>' +
      '<iframe class="newsletter-campaign-preview-frame" data-campaign-preview-frame title="Campaign preview"></iframe>';
    return shell;
  }

  function buildToolbar() {
    var row = document.createElement('div');
    row.className = 'newsletter-campaign-toolbar';
    row.setAttribute('data-newsletter-preview-toolbar', '1');
    row.innerHTML =
      '<button type="button" class="button button-small button-secondary" data-preview-newsletter-campaign>預覽內容</button>' +
      '<span class="help" data-campaign-status hidden></span>';
    return row;
  }

  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>Campaign Preview</title></head><body>' +
        renderPreviewHtml(html) +
        '</body></html>'
    );
    doc.close();
    return true;
  }

  function getCsrfToken() {
    var input = document.querySelector('input[name="csrfmiddlewaretoken"]');
    return input ? input.value : '';
  }

  function getSelectedWeeklyArticleIds() {
    var form = document.querySelector('form[data-edit-form]') || document.getElementById('w-editor-form');
    if (!form) return '';
    var fd = new FormData(form);
    var ids = fd.getAll('weekly_articles') || [];
    var clean = [];
    for (var i = 0; i < ids.length; i++) {
      var v = String(ids[i] || '').trim();
      if (v) clean.push(v);
    }
    return clean.join(',');
  }

  async function composePreviewHtml(templateId, emailBodyHtml, campaignType, weeklyArticleIds, weeklyItemTemplateHtml) {
    var body = new URLSearchParams();
    body.set('template_id', templateId || '');
    body.set('email_body_html', emailBodyHtml || '');
    body.set('campaign_type', campaignType || 'general');
    body.set('weekly_article_ids', weeklyArticleIds || '');
    body.set('weekly_item_template_html', weeklyItemTemplateHtml || '');

    var resp = await fetch('/newsletter/campaigns/preview-compose/', {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRFToken': getCsrfToken(),
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
      body: body.toString(),
    });
    if (!resp.ok) {
      throw new Error('Failed to compose preview (HTTP ' + resp.status + ')');
    }
    var data = await resp.json();
    return data.html || '';
  }

  function resolveHtmlFieldContainer(htmlInput) {
    function isVisible(node) {
      if (!node) return false;
      var style = window.getComputedStyle(node);
      return style.display !== 'none' && style.visibility !== 'hidden';
    }
    var candidates = [
      document.querySelector('[data-field="newsletter_template"]'),
      document.querySelector('[data-field="subject_template"]'),
      document.querySelector('[data-field="list_id"]'),
      document.querySelector('.fields'),
      document.querySelector('[data-edit-form]'),
      document.querySelector('[data-field="html_template"]'),
      htmlInput ? htmlInput.closest('.w-field') : null,
      htmlInput ? htmlInput.parentNode : null,
    ];
    for (var i = 0; i < candidates.length; i++) {
      if (isVisible(candidates[i])) return candidates[i];
    }
    return candidates[0] || null;
  }

  function resolvePreviewAnchor(htmlInput) {
    var scheduledInput = document.getElementById('id_scheduled_at');
    var scheduledPanelSection =
      document.getElementById('panel-scheduled_at-section') ||
      (scheduledInput ? scheduledInput.closest('section.w-panel') : null);
    if (scheduledPanelSection && scheduledPanelSection.parentNode) {
      return { container: scheduledPanelSection.parentNode, beforeNode: scheduledPanelSection };
    }
    var scheduledField =
      document.querySelector('[data-field="scheduled_at"]') ||
      (scheduledInput &&
        (scheduledInput.closest('li[data-contentpath]') ||
          scheduledInput.closest('.w-field') ||
          scheduledInput.closest('li') ||
          scheduledInput.closest('section') ||
          resolveFieldContainer(scheduledInput)));
    if (scheduledField && scheduledField.parentNode) {
      return { container: scheduledField.parentNode, beforeNode: scheduledField };
    }
    var fallback = resolveHtmlFieldContainer(htmlInput);
    if (fallback && fallback.parentNode) {
      return { container: fallback.parentNode, beforeNode: fallback };
    }
    return null;
  }

  function setupWeeklyArticlePager() {
    var weeklyField =
      document.querySelector('[data-field="weekly_articles"]') ||
      resolveFieldContainer(document.querySelector('input[name="weekly_articles"]'));
    if (!weeklyField) {
      return;
    }
    var inputs = weeklyField.querySelectorAll('input[name="weekly_articles"]');
    if (!inputs || !inputs.length) {
      return;
    }

    var rows = [];
    for (var i = 0; i < inputs.length; i++) {
      var row = inputs[i].closest('li') || inputs[i].closest('label') || inputs[i].parentNode;
      if (row) {
        rows.push(row);
      }
    }
    if (!rows.length) {
      return;
    }

    for (var r = 0; r < rows.length; r++) {
      rows[r].classList.add('newsletter-article-row');
    }

    var shell = document.createElement('div');
    shell.className = 'newsletter-article-pager';
    shell.innerHTML =
      '<label class="newsletter-article-pager__label">每頁</label>' +
      '<select class="newsletter-article-pager__size" data-article-page-size>' +
      '<option value="10">10</option>' +
      '<option value="30">30</option>' +
      '<option value="50">50</option>' +
      '</select>' +
      '<button type="button" class="button button-small button-secondary newsletter-article-pager__btn" data-article-prev>上一頁</button>' +
      '<span class="newsletter-article-pager__info" data-article-page-info></span>' +
      '<button type="button" class="button button-small button-secondary newsletter-article-pager__btn" data-article-next>下一頁</button>';
    weeklyField.insertBefore(shell, weeklyField.firstChild);

    var pageSizeSelect = shell.querySelector('[data-article-page-size]');
    var prevBtn = shell.querySelector('[data-article-prev]');
    var nextBtn = shell.querySelector('[data-article-next]');
    var info = shell.querySelector('[data-article-page-info]');
    var page = 1;
    var pageSize = 10;

    function renderPage() {
      var total = rows.length;
      var totalPages = Math.max(1, Math.ceil(total / pageSize));
      if (page > totalPages) page = totalPages;
      var start = (page - 1) * pageSize;
      var end = start + pageSize;
      for (var idx = 0; idx < rows.length; idx++) {
        rows[idx].style.display = idx >= start && idx < end ? '' : 'none';
      }
      info.textContent = '第 ' + page + ' / ' + totalPages + ' 頁，共 ' + total + ' 則';
      prevBtn.disabled = page <= 1;
      nextBtn.disabled = page >= totalPages;
    }

    pageSizeSelect.addEventListener('change', function () {
      pageSize = parseInt(pageSizeSelect.value, 10) || 10;
      page = 1;
      renderPage();
    });
    prevBtn.addEventListener('click', function () {
      if (page > 1) {
        page -= 1;
        renderPage();
      }
    });
    nextBtn.addEventListener('click', function () {
      page += 1;
      renderPage();
    });
    renderPage();
  }

  function boot() {
    var templateSelect = document.getElementById('id_newsletter_template');
    var htmlInput = document.getElementById('id_html_template');
    var campaignTypeInput = document.getElementById('id_campaign_type');
    var weeklyItemTemplateInput = document.getElementById('id_item_template_html');
    var campaignType =
      campaignTypeInput && (campaignTypeInput.value || '').trim()
        ? (campaignTypeInput.value || '').trim()
        : document.querySelector('.newsletter-weekly-only')
        ? 'weekly_news'
        : 'general';
    var isWeekly = campaignType === 'weekly_news';

    if (!templateSelect) {
      return;
    }

    if (campaignTypeInput) {
      toggleFieldVisibility(campaignType);
      campaignTypeInput.addEventListener('change', function () {
        toggleFieldVisibility(campaignTypeInput.value || 'general');
      });
    }
    setupWeeklyArticlePager();

    if (!htmlInput && !isWeekly) {
      return;
    }

    var previewAnchor = resolvePreviewAnchor(htmlInput);
    if (!previewAnchor) {
      return;
    }
    var htmlFieldContainer = previewAnchor.container;
    var insertBeforeNode = previewAnchor.beforeNode;
    var existingToolbars = document.querySelectorAll('[data-newsletter-preview-toolbar]');
    var toolbar = existingToolbars.length ? existingToolbars[0] : buildToolbar();
    for (var t = 1; t < existingToolbars.length; t++) {
      existingToolbars[t].remove();
    }
    var previewBtn = toolbar.querySelector('[data-preview-newsletter-campaign]');
    var statusNode = toolbar.querySelector('[data-campaign-status]');

    var existingShells = document.querySelectorAll('[data-newsletter-preview-shell]');
    var previewShell = existingShells.length ? existingShells[0] : createPreviewShell();
    for (var s = 1; s < existingShells.length; s++) {
      existingShells[s].remove();
    }
    var previewFrame = previewShell.querySelector('[data-campaign-preview-frame]');
    var previewCloseBtn = previewShell.querySelector('[data-campaign-preview-close]');

    if (toolbar.parentNode !== htmlFieldContainer || toolbar.nextSibling !== insertBeforeNode) {
      htmlFieldContainer.insertBefore(toolbar, insertBeforeNode);
    }
    if (previewShell.parentNode !== htmlFieldContainer) {
      htmlFieldContainer.insertBefore(previewShell, toolbar.nextSibling);
    }

    if (previewCloseBtn && !previewCloseBtn.dataset.bound) {
      previewCloseBtn.dataset.bound = '1';
      previewCloseBtn.addEventListener('click', function () {
        previewShell.hidden = true;
      });
    }

    if (!previewBtn.dataset.bound) {
      previewBtn.dataset.bound = '1';
      previewBtn.addEventListener('click', async function () {
      var bodyHtml = htmlInput ? htmlInput.value || '' : '';
      var templateId = (templateSelect.value || '').trim();
      var campaignType =
        campaignTypeInput && (campaignTypeInput.value || '').trim()
          ? (campaignTypeInput.value || '').trim()
          : document.querySelector('.newsletter-weekly-only')
          ? 'weekly_news'
          : 'general';
      var weeklyArticleIds = getSelectedWeeklyArticleIds();
      var weeklyItemTemplateHtml = weeklyItemTemplateInput ? weeklyItemTemplateInput.value || '' : '';
      var html = '';
      try {
        html = (await composePreviewHtml(templateId, bodyHtml, campaignType, weeklyArticleIds, weeklyItemTemplateHtml)).trim();
      } catch (err) {
        statusNode.hidden = false;
        statusNode.textContent = err.message;
        return;
      }
      if (!html) {
        statusNode.hidden = false;
        statusNode.textContent = '目前沒有可預覽的內容';
        return;
      }

      if (!openPreviewInFrame(previewFrame, previewShell, html)) {
        statusNode.hidden = false;
        statusNode.textContent = '無法顯示預覽';
        return;
      }
      statusNode.hidden = true;
      });
    }
  }

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