<%

   function statusChip(r){ return r.refused?'warn':(r.status>=500?'neg':(r.status>=400?'warn':'pos')); }
   function statusLabel(r){ return r.refused?'refused':(r.status>=500?'error':(r.status>=400?'refused':'done')); }
   var methodColor = { POST:'var(--teal-600)', DELETE:'var(--neg)', PUT:'var(--warn)', PATCH:'var(--warn)' };

   var _rows = rows || [];
   var _failed = _rows.filter(function (r) { return r.status >= 400 || r.refused; }).length;
   var _wsSeen = {};
   _rows.forEach(function (r) { if (r.workspaceName) _wsSeen[r.workspaceName] = true; });
   var _wsCount = Object.keys(_wsSeen).length;
   var _pages = Math.max(1, Math.ceil((Number(total) || 0) / (Number(perPage) || 100)));
   var _filtered = !!(filters.user || filters.w || filters.failed);

   var _svgWarn = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M8 2.6l5.8 10.2H2.2z" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/><path d="M8 6.6v2.8M8 11.2v.1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>';
   var _svgAll  = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M2.6 4.4h10.8M2.6 8h10.8M2.6 11.6h10.8" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>';
   var _svgGrid = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><rect x="2" y="2" width="5" height="5" rx="1.2" stroke="currentColor" stroke-width="1.4"/><rect x="9" y="2" width="5" height="5" rx="1.2" stroke="currentColor" stroke-width="1.4"/><rect x="2" y="9" width="5" height="5" rx="1.2" stroke="currentColor" stroke-width="1.4"/><rect x="9" y="9" width="5" height="5" rx="1.2" stroke="currentColor" stroke-width="1.4"/></svg>';
   var _svgClk  = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><circle cx="8" cy="8" r="5.8" stroke="currentColor" stroke-width="1.4"/><path d="M8 4.8V8l2.3 1.4" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>';

   var _acts = [];
   _acts.push({ href: '/staff/audit?failed=1', lb: 'Failed only',   ic: _svgWarn, lead: true });
   _acts.push({ href: '/staff/audit',          lb: 'Everything',    ic: _svgAll });
   _acts.push({ href: '/staff/clients',        lb: 'All clients',   ic: _svgGrid });
   _acts.push({ href: '/staff/time',           lb: 'Time tracking', ic: _svgClk });
%>
<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>
<% if (total && _filtered) { %>
  <p class="claim-lede"><em><%= h.int(total) %></em> record<%= total === 1 ? '' : 's' %> match this filter.</p>
<% } else if (total) { %>
  <p class="claim-lede"><em><%= h.int(total) %></em> change<%= total === 1 ? '' : 's' %> in the last <%= retentionDays %> days.</p>
<% } else if (_filtered) { %>
  <p class="claim-lede">Nothing matches this filter.</p>
<% } else { %>
  <p class="claim-lede">Nothing has been recorded here yet.</p>
<% } %>
<p class="claim-sub">Every change in the portal: who made it, for which client, and whether it worked. Kept for <%= retentionDays %> days.</p>

<div class="qbar">
  <div class="qbar-acts">
    <% _acts.forEach(function (a) { %>
      <a class="qact<%= a.lead ? ' qact-lead' : '' %>" href="<%= a.href %>"><%- a.ic %><span><%= a.lb %></span></a>
    <% }) %>
  </div>
</div>

<div class="bento" style="margin-top:22px">

  <div class="vdark b12">
    <div class="vd-k">Records<%= _filtered ? ' matching' : ' kept' %></div>
    <div class="vd-row">
      <div class="vd-num tnum"><%- total ? h.int(total) : '<span class="noval">—</span>' %></div>
    </div>
    <div class="vd-sub">Kept for <b><%= retentionDays %></b> days and never edited.</div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov"><div class="ovl">On this page</div><div class="ovv tnum"><%- _rows.length ? _rows.length : '<span class="noval">—</span>' %></div></div>
      <div class="ov"><div class="ovl">Pages</div><div class="ovv tnum"><%- total ? _pages : '<span class="noval">—</span>' %></div></div>
      <div class="ov"><div class="ovl">Failed on this page</div><div class="ovv tnum"><%= _failed %></div>
        <div class="rr-meta" style="margin-top:5px">refused or errored, of <%= _rows.length %></div></div>
      <div class="ov"><div class="ovl">Clients on this page</div><div class="ovv tnum"><%- _wsCount ? _wsCount : '<span class="noval">—</span>' %></div></div>
    </div>
  </div>

  <details class="aa-note b12"><summary>Reading this log</summary><div class="aa-note-b">Only changes are logged. Viewing a page is not.
      <br><br>
      <b>Result</b>: <i>done</i> means it saved. <i>Refused</i> means a permission or plan limit blocked it. <i>Error</i> means something failed on our side.
      <br><br>
      Admins see the whole log. Staff see their own clients only.</div></details>

  <div class="card b12">
    <div class="card-p">
      <form class="addform" method="GET" action="/staff/audit" style="align-items:flex-end">
        <div class="fld" style="min-width:220px"><label>User email</label><input name="user" value="<%= filters.user %>" placeholder="anyone"></div>
        <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>Result</label>
          <select name="failed">
            <option value="">Everything</option>
            <option value="1" <%= filters.failed?'selected':'' %>>Failed only</option>
          </select>
        </div>
        <button class="btn btn-primary btn-sm" type="submit">Filter</button>
        <% if(_filtered){ %><a class="btn btn-sm" href="/staff/audit">Clear</a><% } %>
      </form>
    </div>
  </div>

  <div class="card b12">
    <div class="card-h"><h3>Activity</h3><span class="hint"><%= h.int(total) %> record<%= total===1?'':'s' %><% if(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 recorded yet<% if(_filtered){ %> for this filter<% } %>. Changes appear here as soon as anyone saves, approves, publishes or syncs.
      </div>
    <% } else { %>
    <div style="overflow-x:auto">
      <table class="tbl">
        <thead><tr><th>When</th><th>Who</th><th>Client</th><th>Action</th><th<%- locals.seeMoney ? '' : ' title="Figures like a retainer or an invoice amount are masked here. Only an admin sees them."' %>>Details<%= locals.seeMoney ? '' : ' 🔒' %></th><th>Result</th><th>Time</th></tr></thead>
        <tbody>
          <% _rows.forEach(function(r){ %>
            <tr>
              <td class="muted" style="white-space:nowrap" title="<%= new Date(r.at).toISOString() %>"><%= h.timeAgo(r.at) %></td>
              <td>
                <div class="strong"><%= r.userEmail || '—' %></div>
                <div class="rr-meta"><%= r.role %><%= r.viewingAs ? ', viewing as client' : '' %></div>
              </td>
              <td class="muted"><%= r.workspaceName || '—' %></td>
              <td style="white-space:nowrap">
                <span class="code" style="color:<%= methodColor[r.method]||'var(--muted)' %>"><%= r.method %></span>
                <span class="code wrap" style="opacity:.85"><%= r.path %></span>
              </td>
              <td class="rr-meta" style="max-width:340px; word-break:break-word"><%= r.summary || '—' %></td>
              <td><span class="chip <%= statusChip(r) %>" title="HTTP <%= r.status %><%= r.refused ? ', refused by a business-rule check' : '' %>"><%= statusLabel(r) %></span></td>
              <td class="num muted"><%= r.ms %>ms</td>
            </tr>
          <% }) %>
        </tbody>
      </table>
    </div>
    <% if(total>perPage){ %>
      <div class="card-p" style="display:flex; gap:10px; justify-content:center">
        <% var q = function(p){ var s='?page='+p; if(filters.user) s+='&user='+encodeURIComponent(filters.user); if(filters.w) s+='&w='+encodeURIComponent(filters.w); if(filters.failed) s+='&failed=1'; return '/staff/audit'+s; }; %>
        <% if(page>1){ %><a class="btn btn-sm" href="<%= q(page-1) %>">← Newer</a><% } %>
        <% if(page*perPage<total){ %><a class="btn btn-sm" href="<%= q(page+1) %>">Older →</a><% } %>
      </div>
    <% } %>
    <% } %>
  </div>
</div>
