<% const fmtDate = (d) => d ? new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : ''; %>
<% const currentStatus = query.status || 'all'; %>

<%- include('../../partials/adminTopbar', {
  pageTitle: 'Newsletter Subscribers',
  pageSubtitle: stats.total + ' total · ' + stats.newThisWeek + ' new this week',
  topbarActions: `
    <a href="/admin/newsletter/campaigns" class="btn-ghost text-xs">Campaigns</a>
    <a href="/admin/newsletter/export.csv?status=${encodeURIComponent(currentStatus)}" class="btn-ghost text-xs">Export CSV</a>
    <button type="button" id="open-campaign" class="btn-teal text-xs">Send Campaign</button>
  `
}) %>

<main class="admin-main flex-1 overflow-y-auto overflow-x-hidden" id="newsletter-page"
  data-growth='<%- growthChart %>'
  data-sources='<%- sourceChart %>'
  data-campaign-sent="<%= campaignSent ? '1' : '0' %>"
  data-active-count="<%= stats.active %>"
  data-flash="<%= typeof flash !== 'undefined' && flash ? flash.replace(/"/g, '&quot;') : '' %>">

  <% if (typeof flash !== 'undefined' && flash) { %>
  <div class="admin-flash <%= (typeof flashType !== 'undefined' && flashType === 'error') ? 'admin-flash-error' : 'admin-flash-success' %> mb-4"><%= flash %></div>
  <% } %>

  <%- include('../../partials/adminNewsletterNav', { newsletterNav: 'subscribers' }) %>

  <div class="admin-stat-grid" style="margin-bottom:1.25rem">
    <div class="card" style="padding:16px">
      <p class="text-xs mb-1" style="color:rgba(255,255,255,.4)">Total Subscribers</p>
      <p class="text-2xl font-bold text-white"><%= stats.total %></p>
      <p class="text-xs mt-1" style="color:#34d399">↑ <%= stats.newThisWeek %> this week</p>
    </div>
    <div class="card" style="padding:16px">
      <p class="text-xs mb-1" style="color:rgba(255,255,255,.4)">Active</p>
      <p class="text-2xl font-bold text-white"><%= stats.active %></p>
      <p class="text-xs mt-1" style="color:rgba(255,255,255,.3)"><%= stats.activePct %>% of total</p>
    </div>
    <div class="card" style="padding:16px">
      <p class="text-xs mb-1" style="color:rgba(255,255,255,.4)">New This Month</p>
      <p class="text-2xl font-bold text-teal-400"><%= stats.newThisMonth %></p>
      <p class="text-xs mt-1" style="color:rgba(255,255,255,.3)">subscribers joined this month</p>
    </div>
    <div class="card" style="padding:16px">
      <p class="text-xs mb-1" style="color:rgba(255,255,255,.4)">Unsubscribed</p>
      <p class="text-2xl font-bold" style="color:#f87171"><%= stats.unsubscribed %></p>
      <p class="text-xs mt-1" style="color:rgba(255,255,255,.3)"><%= stats.churnPct %>% churn</p>
    </div>
  </div>

  <div class="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-5">
    <div class="card lg:col-span-2" style="padding:20px">
      <p class="text-sm font-semibold text-white mb-1">Subscriber Growth</p>
      <p class="text-xs mb-4" style="color:rgba(255,255,255,.35)">Monthly new subscribers</p>
      <div style="height:180px"><canvas id="growthChart"></canvas></div>
    </div>
    <div class="card" style="padding:20px">
      <p class="text-sm font-semibold text-white mb-1">Subscription Source</p>
      <p class="text-xs mb-4" style="color:rgba(255,255,255,.35)">Where subscribers came from</p>
      <div style="height:130px" class="mb-4"><canvas id="sourceChart"></canvas></div>
      <div id="source-legend" class="space-y-2"></div>
    </div>
  </div>

  <div class="card" style="padding:0;overflow:hidden">
    <form method="get" action="/admin/newsletter" class="flex flex-col sm:flex-row items-start sm:items-center gap-3 p-4 border-b" style="border-color:rgba(255,255,255,.07)">
      <input type="hidden" name="status" id="sub-status" value="<%= currentStatus %>"/>
      <div class="flex gap-2">
        <button type="button" class="filter-pill sub-filter<%= currentStatus === 'all' ? ' active' : '' %>" data-status="all">All</button>
        <button type="button" class="filter-pill sub-filter<%= currentStatus === 'active' ? ' active' : '' %>" data-status="active">Active</button>
        <button type="button" class="filter-pill sub-filter<%= currentStatus === 'unsubscribed' ? ' active' : '' %>" data-status="unsubscribed">Unsubscribed</button>
      </div>
      <input type="search" name="search" value="<%= query.search || '' %>" placeholder="Search email…" class="sm:ml-auto pl-3 pr-4 py-2 rounded-lg text-xs" style="background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.1);color:rgba(255,255,255,.8);width:200px;outline:none"/>
    </form>

    <div class="overflow-x-auto">
      <table class="w-full">
        <thead>
          <tr>
            <th>Email</th>
            <th>Status</th>
            <th class="hidden md:table-cell">Source</th>
            <th class="hidden lg:table-cell">Subscribed</th>
          </tr>
        </thead>
        <tbody>
          <% if (!subscribers.length) { %>
          <tr><td colspan="4" class="text-center py-10" style="color:rgba(255,255,255,.3)">No subscribers.</td></tr>
          <% } %>
          <% subscribers.forEach(function(s) { %>
          <tr>
            <td class="text-sm text-white"><%= s.email %></td>
            <td>
              <% if (s.status === 'active') { %><span class="badge badge-green">Active</span>
              <% } else { %><span class="badge badge-gray">Unsubscribed</span><% } %>
            </td>
            <td class="hidden md:table-cell"><span class="badge badge-purple"><%= s.source || 'website' %></span></td>
            <td class="hidden lg:table-cell text-xs" style="color:rgba(255,255,255,.4)"><%= fmtDate(s.subscribedAt) %></td>
          </tr>
          <% }); %>
        </tbody>
      </table>
    </div>

    <% if (pagination.totalPages > 1) { %>
    <div class="flex items-center justify-between px-4 py-3 border-t" style="border-color:rgba(255,255,255,.06)">
      <p class="text-xs" style="color:rgba(255,255,255,.35)">Page <%= pagination.page %> of <%= pagination.totalPages %></p>
      <div class="flex gap-1">
        <% if (pagination.page > 1) { %><a href="?page=<%= pagination.page - 1 %>&status=<%= currentStatus %>" class="w-7 h-7 rounded-lg text-xs flex items-center justify-center hover:bg-white/10" style="color:rgba(255,255,255,.5)">‹</a><% } %>
        <% if (pagination.page < pagination.totalPages) { %><a href="?page=<%= pagination.page + 1 %>&status=<%= currentStatus %>" class="w-7 h-7 rounded-lg text-xs flex items-center justify-center hover:bg-white/10" style="color:rgba(255,255,255,.5)">›</a><% } %>
      </div>
    </div>
    <% } %>
  </div>
</main>

<div class="modal-overlay" id="campaign-modal">
  <div class="modal-box" style="max-width:480px">
    <h3 class="text-base font-bold text-white mb-1">Send Campaign</h3>
    <p class="text-xs mb-5" style="color:rgba(255,255,255,.45)">Email all <strong class="text-white"><%= stats.active %></strong> active subscriber<%= stats.active === 1 ? '' : 's' %> using your SMTP settings. Each message includes an unsubscribe link.</p>
    <form method="post" action="/admin/newsletter/campaign" class="space-y-4" id="campaign-form">
      <div>
        <label class="form-label">Subject</label>
        <input type="text" name="subject" class="form-input" required placeholder="May product update"/>
      </div>
      <div>
        <label class="form-label">Message</label>
        <textarea name="body" class="form-input" required placeholder="Write your campaign…"></textarea>
      </div>
      <div class="flex gap-3 pt-2">
        <button type="button" id="campaign-cancel" class="btn-ghost flex-1 justify-center">Cancel</button>
        <button type="submit" class="btn-primary flex-1 justify-center" id="campaign-submit" <%= stats.active === 0 ? 'disabled' : '' %>>Send to Active Subscribers</button>
      </div>
    </form>
  </div>
</div>
