<%- include('partials/header', { title: 'Campaigns', heading: 'Campaigns', active: '/campaigns' }) %>

<div class="grid lg:grid-cols-3 gap-6">
  <!-- Create -->
  <div class="bg-white rounded-2xl shadow p-5">
    <h2 class="font-semibold mb-3">New campaign</h2>
    <div class="space-y-2 text-sm">
      <input id="cp_name" placeholder="Campaign name" class="w-full rounded-lg border border-slate-300 px-3 py-2" />
      <select id="cp_device" class="w-full rounded-lg border border-slate-300 px-3 py-2">
        <% devices.forEach((d) => { %>
          <option value="<%= d.id %>"><%= d.label %> <%= d.phone_number ? '(' + d.phone_number + ')' : '' %></option>
        <% }); %>
      </select>
      <input id="cp_group" placeholder="Contact group (recipients)" class="w-full rounded-lg border border-slate-300 px-3 py-2" />
      <textarea id="cp_body" rows="5" placeholder="Hi {name}, {Hello|Hi}! ..." class="w-full rounded-lg border border-slate-300 px-3 py-2 font-mono"></textarea>
      <label class="block text-xs text-slate-500">Schedule (optional, leave blank to send now)</label>
      <input id="cp_when" type="datetime-local" class="w-full rounded-lg border border-slate-300 px-3 py-2" />
      <button onclick="createCampaign()" class="w-full bg-emerald-600 text-white rounded-lg py-2">Create</button>
    </div>
  </div>

  <!-- List -->
  <div class="lg:col-span-2 bg-white rounded-2xl shadow p-5">
    <h2 class="font-semibold mb-3">Your campaigns</h2>
    <table class="w-full text-sm">
      <thead class="text-left text-slate-500 border-b">
        <tr><th class="py-2">Name</th><th>Status</th><th>Progress</th><th></th></tr>
      </thead>
      <tbody>
        <% campaigns.forEach((c) => { %>
          <tr class="border-b last:border-0">
            <td class="py-2"><a href="/campaigns/<%= c.id %>" class="text-emerald-600 hover:underline"><%= c.name %></a></td>
            <td><span class="text-xs px-2 py-1 rounded-full bg-slate-100"><%= c.status %></span></td>
            <td><%= c.sent %>/<%= c.total %> <% if (c.failed) { %><span class="text-rose-500">(<%= c.failed %> failed)</span><% } %></td>
            <td class="text-right space-x-2">
              <% if (c.status === 'running') { %><button onclick="act(<%= c.id %>,'pause')" class="text-amber-600">Pause</button><% } %>
              <% if (c.status === 'paused') { %><button onclick="act(<%= c.id %>,'resume')" class="text-emerald-600">Resume</button><% } %>
              <% if (!['completed','cancelled'].includes(c.status)) { %><button onclick="act(<%= c.id %>,'cancel')" class="text-rose-500">Cancel</button><% } %>
            </td>
          </tr>
        <% }); %>
      </tbody>
    </table>
  </div>
</div>

<script>
  async function createCampaign() {
    const when = document.getElementById('cp_when').value;
    const body = {
      name: document.getElementById('cp_name').value,
      waSessionId: parseInt(document.getElementById('cp_device').value, 10),
      group: document.getElementById('cp_group').value,
      body: document.getElementById('cp_body').value,
      scheduledAt: when ? new Date(when).toISOString() : undefined,
    };
    const r = await fetch('/campaigns', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
    if (r.ok) location.reload(); else alert((await r.json()).error || 'Failed');
  }
  async function act(id, action) {
    await fetch(`/campaigns/${id}/${action}`, { method: 'POST' });
    location.reload();
  }
</script>

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