<%- include('partials/header', { title: 'Templates', heading: 'Message Templates', active: '/templates' }) %>

<div class="grid lg:grid-cols-2 gap-6">
  <div class="bg-white rounded-2xl shadow p-5">
    <h2 class="font-semibold mb-3">New template</h2>
    <input id="t_name" placeholder="Template name" class="w-full rounded-lg border border-slate-300 px-3 py-2 mb-2 text-sm" />
    <textarea id="t_body" rows="6" placeholder="Hi {name}! {Welcome|Hello|Greetings} from our store."
              class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono"></textarea>
    <p class="text-xs text-slate-500 mt-1">Variables: <code>{name}</code> <code>{phone}</code> · Spintax: <code>{a|b|c}</code></p>
    <div class="flex gap-2 mt-3">
      <button onclick="saveTemplate()" class="bg-emerald-600 text-white rounded-lg px-4 py-2 text-sm">Save</button>
      <button onclick="previewTemplate()" class="bg-slate-200 rounded-lg px-4 py-2 text-sm">Preview</button>
    </div>
    <div id="preview" class="hidden mt-3 p-3 bg-slate-50 rounded-lg text-sm whitespace-pre-wrap"></div>
  </div>

  <div class="bg-white rounded-2xl shadow p-5">
    <h2 class="font-semibold mb-3">Saved templates</h2>
    <ul class="divide-y">
      <% templates.forEach((t) => { %>
        <li class="py-3">
          <div class="flex justify-between">
            <p class="font-medium"><%= t.name %></p>
            <button onclick="delTemplate(<%= t.id %>)" class="text-rose-500 text-sm hover:underline">Delete</button>
          </div>
          <p class="text-sm text-slate-500 mt-1 whitespace-pre-wrap"><%= t.body %></p>
        </li>
      <% }); %>
    </ul>
  </div>
</div>

<script>
  async function saveTemplate() {
    const body = { name: document.getElementById('t_name').value, body: document.getElementById('t_body').value };
    const r = await fetch('/templates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
    if (r.ok) location.reload(); else alert('Failed to save');
  }
  async function previewTemplate() {
    const r = await fetch('/templates/preview', { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ body: document.getElementById('t_body').value }) });
    const { preview } = await r.json();
    const el = document.getElementById('preview');
    el.textContent = preview; el.classList.remove('hidden');
  }
  async function delTemplate(id) {
    if (!confirm('Delete template?')) return;
    await fetch(`/templates/${id}`, { method: 'DELETE' });
    location.reload();
  }
</script>

<%- include('partials/footer') %>
