<%- include('partials/header') %>
<%- include('partials/nav') %>

<main class="flex-grow max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-8">

  <!-- Page Header -->
  <div class="mb-8">
    <h1 class="text-3xl font-bold text-slate-900">Dashboard</h1>
    <p class="text-sm text-slate-500 mt-1">Welcome back, <span class="font-medium text-slate-700"><%= user.email %></span></p>
  </div>

  <% if (brandNew) { %>
    <div class="mb-8 rounded-2xl border border-brand-200 bg-brand-50 p-6">
      <h2 class="text-lg font-bold text-brand-900">Start here: your first campaign in 3 steps</h2>
      <ol class="mt-3 grid sm:grid-cols-3 gap-4 text-sm text-brand-900/80">
        <li><span class="font-bold">1. Connect a sender.</span> Add your own email server, SMS account or Telegram bot, or <a class="underline font-semibold" href="/requests">request shared access</a> from an admin.</li>
        <li><span class="font-bold">2. Import contacts.</span> Upload a CSV. Every contacts page has a sample file you can download.</li>
        <li><span class="font-bold">3. Compose and send.</span> Use <code>{{name}}</code> placeholders, preview, then queue it.</li>
      </ol>
    </div>
  <% } %>

  <% if (pendingRequests > 0) { %>
    <div class="mb-6 px-4 py-3 rounded-lg text-sm border bg-amber-50 border-amber-200 text-amber-800 flex items-center justify-between gap-3">
      <span>You have <strong><%= pendingRequests %></strong> access request<%= pendingRequests === 1 ? '' : 's' %> waiting for admin approval.</span>
      <a href="/requests" class="font-semibold underline whitespace-nowrap">View requests</a>
    </div>
  <% } %>

  <!-- Channel cards: each shows readiness and the single next step -->
  <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
    <% channels.forEach(function (c) {
         const next = c.senders === 0
           ? { label: 'Connect ' + (c.noun === 'account' ? 'an ' : 'a ') + c.noun, href: '/' + c.key + '/' + (c.key === 'email' ? 'servers' : c.key === 'sms' ? 'accounts' : 'bots') }
           : c.contacts === 0
             ? { label: 'Import contacts', href: '/' + c.key + '/contacts' }
             : { label: 'Compose campaign', href: '/' + c.key + '/send' };
    %>
      <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-5 flex flex-col">
        <div class="flex items-center justify-between">
          <h3 class="text-base font-bold text-slate-900"><%= c.icon %> <%= c.label %></h3>
          <a href="/<%= c.key %>/send" class="text-xs font-semibold text-brand-600 hover:text-brand-700">Open &rarr;</a>
        </div>

        <ul class="mt-4 space-y-2 text-sm">
          <li class="flex items-center justify-between">
            <span class="text-slate-500"><%= c.senders > 0 ? '✅' : '⬜' %> <%= c.noun.charAt(0).toUpperCase() + c.noun.slice(1) %>s ready</span>
            <span class="font-semibold text-slate-800"><%= c.senders %></span>
          </li>
          <li class="flex items-center justify-between">
            <span class="text-slate-500"><%= c.contacts > 0 ? '✅' : '⬜' %> Contacts</span>
            <span class="font-semibold text-slate-800"><%= c.contacts %></span>
          </li>
          <li class="flex items-center justify-between">
            <span class="text-slate-500">Sends left today</span>
            <span class="font-semibold <%= c.senders === 0 ? 'text-slate-300' : (c.unlimited || c.remaining > 0) ? 'text-emerald-600' : 'text-red-500' %>"><%= c.senders === 0 ? '—' : c.unlimited ? 'No cap' : c.remaining %></span>
          </li>
        </ul>

        <div class="mt-5 pt-4 border-t border-slate-100 flex items-center justify-between gap-2">
          <a href="<%= next.href %>" class="flex-1 text-center px-3 py-2 text-sm font-semibold text-white bg-brand-500 hover:bg-brand-600 rounded-lg shadow-sm transition"><%= next.label %></a>
          <% if (c.senders === 0) { %>
            <a href="/requests" class="text-xs font-medium text-brand-600 hover:text-brand-700 whitespace-nowrap">or request access</a>
          <% } %>
        </div>
      </div>
    <% }); %>
  </div>

  <!-- Recent Campaign Activity -->
  <div class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
    <div class="p-6 border-b border-slate-100 flex items-center justify-between">
      <div>
      <h3 class="text-lg font-bold text-slate-900">Recent Campaign Activity</h3>
      <p class="text-xs text-slate-500 mt-0.5">Across all channels</p>
      </div>
      <a href="/campaigns" class="text-xs font-semibold text-brand-600 hover:text-brand-700">All campaigns &rarr;</a>
    </div>

    <% if (campaigns.length === 0) { %>
      <div class="p-12 text-center text-slate-400">
        <p class="text-4xl mb-2">📊</p>
        <p class="text-sm">No campaigns sent yet. Queue one from Email or Telegram to see it here.</p>
      </div>
    <% } else { %>
      <div class="overflow-x-auto">
        <table class="w-full text-left border-collapse">
          <thead>
            <tr class="bg-slate-50 text-xs font-semibold text-slate-500 border-b border-sky-100">
              <th class="py-3 px-4">Channel</th>
              <th class="py-3 px-4">Message</th>
              <th class="py-3 px-4">Status</th>
              <th class="py-3 px-4">Sent</th>
              <th class="py-3 px-4">Pending</th>
              <th class="py-3 px-4">Failed</th>
              <th class="py-3 px-4">Queued</th>
              <th class="py-3 px-4"></th>
            </tr>
          </thead>
          <tbody class="divide-y divide-sky-50 text-sm">
            <% campaigns.forEach(c => { %>
              <tr class="hover:bg-brand-50/30 transition" data-campaign-row="<%= c.id %>">
                <td class="py-3 px-4 font-medium text-slate-800 capitalize">
                  <%= c.channel === 'email' ? '✉️' : c.channel === 'telegram' ? '✈️' : c.channel === 'sms' ? '💬' : '📱' %> <%= c.channel %>
                </td>
                <td class="py-3 px-4 text-slate-600 max-w-xs truncate"><%= c.subject || c.message %></td>
                <td class="py-3 px-4">
                  <span data-status class="px-2 py-0.5 rounded-full text-xs font-medium <%= c.status === 'completed' ? 'bg-emerald-50 text-emerald-700' : c.status === 'sending' ? 'bg-sky-50 text-sky-700' : 'bg-slate-100 text-slate-500' %>">
                    <%= c.status %>
                  </span>
                  <% if (c.status_note && c.status !== 'completed') { %><div class="text-[11px] text-amber-700 mt-1 max-w-xs leading-snug">⏳ <%= c.status_note %></div><% } %>
                </td>
                <td class="py-3 px-4 text-emerald-600 font-semibold" data-sent><%= c.stats.sent %></td>
                <td class="py-3 px-4 text-slate-500" data-pending><%= c.stats.pending %></td>
                <td class="py-3 px-4 text-red-500" data-failed><%= c.stats.failed %></td>
                <td class="py-3 px-4 text-slate-400 text-xs"><%= c.created_at %></td>
                <td class="py-3 px-4">
                  <a href="/campaigns/<%= c.id %>" class="text-xs font-semibold text-brand-600 hover:text-brand-700">View &rarr;</a>
                </td>
              </tr>
            <% }) %>
          </tbody>
        </table>
      </div>
    <% } %>
  </div>
</main>

<script>
  // Poll only campaigns that are still in-flight; stop once a row completes.
  function livePoll() {
    const rows = document.querySelectorAll('[data-campaign-row]');
    let anyActive = false;

    rows.forEach((row) => {
      const statusEl = row.querySelector('[data-status]');
      const currentStatus = statusEl.textContent.trim();
      if (currentStatus !== 'queued' && currentStatus !== 'sending') return;

      anyActive = true;
      const id = row.getAttribute('data-campaign-row');

      fetch(`/campaigns/${id}/status`)
        .then((r) => r.json())
        .then((data) => {
          if (data.error) return;
          statusEl.textContent = data.status;
          statusEl.className = 'px-2 py-0.5 rounded-full text-xs font-medium ' +
            (data.status === 'completed' ? 'bg-emerald-50 text-emerald-700' :
             data.status === 'sending' ? 'bg-sky-50 text-sky-700' : 'bg-slate-100 text-slate-500');
          row.querySelector('[data-sent]').textContent = data.stats.sent;
          row.querySelector('[data-pending]').textContent = data.stats.pending;
          row.querySelector('[data-failed]').textContent = data.stats.failed;
        })
        .catch(() => {});
    });

    if (anyActive) setTimeout(livePoll, 4000);
  }
  livePoll();
</script>

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