(function(){
  'use strict';

  const apiUrl = window.PYRK_WALK_EMAIL_API || '../../api/walk_email_templates.php';
  const csrf = window.__PYRK_CSRF__ || window.PYRK_CSRF || '';
  const state = {
    walks: [],
    catalog: {},
    variables: {},
    currentWalkId: '',
    currentTemplateKey: 'member_invitation',
    installed: true,
    isDirty: false,
  };

  const $ = (id) => document.getElementById(id);
  const els = {
    walkSelect: $('emailWalkSelect'),
    walkInfo: $('emailWalkInfo'),
    typeList: $('templateTypeList'),
    variables: $('emailVariables'),
    form: $('walkEmailTemplateForm'),
    templateKey: $('templateKey'),
    subject: $('emailSubject'),
    body: $('emailBody'),
    msg: $('walkEmailTemplateMsg'),
    title: $('templateTitle'),
    desc: $('templateDescription'),
    eyebrow: $('templateEyebrow'),
    badge: $('templateStatusBadge'),
    previewBtn: $('previewEmailTemplateBtn'),
    resetBtn: $('resetEmailTemplateBtn'),
    testEmail: $('testEmailAddress'),
    sendTestBtn: $('sendTestEmailTemplateBtn'),
    modal: $('walkEmailPreviewModal'),
    previewSubject: $('previewSubject'),
    previewFrame: $('previewFrame'),
    starterList: $('starterTemplateList'),
    editorToolbar: $('emailEditorToolbar'),
    editorPreview: $('inlineEmailPreview'),
    reloadBtn: $('reloadWalkEmailStudioBtn'),
  };

  const starters = {
    pro_invitation: {
      label: 'Premium invitation',
      subject: 'You are invited: {walk_title}',
      body: '<h2>You are invited to {walk_title}</h2>\n<p>Hi {member_name},</p>\n<p>We are pleased to invite you to join this Pyrk walk.</p>\n<div style="margin:16px 0;padding:16px;border:1px solid #e2e8f0;border-radius:14px;background:#f8fafc;">\n<strong>Walk details</strong><br>\nDate: {walk_date}<br>\nTime: {walk_time}<br>\nRoute: {route_name}<br>\nDistance: {distance_km} KM\n</div>\n{walk_description_block}\n{walk_button}\n<p>Please open the walk page to review the details, sign the waiver, and confirm your participation.</p>\n<p>See you there,<br><strong>{brand_name}</strong></p>'
    },
    friendly_invitation: {
      label: 'Friendly member invite',
      subject: 'Join us for {walk_title}',
      body: '<p>Hi {member_name},</p>\n<p>You are invited to join <strong>{walk_title}</strong>.</p>\n<p><strong>Date:</strong> {walk_date}<br>\n<strong>Time:</strong> {walk_time}<br>\n<strong>Distance:</strong> {distance_km} KM</p>\n{walk_description_block}\n<p>Tap the button below to open the walk and complete the required steps.</p>\n{walk_button}'
    },
    clean_reminder: {
      label: 'Clean reminder',
      subject: 'Reminder: {walk_title}',
      body: '<h2>Your walk is coming up</h2>\n<p>Hi {member_name},</p>\n<p>This is a friendly reminder for your registered walk.</p>\n<ul>\n<li><strong>Walk:</strong> {walk_title}</li>\n<li><strong>Date:</strong> {walk_date}</li>\n<li><strong>Time:</strong> {walk_time}</li>\n<li><strong>Route:</strong> {route_name}</li>\n</ul>\n{walk_description_block}\n<p>Please arrive 15 minutes early.</p>\n{walk_button}'
    }
  };

  const blocks = {
    details: '<div style="margin:16px 0;padding:16px;border:1px solid #e2e8f0;border-radius:14px;background:#f8fafc;">\n<strong>Walk details</strong><br>\nDate: {walk_date}<br>\nTime: {walk_time}<br>\nRoute: {route_name}<br>\nDistance: {distance_km} KM\n</div>',
    description: '{walk_description_block}',
    button: '{walk_button}',
    divider: '<hr>',
    signature: '<p>Regards,<br><strong>{brand_name}</strong></p>',
    note: '<blockquote>Important note: write your message here.</blockquote>'
  };

  function notice(message, type){
    if (!els.msg) return;
    els.msg.textContent = message || '';
    els.msg.className = 'notice ' + (type || '');
  }

  function setDirty(value){
    state.isDirty = !!value;
    if (els.badge && state.isDirty) {
      els.badge.textContent = 'Unsaved changes';
      els.badge.classList.add('dirty');
    }
    renderInlinePreview();
  }

  function escapeHtml(v){
    return String(v == null ? '' : v).replace(/[&<>"']/g, function(ch){
      return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'})[ch];
    });
  }

  function api(action, payload){
    return fetch(apiUrl, {
      method: 'POST',
      headers: {'Content-Type':'application/json', 'X-CSRF-Token': csrf},
      credentials: 'same-origin',
      body: JSON.stringify(Object.assign({action}, payload || {}))
    }).then(function(res){
      return res.text().then(function(text){
        let data = null;
        try { data = text ? JSON.parse(text) : {}; }
        catch (err) {
          const clean = String(text || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
          throw new Error(clean ? clean.slice(0, 500) : 'API did not return JSON. Check that steps/api/walk_email_templates.php was uploaded and that the API path is ../../api/walk_email_templates.php.');
        }
        if (!res.ok || !data.ok) throw new Error((data && data.message) || 'Request failed');
        return data.data || {};
      });
    });
  }

  function renderWalks(){
    if (!els.walkSelect) return;
    if (!state.walks.length) {
      els.walkSelect.innerHTML = '<option value="">No walks found</option>';
      if (els.walkInfo) els.walkInfo.innerHTML = '<strong>No walks loaded.</strong><br><span class="muted">Create a walk first, or check the API response in the browser Network tab.</span>';
      return;
    }
    els.walkSelect.innerHTML = '<option value="">Choose a walk...</option>' + state.walks.map(function(w){
      const date = w.walk_date ? ' · ' + w.walk_date : '';
      const route = w.route_name ? ' · ' + w.route_name : '';
      const status = w.status ? ' · ' + String(w.status).replace(/_/g, ' ') : '';
      return '<option value="' + Number(w.id) + '">' + escapeHtml(String(w.title || 'Walk #' + w.id) + date + route + status) + '</option>';
    }).join('');

    if (!state.currentWalkId && state.walks.length === 1) {
      state.currentWalkId = String(state.walks[0].id);
      els.walkSelect.value = state.currentWalkId;
      updateWalkInfo();
      loadTemplate();
    }
  }

  function renderTypes(){
    const keys = Object.keys(state.catalog || {});
    if (!els.typeList) return;
    els.typeList.innerHTML = keys.map(function(key){
      const item = state.catalog[key] || {};
      const active = key === state.currentTemplateKey ? ' active' : '';
      return '<button type="button" class="template-type-btn' + active + '" data-template-key="' + escapeHtml(key) + '"><strong>' + escapeHtml(item.label || key) + '</strong><small>' + escapeHtml(item.description || '') + '</small></button>';
    }).join('') || '<p class="muted small">No template types returned from API.</p>';
  }

  function renderVariables(){
    const vars = state.variables || {};
    if (!els.variables) return;
    els.variables.innerHTML = Object.keys(vars).map(function(key){
      return '<button type="button" class="email-variable-chip" data-copy-var="' + escapeHtml(key) + '"><code>' + escapeHtml(key) + '</code><span>' + escapeHtml(vars[key]) + '</span></button>';
    }).join('') || '<p class="muted small">No variables available.</p>';
  }

  function renderStarters(){
    if (!els.starterList) return;
    els.starterList.innerHTML = Object.keys(starters).map(function(key){
      const item = starters[key];
      return '<button type="button" class="starter-card" data-starter="' + escapeHtml(key) + '"><span>Demo</span><strong>' + escapeHtml(item.label) + '</strong><small>Load professional sample content</small></button>';
    }).join('');
  }

  function selectedWalk(){
    const id = Number(state.currentWalkId || 0);
    return state.walks.find(function(w){ return Number(w.id) === id; }) || null;
  }

  function updateWalkInfo(){
    const w = selectedWalk();
    if (!els.walkInfo) return;
    if (!w) {
      els.walkInfo.textContent = 'Select a walk to edit its email content.';
      return;
    }
    const time = String(w.start_time || '').slice(0,5) + (w.expected_finish_time ? '–' + String(w.expected_finish_time).slice(0,5) : '');
    els.walkInfo.innerHTML = '<strong>' + escapeHtml(w.title || 'Walk') + '</strong><br>' + escapeHtml((w.walk_date || '') + ' ' + time) + '<br>' + escapeHtml(w.route_name || 'Route not linked') + '<div class="walk-email-mini-pills"><span>' + escapeHtml(w.status || 'status') + '</span><span>' + escapeHtml(w.access_type || 'access') + '</span><span>' + escapeHtml(w.payment_model || 'payment') + '</span></div>';
  }

  function setLoading(isLoading){
    [els.subject, els.body, els.previewBtn, els.resetBtn, els.sendTestBtn].forEach(function(el){ if(el) el.disabled = !!isLoading; });
  }

  function loadTemplate(){
    notice('');
    const walkId = Number(state.currentWalkId || 0);
    if (!walkId) {
      if (els.subject) els.subject.value = '';
      if (els.body) els.body.value = '';
      if (els.title) els.title.textContent = 'Email editor';
      if (els.desc) els.desc.textContent = 'Choose a walk and email type.';
      if (els.badge) { els.badge.textContent = 'Default'; els.badge.className = 'template-status-badge'; }
      renderInlinePreview();
      return;
    }
    setLoading(true);
    api('get', {walk_id: walkId, template_key: state.currentTemplateKey}).then(function(data){
      const t = data.template || {};
      els.templateKey.value = state.currentTemplateKey;
      els.subject.value = t.subject || '';
      els.body.value = t.body_html || '';
      els.title.textContent = t.label || 'Email editor';
      els.desc.textContent = t.description || '';
      els.eyebrow.textContent = 'Step 2';
      els.badge.textContent = t.is_custom ? 'Custom content' : 'Default content';
      els.badge.className = 'template-status-badge' + (t.is_custom ? ' custom' : '');
      state.isDirty = false;
      renderInlinePreview();
    }).catch(function(err){ notice(err.message, 'error'); }).finally(function(){ setLoading(false); });
  }

  function saveTemplate(ev){
    ev.preventDefault();
    const walkId = Number(state.currentWalkId || 0);
    if (!walkId) { notice('Choose a walk first.', 'error'); return; }
    setLoading(true);
    api('save', {
      walk_id: walkId,
      template_key: state.currentTemplateKey,
      subject: els.subject.value,
      body_html: els.body.value
    }).then(function(data){
      notice('Saved. Future emails for this walk will use this content.', 'success');
      const t = data.template || {};
      els.badge.textContent = t.is_custom ? 'Custom content' : 'Default content';
      els.badge.className = 'template-status-badge' + (t.is_custom ? ' custom' : '');
      state.isDirty = false;
    }).catch(function(err){ notice(err.message, 'error'); }).finally(function(){ setLoading(false); });
  }

  function resetTemplate(){
    const walkId = Number(state.currentWalkId || 0);
    if (!walkId) { notice('Choose a walk first.', 'error'); return; }
    if (!confirm('Restore the default content for this walk email?')) return;
    setLoading(true);
    api('reset', {walk_id: walkId, template_key: state.currentTemplateKey}).then(function(data){
      const t = data.template || {};
      els.subject.value = t.subject || '';
      els.body.value = t.body_html || '';
      els.badge.textContent = 'Default content';
      els.badge.className = 'template-status-badge';
      state.isDirty = false;
      renderInlinePreview();
      notice('Default content restored.', 'success');
    }).catch(function(err){ notice(err.message, 'error'); }).finally(function(){ setLoading(false); });
  }

  function previewTemplate(){
    const walkId = Number(state.currentWalkId || 0);
    if (!walkId) { notice('Choose a walk first.', 'error'); return; }
    api('preview', {walk_id: walkId, template_key: state.currentTemplateKey, subject: els.subject.value, body_html: els.body.value}).then(function(data){
      const p = data.preview || {};
      els.previewSubject.textContent = p.subject || 'Preview';
      els.previewFrame.srcdoc = emailPreviewDocument(p.html || '');
      els.modal.hidden = false;
    }).catch(function(err){ notice(err.message, 'error'); });
  }

  function sendTest(){
    const walkId = Number(state.currentWalkId || 0);
    if (!walkId) { notice('Choose a walk first.', 'error'); return; }
    setLoading(true);
    api('send_test', {walk_id: walkId, template_key: state.currentTemplateKey, to_email: els.testEmail.value, subject: els.subject.value, body_html: els.body.value}).then(function(){
      notice('Test email processed using the current editor content.', 'success');
    }).catch(function(err){ notice(err.message, 'error'); }).finally(function(){ setLoading(false); });
  }

  function insertIntoBody(text){
    if (!els.body) return;
    const start = els.body.selectionStart || els.body.value.length;
    const end = els.body.selectionEnd || start;
    const before = els.body.value.slice(0, start);
    const after = els.body.value.slice(end);
    const spacerBefore = before && !before.endsWith('\n') ? '\n' : '';
    const spacerAfter = after && !after.startsWith('\n') ? '\n' : '';
    els.body.value = before + spacerBefore + text + spacerAfter + after;
    els.body.focus();
    const pos = (before + spacerBefore + text).length;
    els.body.setSelectionRange(pos, pos);
    setDirty(true);
  }

  function applyStarter(key){
    const item = starters[key];
    if (!item) return;
    if ((els.subject.value || els.body.value) && !confirm('Replace the current editor content with this demo template?')) return;
    els.subject.value = item.subject;
    els.body.value = item.body;
    setDirty(true);
    notice('Demo content loaded. Review it, then save it for this walk.', 'success');
  }

  function emailPreviewDocument(html){
    return '<!doctype html><html><head><meta charset="utf-8"><style>body{font-family:Arial,sans-serif;background:#f8fafc;margin:0;padding:24px;color:#0f172a;line-height:1.55}.mail{max-width:680px;margin:0 auto;background:#fff;border:1px solid #e2e8f0;border-radius:22px;padding:26px;box-shadow:0 24px 60px rgba(15,23,42,.12)}a{color:#0f766e}</style></head><body><div class="mail">' + html + '</div></body></html>';
  }

  function renderInlinePreview(){
    if (!els.editorPreview) return;
    const localHtml = String(els.body && els.body.value ? els.body.value : '')
      .replaceAll('{member_name}', 'Sample Member')
      .replaceAll('{member_email}', 'member@example.com')
      .replaceAll('{walk_title}', selectedWalk()?.title || 'Selected walk')
      .replaceAll('{walk_date}', selectedWalk()?.walk_date || 'Walk date')
      .replaceAll('{walk_time}', (String(selectedWalk()?.start_time || '19:00').slice(0,5)) + '–' + (String(selectedWalk()?.expected_finish_time || '20:00').slice(0,5)))
      .replaceAll('{route_name}', selectedWalk()?.route_name || 'Route name')
      .replaceAll('{distance_km}', '5.0')
      .replaceAll('{brand_name}', 'Pyrk')
      .replaceAll('{walk_description}', 'Sample walk description')
      .replaceAll('{walk_description_block}', '<div style="margin:12px 0;padding:12px;border:1px solid #e2e8f0;border-radius:12px;background:#f8fafc;"><strong>Walk note</strong><br>Sample walk description shown here.</div>')
      .replaceAll('{walk_link}', '#')
      .replaceAll('{walk_button}', '<p><a href="#" style="display:inline-block;background:#1c7c54;color:#fff;text-decoration:none;padding:12px 18px;border-radius:12px;font-weight:bold;">Open walk</a></p>');
    els.editorPreview.srcdoc = emailPreviewDocument(localHtml || '<p class="muted">Start writing to preview the email.</p>');
  }

  function init(){
    renderStarters();
    api('overview').then(function(data){
      state.walks = data.walks || [];
      state.catalog = data.catalog || {};
      state.variables = data.variables || {};
      state.installed = !!data.installed;
      renderWalks();
      renderTypes();
      renderVariables();
      if (!state.installed) notice('Run run_this_sql_walk_email_templates.sql before saving custom content. Walks can still be previewed.', 'error');
    }).catch(function(err){
      if (els.walkSelect) els.walkSelect.innerHTML = '<option value="">Walks failed to load</option>';
      notice('Walks not loading: ' + err.message, 'error');
    });

    els.walkSelect && els.walkSelect.addEventListener('change', function(){
      state.currentWalkId = this.value;
      updateWalkInfo();
      loadTemplate();
    });
    els.typeList && els.typeList.addEventListener('click', function(ev){
      const btn = ev.target.closest('[data-template-key]');
      if (!btn) return;
      if (state.isDirty && !confirm('You have unsaved changes. Switch email type anyway?')) return;
      state.currentTemplateKey = btn.dataset.templateKey;
      renderTypes();
      loadTemplate();
    });
    els.variables && els.variables.addEventListener('click', function(ev){
      const btn = ev.target.closest('[data-copy-var]');
      if (!btn) return;
      insertIntoBody(btn.dataset.copyVar);
      navigator.clipboard && navigator.clipboard.writeText(btn.dataset.copyVar).catch(function(){});
    });
    els.starterList && els.starterList.addEventListener('click', function(ev){
      const btn = ev.target.closest('[data-starter]');
      if (btn) applyStarter(btn.dataset.starter);
    });
    els.editorToolbar && els.editorToolbar.addEventListener('click', function(ev){
      const btn = ev.target.closest('[data-block]');
      if (!btn) return;
      insertIntoBody(blocks[btn.dataset.block] || '');
    });
    els.form && els.form.addEventListener('submit', saveTemplate);
    els.resetBtn && els.resetBtn.addEventListener('click', resetTemplate);
    els.previewBtn && els.previewBtn.addEventListener('click', previewTemplate);
    els.sendTestBtn && els.sendTestBtn.addEventListener('click', sendTest);
    els.subject && els.subject.addEventListener('input', function(){ setDirty(true); });
    els.body && els.body.addEventListener('input', function(){ setDirty(true); });
    els.reloadBtn && els.reloadBtn.addEventListener('click', function(){ window.location.reload(); });
    document.querySelectorAll('[data-close-email-preview]').forEach(function(btn){ btn.addEventListener('click', function(){ els.modal.hidden = true; }); });
    els.modal && els.modal.addEventListener('click', function(ev){ if (ev.target === els.modal) els.modal.hidden = true; });
    renderInlinePreview();
  }

  document.addEventListener('DOMContentLoaded', init);
})();
