document.querySelectorAll('form').forEach((form) => {
  form.addEventListener('submit', () => {
    const btn = form.querySelector('button[type="submit"],button:not([type])');
    if (btn) {
      btn.disabled = true;
      btn.dataset.originalText = btn.textContent;
      btn.textContent = 'Processing...';
    }
  });
});

(function () {
  document.querySelectorAll('.template-picker').forEach((sel) => {
    sel.addEventListener('change', function () {
      const opt = this.options[this.selectedIndex];
      const bodyTarget = this.dataset.targetBody ? document.getElementById(this.dataset.targetBody) : null;
      const subjectTarget = this.dataset.targetSubject ? document.getElementById(this.dataset.targetSubject) : null;
      if (bodyTarget && opt && opt.dataset.body) bodyTarget.value = opt.dataset.body;
      if (subjectTarget && opt && opt.dataset.subject) subjectTarget.value = opt.dataset.subject;
    });
  });
})();

(function () {
  const templates = window.__TEMPLATES__ || [];
  const context = window.__CAMPAIGN_CONTEXT__ || {};
  const select = document.getElementById('campaign-template');
  const channel = document.getElementById('campaign-channel');
  const subjectInput = document.getElementById('campaign-subject');
  const bodyInput = document.getElementById('campaign-body');
  const preview = document.getElementById('campaign-preview');
  const canvas = document.getElementById('builder-canvas');
  const builderJsonInput = document.getElementById('campaign-builder-json');
  const preflightSummary = document.getElementById('campaign-preflight-summary');
  const preflightList = document.getElementById('campaign-preflight-list');
  const listSelect = document.getElementById('campaign-contact-list');
  const segmentSelect = document.querySelector('[name="segment_id"]');
  const filterInput = document.querySelector('[name="recipient_filter"]');
  if (!select || !channel || !preview || !canvas || !builderJsonInput) return;

  const sample = {
    first_name: 'Avery',
    last_name: 'Jordan',
    company: 'Northwind Health',
    email: 'avery@example.com',
    phone: '+15555551212',
    unsubscribe_url: 'https://example.com/unsubscribe'
  };

  const defaults = {
    hero: '<table role="presentation" width="100%"><tr><td style="padding:28px;border-radius:16px;background:#12395b;color:#ffffff;"><div style="font-size:28px;font-weight:700;margin-bottom:8px;">Commercial campaign launch</div><div style="font-size:15px;line-height:1.6;">Hi {{first_name}}, here is the latest update for {{company}}.</div></td></tr></table>',
    heading: '<h2>{{first_name}}, important update</h2>',
    text: '<p>We have a new message for {{company}}. Use this section for body copy, offer details, and next steps.</p>',
    image: '<p><img src="https://via.placeholder.com/640x240" alt="Campaign visual" style="max-width:100%;border-radius:14px;"></p>',
    cta: '<p><a href="https://example.com" style="display:inline-block;padding:12px 18px;border-radius:999px;background:#1f5b92;color:#ffffff;text-decoration:none;">Review details</a></p>',
    divider: '<hr style="border:none;border-top:1px solid #d8e1ec;margin:24px 0;">',
    spacer: '<div style="height:24px;"></div>'
  };

  let blocks = [];
  let draggedIndex = null;

  const pickedTemplate = () => templates.find((t) => Number(t.id) === Number(select.value || 0));

  const interpolate = (text) => String(text || '')
    .replaceAll('{{first_name}}', sample.first_name)
    .replaceAll('{{last_name}}', sample.last_name)
    .replaceAll('{{company}}', sample.company)
    .replaceAll('{{email}}', sample.email)
    .replaceAll('{{phone}}', sample.phone)
    .replaceAll('{{unsubscribe_url}}', sample.unsubscribe_url);

  const bodyFromBlocks = () => blocks.map((block) => block.html || '').filter(Boolean).join('\n\n');

  const summaryAudience = () => {
    const listText = listSelect && listSelect.value ? listSelect.options[listSelect.selectedIndex].text : '';
    if (listText) return listText;
    if (segmentSelect && segmentSelect.value) return 'Saved segment';
    if (filterInput && filterInput.value.trim()) return `Tag filter: ${filterInput.value.trim()}`;
    return `All reachable ${channel.value.toUpperCase()} contacts`;
  };

  const variantCount = () => {
    const hasA = !!(document.querySelector('[name="variant_a_subject"]')?.value.trim() || document.querySelector('[name="variant_a_body"]')?.value.trim());
    const hasB = !!(document.querySelector('[name="variant_b_subject"]')?.value.trim() || document.querySelector('[name="variant_b_body"]')?.value.trim());
    return 1 + (hasA ? 1 : 0) + (hasB ? 1 : 0);
  };

  const syncBuilder = () => {
    builderJsonInput.value = JSON.stringify(blocks);
    if (blocks.length) {
      bodyInput.value = bodyFromBlocks();
    }
    renderPreview();
    renderPreflight();
  };

  const renderBlocks = () => {
    canvas.innerHTML = '';
    if (!blocks.length) {
      canvas.innerHTML = '<div class="builder-empty muted">Drop builder blocks here or start from a template.</div>';
      return;
    }
    blocks.forEach((block, index) => {
      const card = document.createElement('div');
      card.className = 'builder-block';
      card.draggable = true;
      card.dataset.index = String(index);
      card.innerHTML = `
        <div class="builder-block-head">
          <div class="builder-block-title"><span class="drag-handle">↕</span> <strong>${String(block.type || 'text').toUpperCase()}</strong></div>
          <button type="button" class="btn danger small">Remove</button>
        </div>
        <textarea rows="5">${block.html || ''}</textarea>
      `;
      const textarea = card.querySelector('textarea');
      textarea.addEventListener('input', () => {
        blocks[index].html = textarea.value;
        syncBuilder();
      });
      card.querySelector('button').addEventListener('click', () => {
        blocks.splice(index, 1);
        renderBlocks();
        syncBuilder();
      });
      card.addEventListener('dragstart', () => {
        draggedIndex = index;
        card.classList.add('dragging');
      });
      card.addEventListener('dragend', () => {
        draggedIndex = null;
        card.classList.remove('dragging');
      });
      card.addEventListener('dragover', (event) => {
        event.preventDefault();
        card.classList.add('drag-over');
      });
      card.addEventListener('dragleave', () => card.classList.remove('drag-over'));
      card.addEventListener('drop', (event) => {
        event.preventDefault();
        card.classList.remove('drag-over');
        if (draggedIndex === null || draggedIndex === index) return;
        const moved = blocks.splice(draggedIndex, 1)[0];
        blocks.splice(index, 0, moved);
        renderBlocks();
        syncBuilder();
      });
      canvas.appendChild(card);
    });
  };

  const addBlock = (type) => {
    blocks.push({ type, html: defaults[type] || defaults.text });
    renderBlocks();
    syncBuilder();
  };

  const renderPreview = () => {
    const picked = pickedTemplate();
    const rawBody = blocks.length ? bodyFromBlocks() : (bodyInput.value.trim() || picked?.body || 'Choose a template or add builder blocks to preview the campaign body here.');
    const rawSubject = subjectInput.value.trim() || picked?.subject || '';
    preview.innerHTML = '';
    const meta = document.createElement('div');
    meta.className = 'small muted';
    if (picked) {
      meta.textContent = picked.type === channel.value
        ? `Matched ${picked.type.toUpperCase()} template`
        : `Template type mismatch: ${picked.type.toUpperCase()} selected`;
    } else {
      meta.textContent = blocks.length ? 'Builder content preview' : 'No template selected';
    }
    preview.appendChild(meta);
    if (channel.value === 'email' && rawSubject) {
      const s = document.createElement('div');
      s.className = 'preview-subject';
      s.textContent = 'Subject: ' + interpolate(rawSubject);
      preview.appendChild(s);
    }
    const body = document.createElement('div');
    body.className = 'preview-inner';
    body.innerHTML = interpolate(rawBody);
    preview.appendChild(body);
  };

  const renderPreflight = () => {
    if (!preflightList || !preflightSummary) return;
    const picked = pickedTemplate();
    const body = blocks.length ? bodyFromBlocks() : (bodyInput.value.trim() || picked?.body || '');
    const subject = subjectInput.value.trim() || picked?.subject || '';
    const providerStatus = context.providerStatus || {};
    const listChannel = listSelect && listSelect.value ? listSelect.options[listSelect.selectedIndex].dataset.channel || 'both' : 'both';
    const checks = [];

    const pushCheck = (status, label, detail) => checks.push({ status, label, detail });

    if (channel.value === 'email') {
      pushCheck(providerStatus.smtp?.configured ? 'pass' : 'error', 'Provider readiness', providerStatus.smtp?.configured ? 'SMTP ready' : 'SMTP missing');
      pushCheck(subject ? 'pass' : 'error', 'Subject line', subject ? 'Subject ready' : 'Missing subject');
    } else {
      pushCheck(providerStatus.twilio?.configured ? 'pass' : 'error', 'Provider readiness', providerStatus.twilio?.configured ? 'Twilio ready' : 'Twilio missing');
      pushCheck('pass', 'Subject line', 'Not required for SMS');
    }

    pushCheck(body.replace(/<[^>]*>/g, '').trim() ? 'pass' : 'error', 'Content', blocks.length ? `${blocks.length} builder blocks ready` : (body ? 'Raw editor content ready' : 'No content detected'));

    if (picked) {
      pushCheck(picked.type === channel.value ? 'pass' : 'warn', 'Template match', picked.type === channel.value ? 'Template matches channel' : `${picked.type.toUpperCase()} template selected on ${channel.value.toUpperCase()} campaign`);
    }

    if (listSelect && listSelect.value) {
      pushCheck(listChannel === 'both' || listChannel === channel.value ? 'pass' : 'error', 'Audience source', listSelect.options[listSelect.selectedIndex].text);
    } else {
      pushCheck('pass', 'Audience source', summaryAudience());
    }

    if (channel.value === 'email') {
      const hasUnsubscribe = body.includes('{{unsubscribe_url}}') || /unsubscribe/i.test(body);
      pushCheck(hasUnsubscribe ? 'pass' : 'warn', 'Unsubscribe footer', hasUnsubscribe ? 'Detected' : 'Add unsubscribe language or token');
    }

    if (Number(context.systemHealth?.bounceRate || 0) >= 3) {
      pushCheck('warn', 'Recent bounce rate', `${Number(context.systemHealth.bounceRate).toFixed(1)}% system bounce rate`);
    }
    if (Number(context.systemHealth?.queuePressure || 0) >= 20) {
      pushCheck('warn', 'Queue pressure', `${Number(context.systemHealth.queuePressure).toFixed(1)}% queued backlog`);
    }

    preflightSummary.textContent = `${summaryAudience()} · ${blocks.length} builder blocks · ${variantCount()} variants`;
    preflightList.innerHTML = '';
    checks.forEach((check) => {
      const row = document.createElement('div');
      row.className = `preflight-row status-${check.status}`;
      row.innerHTML = `<strong>${check.label}</strong><span>${check.detail}</span>`;
      preflightList.appendChild(row);
    });
  };

  document.querySelectorAll('.builder-add').forEach((button) => {
    button.addEventListener('click', () => addBlock(button.dataset.block || 'text'));
  });

  [select, channel, subjectInput, bodyInput, listSelect, segmentSelect, filterInput].filter(Boolean).forEach((el) => {
    el.addEventListener('input', () => {
      renderPreview();
      renderPreflight();
    });
    el.addEventListener('change', () => {
      const picked = pickedTemplate();
      if (picked && subjectInput && !subjectInput.value.trim() && picked.subject && channel.value === 'email') {
        subjectInput.value = picked.subject;
      }
      if (picked && !blocks.length && bodyInput && !bodyInput.value.trim() && picked.body) {
        bodyInput.value = picked.body;
      }
      renderPreview();
      renderPreflight();
    });
  });

  document.querySelectorAll('[name="variant_a_subject"],[name="variant_a_body"],[name="variant_b_subject"],[name="variant_b_body"],[name="ab_enabled"]').forEach((el) => {
    el.addEventListener('input', renderPreflight);
    el.addEventListener('change', renderPreflight);
  });

  renderBlocks();
  renderPreview();
  renderPreflight();
})();

(function () {
  document.querySelectorAll('.mini-chart').forEach((node) => {
    let series = [];
    try {
      series = JSON.parse(node.dataset.series || '[]');
    } catch (e) {
      series = [];
    }
    if (!Array.isArray(series) || !series.length) {
      node.innerHTML = '<div class="muted">No recent data.</div>';
      return;
    }
    const keys = (node.dataset.keys || 'delivered_count,unique_open_count,unique_click_count,bounced_count')
      .split(',')
      .map((key) => key.trim())
      .filter(Boolean);
    const names = (node.dataset.names || '')
      .split('|')
      .map((name) => name.trim())
      .filter(Boolean);
    const labelKey = node.dataset.labelKey || 'day';
    const max = Math.max(1, ...series.map((item) => Math.max(...keys.map((key) => Number(item[key] || 0)))));
    const wrap = document.createElement('div');
    wrap.className = 'chart-bars';

    const formatLabel = (value) => {
      const text = String(value || '');
      if (/^\d{4}-\d{2}-\d{2}/.test(text)) return text.slice(5);
      return text.length > 12 ? `${text.slice(0, 10)}…` : text;
    };

    series.forEach((item) => {
      const group = document.createElement('div');
      group.className = `chart-group chart-group-${Math.max(1, keys.length)}`;
      keys.forEach((key) => {
        const bar = document.createElement('div');
        bar.className = `bar ${key}`;
        bar.style.height = `${Math.max(8, (Number(item[key] || 0) / max) * 120)}px`;
        bar.title = `${key}: ${item[key] || 0}`;
        group.appendChild(bar);
      });
      const label = document.createElement('div');
      label.className = 'chart-label';
      label.textContent = formatLabel(item[labelKey]);
      group.appendChild(label);
      wrap.appendChild(group);
    });

    const legend = document.createElement('div');
    legend.className = 'chart-legend';
    legend.innerHTML = keys.map((key, index) => `<span><i class="legend-chip ${key}"></i>${names[index] || key.replaceAll('_', ' ')}</span>`).join('');
    node.innerHTML = '';
    node.appendChild(wrap);
    node.appendChild(legend);
  });
})();


(function () {
  document.querySelectorAll('.js-page-slider').forEach((slider) => {
    const root = slider.closest('.page-slider');
    const valueNode = root ? root.querySelector('[data-slider-value]') : null;

    const update = () => {
      if (valueNode) valueNode.textContent = slider.value;
    };

    slider.addEventListener('input', update);
    slider.addEventListener('change', () => {
      const base = slider.dataset.pageBase || '';
      if (!base) return;
      window.location.href = `${base}${slider.value}`;
    });

    update();
  });
})();

(function () {
  document.querySelectorAll('.js-page-slider').forEach((slider) => {
    const root = slider.closest('.page-slider');
    const valueNode = root ? root.querySelector('[data-slider-value]') : null;
    const pageTemplate = slider.dataset.pageTemplate || '';
    const pageBase = slider.dataset.pageBase || '';

    const update = () => {
      if (valueNode) valueNode.textContent = slider.value;
    };

    slider.addEventListener('input', update);
    slider.addEventListener('change', () => {
      if (pageTemplate) {
        window.location.href = pageTemplate.replace('__PAGE__', slider.value);
        return;
      }
      if (pageBase) {
        window.location.href = `${pageBase}${slider.value}`;
      }
    });

    update();
  });
})();

(function () {
  const drawer = document.getElementById('mail-compose-drawer');
  if (!drawer) return;
  const open = () => {
    drawer.classList.add('is-open');
    drawer.setAttribute('aria-hidden', 'false');
  };
  const close = () => {
    drawer.classList.remove('is-open');
    drawer.setAttribute('aria-hidden', 'true');
  };
  document.querySelectorAll('[data-compose-toggle="true"]').forEach((button) => button.addEventListener('click', open));
  document.querySelectorAll('[data-compose-close="true"]').forEach((button) => button.addEventListener('click', close));
  drawer.addEventListener('click', (event) => {
    if (event.target === drawer) close();
  });
})();

(function () {
  document.querySelectorAll('.js-apply-reply').forEach((button) => {
    button.addEventListener('click', () => {
      const bodyTarget = document.getElementById(button.dataset.target || '');
      const subjectTarget = document.getElementById(button.dataset.subjectTarget || '');
      if (subjectTarget && button.dataset.subject) {
        subjectTarget.value = button.dataset.subject;
        subjectTarget.dispatchEvent(new Event('input', { bubbles: true }));
      }
      if (bodyTarget) {
        bodyTarget.value = button.dataset.body || '';
        bodyTarget.dispatchEvent(new Event('input', { bubbles: true }));
      }
    });
  });
})();

(function () {
  document.querySelectorAll('.mail-autosave-form').forEach((form) => {
    const autosaveUrl = form.dataset.autosaveUrl || '';
    if (!autosaveUrl) return;
    const statusNode = form.querySelector('.mail-draft-status');
    let timer = null;
    let lastSnapshot = '';

    const setState = (state, message) => {
      form.classList.remove('is-saving', 'is-saved', 'is-error');
      if (state) form.classList.add(state);
      if (statusNode && message) statusNode.textContent = message;
    };

    const buildSnapshot = () => JSON.stringify({
      contact_id: form.querySelector('[name="contact_id"]')?.value || '',
      to_address: form.querySelector('[name="to_address"]')?.value || '',
      subject: form.querySelector('[name="subject"]')?.value || '',
      body: form.querySelector('[name="body"]')?.value || '',
      conversation_key: form.querySelector('[name="conversation_key"]')?.value || '',
      draft_type: form.querySelector('[name="draft_type"]')?.value || 'compose'
    });

    const autosave = async () => {
      const snapshot = buildSnapshot();
      if (!snapshot || snapshot === lastSnapshot) return;
      const bodyField = form.querySelector('[name="body"]');
      const subjectField = form.querySelector('[name="subject"]');
      if (!bodyField && !subjectField) return;
      setState('is-saving', 'Saving draft...');
      const payload = new FormData();
      payload.append('_csrf', form.querySelector('[name="_csrf"]')?.value || '');
      payload.append('draft_type', form.querySelector('[name="draft_type"]')?.value || 'compose');
      payload.append('conversation_key', form.querySelector('[name="conversation_key"]')?.value || '');
      payload.append('contact_id', form.querySelector('[name="contact_id"]')?.value || '');
      payload.append('to_address', form.querySelector('[name="to_address"]')?.value || '');
      payload.append('subject', form.querySelector('[name="subject"]')?.value || '');
      payload.append('body', form.querySelector('[name="body"]')?.value || '');
      try {
        const response = await fetch(autosaveUrl, {
          method: 'POST',
          body: payload,
          credentials: 'same-origin',
          headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const data = await response.json();
        if (data?.draft_id) {
          let hidden = form.querySelector('[name="draft_id"]');
          if (!hidden) {
            hidden = document.createElement('input');
            hidden.type = 'hidden';
            hidden.name = 'draft_id';
            form.appendChild(hidden);
          }
          hidden.value = data.draft_id;
        }
        lastSnapshot = snapshot;
        setState('is-saved', data?.saved_at ? `Draft saved at ${data.saved_at}` : 'Draft saved.');
      } catch (error) {
        setState('is-error', 'Draft autosave failed.');
      }
    };

    form.querySelectorAll('input[type="text"],input[type="email"],input[type="search"],input:not([type]),textarea,select').forEach((field) => {
      field.addEventListener('input', () => {
        clearTimeout(timer);
        timer = setTimeout(autosave, 900);
      });
      field.addEventListener('change', () => {
        clearTimeout(timer);
        timer = setTimeout(autosave, 200);
      });
    });
  });
})();
