<%
  var _rows = rows || [];
  var _pages = Math.max(1, Math.ceil((stats.total || 0) / perPage));
  var _filtered = !!(filters.w || filters.channel || filters.failed || filters.audience !== 'client');
  var KIND = { invite: 'Invitation', 'team-invite': 'Team invitation', 'password-reset': 'Password reset', notification: 'Notification',
    message: 'Message', 'weekly-digest': 'Weekly summary', alert: 'Alert', rise: 'Improvement', change: 'Update', other: 'Email' };
  var qs = function (extra) {
    var p = Object.assign({ w: filters.w, days: filters.days, channel: filters.channel, audience: filters.audience, failed: filters.failed ? '1' : '' }, extra || {});
    return '/staff/communications?' + Object.keys(p).filter(function (k) { return p[k] !== '' && p[k] != null && p[k] !== false; }).map(function (k) { return k + '=' + encodeURIComponent(p[k]); }).join('&');
  };
%>
<div class="pg-head" style="margin-bottom:0">
  <div><div class="eyebrow">Operations</div></div>
  <div class="ph-right"><%- include('../partials/demo-toggle') %></div>
</div>

<h1 class="claim"><%= title %></h1>
<p class="claim-lede"><% if (stats.total) { %><em><%= h.int(stats.total) %></em> item<%= stats.total === 1 ? '' : 's' %> in the last <%= filters.days %> days.<% } else { %>Nothing in the last <%= filters.days %> days.<% } %></p>
<p class="claim-sub">Every notification and email the portal sent<%= filters.audience === 'client' ? ' to clients' : filters.audience === 'staff' ? ' to staff' : '' %>.</p>

<div class="bento" style="margin-top:22px">
  <div class="card shelf-c b3 sc-violet"><div class="cl">Notifications</div><div class="cv tnum"><%= h.int(stats.notifications) %></div></div>
  <div class="card shelf-c b3 sc-lime"><div class="cl">Emails sent</div><div class="cv tnum"><%= h.int(stats.emailsSent) %></div></div>
  <div class="card shelf-c b3 sc-sky"><div class="cl">Emails not sent</div><div class="cv tnum"><%= h.int(stats.emailsFailed) %></div></div>
  <div class="card shelf-c b3 sc-navy"><div class="cl">Period</div><div class="cv tnum"><%= filters.days %> days</div></div>

  <div class="card b12">
    <div class="card-p">
      <form class="addform" method="GET" action="/staff/communications" style="align-items:flex-end">
        <div class="fld" style="min-width:200px"><label>Client</label>
          <select name="w"><option value="">All clients</option>
            <% workspaces.forEach(function (w) { %><option value="<%= w.slug %>" <%= filters.w === w.slug ? 'selected' : '' %>><%= w.name %></option><% }) %>
          </select></div>
        <div class="fld" style="min-width:150px"><label>Sent to</label>
          <select name="audience">
            <option value="client" <%= filters.audience === 'client' ? 'selected' : '' %>>Clients</option>
            <option value="staff" <%= filters.audience === 'staff' ? 'selected' : '' %>>Staff</option>
            <option value="all" <%= filters.audience === 'all' ? 'selected' : '' %>>Everyone</option>
          </select></div>
        <div class="fld" style="min-width:150px"><label>Type</label>
          <select name="channel">
            <option value="">Everything</option>
            <option value="notification" <%= filters.channel === 'notification' ? 'selected' : '' %>>Notifications</option>
            <option value="email" <%= filters.channel === 'email' ? 'selected' : '' %>>Emails only</option>
          </select></div>
        <div class="fld" style="min-width:130px"><label>Period</label>
          <select name="days"><% [7, 30, 90, 365].forEach(function (d) { %><option value="<%= d %>" <%= filters.days === d ? 'selected' : '' %>>Last <%= d %> days</option><% }) %></select></div>
        <div class="fld" style="min-width:140px"><label>Status</label>
          <select name="failed"><option value="">All</option><option value="1" <%= filters.failed ? 'selected' : '' %>>Not sent only</option></select></div>
        <button class="btn btn-primary btn-sm" type="submit">Filter</button>
        <% if (_filtered) { %><a class="btn btn-sm" href="/staff/communications">Clear</a><% } %>
      </form>
    </div>
  </div>

  <div class="card b12">
    <div class="card-h"><h3>Log</h3><span class="hint"><%= h.int(stats.total) %> item<%= stats.total === 1 ? '' : 's' %><% if (stats.total > perPage) { %>, page <%= page %> of <%= _pages %><% } %></span></div>
    <% if (!_rows.length) { %>
      <div class="card-p rr-meta" style="text-align:center; padding:34px 12px">Nothing<%= _filtered ? ' for this filter' : '' %>.</div>
    <% } else { %>
    <div style="overflow-x:auto">
      <table class="tbl">
        <thead><tr><th>When</th><th>Client</th><th>Type</th><th>What</th><th>Email</th><th>Seen</th></tr></thead>
        <tbody>
        <% _rows.forEach(function (r) { %>
          <tr>
            <td class="muted" style="white-space:nowrap" title="<%= new Date(r.at).toISOString() %>"><%= h.date(r.at) %><div class="rr-meta"><%= h.time(r.at) %></div></td>
            <td class="muted"><%= r.client %><% if (r.audience) { %><div class="rr-meta"><%= r.audience === 'client' ? 'to client' : 'to staff' %></div><% } %></td>
            <td style="white-space:nowrap"><span class="chip flat"><%= r.type === 'email' ? (KIND[r.kind] || 'Email') : (r.kind === 'message' ? 'Message' : 'Notification') %></span><% if (r.category) { %><div class="rr-meta"><%= r.category %></div><% } %></td>
            <td style="max-width:420px">
              <div class="strong" style="word-break:break-word"><%= r.title || '—' %></div>
              <% if (r.type === 'email') { %><div class="rr-meta">To <%= r.to %></div>
              <% } else if (r.body) { %><div class="rr-meta" style="word-break:break-word"><%= String(r.body).replace(/<[^>]+>/g, ' ').slice(0, 160) %></div><% } %>
            </td>
            <td style="min-width:170px">
              <% if (r.type === 'email') { %>
                <span class="chip <%= r.sent ? 'pos' : 'neg' %>"><%= r.sent ? 'Sent' : 'Not sent' %></span>
                <% if (!r.sent && r.reason) { %><div class="rr-meta" style="max-width:240px; word-break:break-word"><%= r.reason %></div><% } %>
              <% } else if (r.emails.length) { var _ok = r.emails.filter(function (e) { return e.sent; }); %>
                <span class="chip <%= _ok.length === r.emails.length ? 'pos' : (_ok.length ? 'warn' : 'neg') %>"><%= _ok.length === r.emails.length ? 'Emailed' : (_ok.length ? 'Partly sent' : 'Not sent') %></span>
                <div class="rr-meta" style="word-break:break-word"><%= r.emails.map(function (e) { return e.to + (e.sent ? '' : ' (not sent)'); }).join(', ') %></div>
              <% } else if (r.emailedAt) { %>
                <span class="chip pos">Emailed</span>
              <% } else if (r.emailSkipped) { var _bad = /fail|error|smtp|not configured/i.test(r.emailSkipped); %>
                <span class="chip <%= _bad ? 'neg' : 'flat' %>"><%= _bad ? 'Not sent' : 'Not emailed' %></span><div class="rr-meta" style="max-width:240px; word-break:break-word"><%= r.emailSkipped %></div>
              <% } else { %>
                <span class="rr-meta">In portal only</span>
              <% } %>
            </td>
            <td class="muted" style="white-space:nowrap"><%= r.type === 'email' ? '—' : (r.reads ? r.reads + ' read' : 'Unread') %></td>
          </tr>
        <% }) %>
        </tbody>
      </table>
    </div>
    <% if (stats.total > perPage) { %>
      <div class="card-p" style="display:flex; gap:10px; justify-content:center">
        <% if (page > 1) { %><a class="btn btn-sm" href="<%= qs({ page: page - 1 }) %>">← Newer</a><% } %>
        <% if (page * perPage < stats.total) { %><a class="btn btn-sm" href="<%= qs({ page: page + 1 }) %>">Older →</a><% } %>
      </div>
    <% } %>
    <% if (capped) { %><div class="card-p rr-meta" style="padding-top:0">Showing the most recent items only. Pick a client or a shorter period to see the rest.</div><% } %>
    <% } %>
  </div>
</div>
