(function(){
  'use strict';

  const apiUrl = window.PYRK_WHATSAPP_PRESETS_API || '../../api/whatsapp_presets.php';
  const csrf = window.__PYRK_CSRF__ || window.PYRK_CSRF || '';
  const state = { presets: [], useCases: {}, variables: {}, installed: true, selectedId: 0 };
  const $ = id => document.getElementById(id);
  const els = {
    list: $('whatsappPresetList'), count: $('whatsappPresetCount'), search: $('whatsappPresetSearch'), status: $('whatsappPresetStatusFilter'),
    form: $('whatsappPresetForm'), id: $('whatsappPresetId'), name: $('whatsappPresetName'), useCase: $('whatsappPresetUseCase'), audience: $('whatsappPresetAudience'),
    sort: $('whatsappPresetSort'), active: $('whatsappPresetActive'), isDefault: $('whatsappPresetDefault'), headline: $('whatsappPresetHeadline'), message: $('whatsappPresetMessage'),
    variables: $('whatsappPresetVariables'), preview: $('whatsappPresetPreview'), counter: $('whatsappPresetCharacterCount'), notice: $('whatsappPresetMessageNotice'),
    state: $('whatsappPresetEditorState'), eyebrow: $('whatsappPresetEditorEyebrow'), title: $('whatsappPresetEditorTitle'), deleteBtn: $('deleteWhatsAppPresetBtn'),
    newBtn: $('newWhatsAppPresetBtn'), clearBtn: $('clearWhatsAppPresetBtn'), reloadBtn: $('reloadWhatsAppPresetsBtn'), install: $('whatsappPresetInstallWarning'), saveBtn: $('saveWhatsAppPresetBtn')
  };

  const sample = {
    '{first_name}':'Alex','{last_name}':'Walker','{full_name}':'Alex Walker','{walk_title}':'Beirut Sunrise Walk',
    '{walk_date}':'21/07/2026','{walk_time}':'07:00','{route_name}':'Pyrk Waterfront Route','{distance_km}':'6.4',
    '{walk_link}':'https://thepyrk.com/steps/public/walk.php?id=123'
  };
  Object.keys(sample).forEach(token => { sample['$' + token.replace(/[{}]/g, '') + '$'] = sample[token]; });

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

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

  async function api(action, payload){
    const response = await fetch(apiUrl, {
      method:'POST', credentials:'same-origin',
      headers:{'Content-Type':'application/json','X-CSRF-Token':csrf},
      body:JSON.stringify(Object.assign({action}, payload || {}))
    });
    const text = await response.text();
    let json;
    try { json = text ? JSON.parse(text) : {}; }
    catch (e) { throw new Error(String(text || 'API did not return JSON.').replace(/<[^>]+>/g,' ').replace(/\s+/g,' ').trim().slice(0,500)); }
    if (!response.ok || !json.ok) throw new Error(json.message || 'Request failed.');
    return json.data || {};
  }

  function useCaseLabel(key){ return state.useCases[key] || key.replace(/_/g,' '); }

  function renderUseCases(){
    els.useCase.innerHTML = Object.entries(state.useCases).map(([key,label]) => `<option value="${escapeHtml(key)}">${escapeHtml(label)}</option>`).join('');
    if (!els.useCase.value) els.useCase.value = 'custom';
  }

  function renderVariables(){
    els.variables.innerHTML = Object.entries(state.variables).map(([token,label]) => `<button type="button" data-token="${escapeHtml(token)}" title="${escapeHtml(label)}">${escapeHtml(token)}</button>`).join('');
    els.variables.querySelectorAll('[data-token]').forEach(btn => btn.addEventListener('click', () => insertToken(btn.dataset.token || '')));
  }

  function filteredPresets(){
    const q = String(els.search.value || '').trim().toLowerCase();
    const status = els.status.value || 'all';
    return state.presets.filter(p => {
      if (status === 'active' && Number(p.is_active) !== 1) return false;
      if (status === 'inactive' && Number(p.is_active) === 1) return false;
      const hay = `${p.preset_name || ''} ${p.use_case || ''} ${p.headline_template || ''}`.toLowerCase();
      return !q || hay.includes(q);
    });
  }

  function renderList(){
    const rows = filteredPresets();
    els.count.textContent = String(state.presets.length);
    els.list.innerHTML = rows.map(p => {
      const selected = Number(p.id) === Number(state.selectedId);
      return `<button type="button" class="preset-list-card ${selected ? 'is-selected' : ''} ${Number(p.is_active) === 1 ? '' : 'is-inactive'}" data-preset-id="${Number(p.id)}">
        <span class="preset-list-copy">
          <strong>${escapeHtml(p.preset_name || 'Unnamed preset')}</strong>
          <small>${escapeHtml(p.headline_template || '')}</small>
          <span class="preset-list-badges">
            <span class="preset-mini-badge">${escapeHtml(useCaseLabel(p.use_case || 'custom'))}</span>
            ${Number(p.is_default) === 1 ? '<span class="preset-mini-badge default">Default</span>' : ''}
            ${Number(p.is_active) !== 1 ? '<span class="preset-mini-badge inactive">Inactive</span>' : ''}
          </span>
        </span><span class="preset-list-arrow">›</span>
      </button>`;
    }).join('') || '<div class="preset-empty">No presets match this filter.</div>';
    els.list.querySelectorAll('[data-preset-id]').forEach(btn => btn.addEventListener('click', () => editPreset(Number(btn.dataset.presetId))));
  }

  function replaceSample(text){
    let result = String(text || '');
    Object.entries(sample).forEach(([token,value]) => { result = result.split(token).join(value); });
    return result;
  }

  function formatPreview(text){
    const escaped = escapeHtml(text);
    return escaped.replace(/\*([^*\n]+)\*/g,'<strong>$1</strong>');
  }

  function renderPreview(){
    const headline = replaceSample(els.headline.value).replace(/\*/g,'').trim();
    const body = replaceSample(els.message.value).trim();
    const full = `${headline ? '*' + headline + '*\n\n' : ''}${body}`.trim();
    els.preview.innerHTML = full ? formatPreview(full) : 'Start typing to preview the message.';
    els.counter.textContent = `${els.message.value.length} / 4000 characters`;
  }

  function insertToken(token){
    const target = document.activeElement === els.headline ? els.headline : els.message;
    const start = Number.isInteger(target.selectionStart) ? target.selectionStart : target.value.length;
    const end = Number.isInteger(target.selectionEnd) ? target.selectionEnd : start;
    target.value = target.value.slice(0,start) + token + target.value.slice(end);
    const caret = start + token.length;
    target.focus(); target.setSelectionRange(caret,caret); renderPreview();
  }

  function clearEditor(){
    state.selectedId = 0;
    els.form.reset();
    els.id.value = '';
    els.useCase.value = 'custom';
    els.audience.value = 'auto';
    els.sort.value = '100';
    els.active.checked = true;
    els.isDefault.checked = false;
    els.deleteBtn.hidden = true;
    els.state.textContent = 'New';
    els.eyebrow.textContent = 'Create';
    els.title.textContent = 'New WhatsApp preset';
    notice(''); renderPreview(); renderList();
    els.name.focus();
  }

  function editPreset(id){
    const p = state.presets.find(row => Number(row.id) === Number(id));
    if (!p) return;
    state.selectedId = Number(p.id);
    els.id.value = String(p.id);
    els.name.value = p.preset_name || '';
    els.useCase.value = p.use_case || 'custom';
    els.audience.value = p.audience_default || 'auto';
    els.sort.value = String(Number(p.sort_order || 100));
    els.active.checked = Number(p.is_active) === 1;
    els.isDefault.checked = Number(p.is_default) === 1;
    els.headline.value = p.headline_template || '';
    els.message.value = p.message_template || '';
    els.deleteBtn.hidden = false;
    els.state.textContent = Number(p.is_active) === 1 ? 'Active' : 'Inactive';
    els.eyebrow.textContent = 'Edit';
    els.title.textContent = p.preset_name || 'Edit preset';
    notice(''); renderPreview(); renderList();
    els.form.scrollIntoView({behavior:'smooth',block:'start'});
  }

  async function load(){
    notice('Loading presets…');
    try {
      const data = await api('overview');
      state.installed = Number(data.installed) === 1;
      state.presets = data.presets || [];
      state.useCases = data.use_cases || {};
      state.variables = data.variables || {};
      els.install.hidden = state.installed;
      els.saveBtn.disabled = !state.installed;
      renderUseCases(); renderVariables(); renderList();
      notice(state.installed ? '' : 'Import the migration before creating presets.', state.installed ? '' : 'error');
    } catch (e) { notice(e.message, 'error'); }
  }

  els.form.addEventListener('submit', async event => {
    event.preventDefault();
    if (!state.installed) return;
    const payload = {
      id:Number(els.id.value || 0), preset_name:els.name.value, use_case:els.useCase.value,
      audience_default:els.audience.value, sort_order:Number(els.sort.value || 100),
      is_active:els.active.checked ? 1 : 0, is_default:els.isDefault.checked ? 1 : 0,
      headline_template:els.headline.value, message_template:els.message.value
    };
    els.saveBtn.disabled = true; notice('Saving preset…');
    try {
      const data = await api('save', payload);
      state.presets = data.presets || state.presets;
      const saved = data.preset || null;
      notice('WhatsApp preset saved.', 'success');
      if (saved) editPreset(Number(saved.id)); else renderList();
    } catch (e) { notice(e.message, 'error'); }
    finally { els.saveBtn.disabled = false; }
  });

  els.deleteBtn.addEventListener('click', async () => {
    const id = Number(els.id.value || 0);
    const p = state.presets.find(row => Number(row.id) === id);
    if (!id || !p) return;
    if (!window.confirm(`Delete the preset “${p.preset_name}”? Existing sent and queued messages will not be changed.`)) return;
    els.deleteBtn.disabled = true; notice('Deleting preset…');
    try {
      const data = await api('delete', {id});
      state.presets = data.presets || [];
      clearEditor(); notice('WhatsApp preset deleted.', 'success');
    } catch (e) { notice(e.message, 'error'); }
    finally { els.deleteBtn.disabled = false; }
  });

  [els.headline,els.message].forEach(el => el.addEventListener('input', renderPreview));
  els.search.addEventListener('input', renderList);
  els.status.addEventListener('change', renderList);
  els.newBtn.addEventListener('click', clearEditor);
  els.clearBtn.addEventListener('click', clearEditor);
  els.reloadBtn.addEventListener('click', load);
  els.active.addEventListener('change', () => { if (!els.active.checked) els.isDefault.checked = false; });
  els.isDefault.addEventListener('change', () => { if (els.isDefault.checked) els.active.checked = true; });

  clearEditor(); load();
})();
