<%
  function riskChip(r){ return '<span class="chip '+(r==='High'?'neg':(r==='Medium'?'warn':'pos'))+'">'+r+'</span>'; }
  var colors={DL:'var(--navy)',NR:'var(--neg)',OH:'var(--teal-600)',VF:'#3F7A17',AP:'#B5791E',LX:'#5436DA'};
  var money = locals.money || { billing: true, internal: true };

  var _rows    = rows || [];

  var _mrr     = _rows.reduce(function (s, r) { return s + (r.live === false ? 0 : (r.mrr || 0)); }, 0);
  var _mrrOff  = _rows.filter(function (r) { return r.live === false; }).length;

  var _mrrUnset = _rows.filter(function (r) { return r.live !== false && r.mrr == null; }).length;
  var _hours   = _rows.reduce(function (s, r) { return s + (r.hours || 0); }, 0);
  var _visRows = _rows.filter(function (r) { return r.aiVis != null; });
  var _avgVis  = _visRows.length ? Math.round(_visRows.reduce(function (s, r) { return s + r.aiVis; }, 0) / _visRows.length) : null;
  var _high    = _rows.filter(function (r) { return r.risk === 'High'; }).length;
  var _tasks   = _rows.reduce(function (s, r) { return s + (r.openTasks || 0); }, 0);
  var _demo    = _rows.filter(function (r) { return r.ws && r.ws.isDemo; }).length;

  var dash = function (val) { return (val == null || val === '') ? '<span class="noval">—</span>' : String(val); };

  var _svgPlus = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M8 3.2v9.6M3.2 8h9.6" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>';
  var _svgDial = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><circle cx="8" cy="8" r="5.9" stroke="currentColor" stroke-width="1.3"/><circle cx="8" cy="8" r="2.6" stroke="currentColor" stroke-width="1.3"/></svg>';
  var _svgUp   = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M8 12.6V4.2M4.6 7.6L8 4.2l3.4 3.4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></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 _svgUsr  = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><circle cx="8" cy="5.6" r="2.6" stroke="currentColor" stroke-width="1.4"/><path d="M3.2 13.4a4.8 4.8 0 0 1 9.6 0" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>';

  var _acts = [];
  _acts.push({ href: '/staff/clients/new',     lb: 'Add client',      ic: _svgPlus, lead: true });
  _acts.push({ href: '/staff/mission-control', lb: 'Mission Control', ic: _svgDial });
  _acts.push({ href: '/staff/upload',          lb: 'Upload centre',   ic: _svgUp });
  _acts.push({ href: '/staff/time',            lb: 'Log time',        ic: _svgClk });
  _acts.push({ href: '/staff/team',            lb: 'Team',            ic: _svgUsr });
%>
<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Agency</div>
  </div>
  <div class="ph-right"><%- include('../partials/demo-toggle') %></div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (money.billing && _mrr) { %>
  <p class="claim-lede">Your book of business is <em><%= h.money(_mrr) %></em> a month.</p>
<% } else if (_rows.length) { %>
  <p class="claim-lede"><em><%= _rows.length %></em> client<%= _rows.length === 1 ? '' : 's' %> on the books.</p>
<% } else { %>
  <p class="claim-lede">There is no client here yet.</p>
<% } %>
<p class="claim-sub"><%
  if (_rows.length) { %>Each figure is the client's latest measurement, the same number on their dashboard.<%
  } else { %>Add your first client to start.<% }
%></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 vd-cut b12">
    <span class="vn-fillet"></span>
    <a class="vn-cut" href="/staff/clients/new">Add a client
      <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M6 2.4v7.2M2.4 6h7.2" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>
    </a>
    <div class="vd-k"><%= money.billing ? 'Recurring revenue' : 'Active clients' %></div>
    <div class="vd-row">
      <div class="vd-num tnum"><%- money.billing ? (_mrr ? h.money(_mrr) : '<span class="noval">—</span>') : dash(_rows.length) %></div>
    </div>
    <div class="vd-sub">Across <b><%= _rows.length %></b> client<%= _rows.length === 1 ? '' : 's' %><%= _demo ? ', ' + _demo + ' of them demo accounts' : '' %><%= (money.billing && _mrrUnset) ? ', ' + _mrrUnset + ' with no retainer set' : '' %><%= (money.billing && _mrrOff) ? '. ' + _mrrOff + ' paused or ended, not counted' : '' %>.</div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov"><div class="ovl">Clients</div><div class="ovv tnum"><%= _rows.length %></div></div>
      <div class="ov"><div class="ovl">Avg AI Visibility</div><div class="ovv tnum"><%- dash(_avgVis) %></div>
        <div class="rr-meta" style="margin-top:5px">over <%= _visRows.length %> with a run</div></div>
      <div class="ov"><div class="ovl">Hours this month</div><div class="ovv tnum"><%- _hours ? _hours + 'h' : '<span class="noval">—</span>' %></div></div>
      <div class="ov"><div class="ovl">Open tasks</div><div class="ovv tnum"><%= _tasks %></div></div>
      <div class="ov"><div class="ovl">At high risk</div><div class="ovv tnum"><%= _high %></div></div>
    </div>
  </div>

  <details class="aa-note b12"><summary>Reading this table</summary><div class="aa-note-b">Each figure is the client's latest measurement, the same number on their dashboard. A dash means not measured yet.
      <br><br>
      <b>Hours</b> are this month's time from Clockify.
      <br><br>
      <b>Modules</b> decide which pages a client can open. Turning one off hides the section and blocks its address.</div></details>

  <div class="card b12">
    <div class="card-h"><h3>All clients</h3><span class="hint">hours are this month</span></div>
    <div style="overflow-x:auto">
      <table class="tbl">
        <thead><tr><th>Client</th><th>Team</th><th>Plan</th><th>AI Vis.</th><th>SEO</th><th>Open tasks</th><th>Hours/mo</th><th>MRR</th><th>Risk</th><th class="rowact-cell">Actions</th></tr></thead>
        <tbody>
          <% _rows.forEach(function(r){ var w=r.ws; %>
            <tr>

              <td class="strong"><% if (w.logoUrl) { %><span class="cl-badge cl-logo cl-row"><img src="<%= w.logoUrl %>" alt="" width="24" height="24" loading="lazy"></span>
                <% } else { %><span class="cl-badge cl-row" style="background:<%= colors[w.badge]||'var(--navy)' %>"><%= w.badge %></span><% } %><%= w.name %><% if (w.isDemo) { %> <span class="chip flat" title="Demo client (excluded from agency totals unless demo data is shown)">Demo</span><% } %><% if (w.previewMode) { %> <span class="chip warn" title="Preview mode: left out of every schedule">Preview</span><% } %><% var _ls = w.lifecycle && w.lifecycle.status; if (_ls && _ls !== 'active') { %> <span class="chip <%= _ls === 'archived' ? 'neg' : 'warn' %>" title="Nothing runs for this client"><%= { paused: 'Paused', readonly: 'Read-only', archived: 'Archived' }[_ls] %></span><% } %></td>

              <td>
                <% if (w.accountManager) { %>
                  <div style="display:flex; align-items:center; gap:6px; white-space:nowrap">
                    <%- include('../partials/avatar', { url: w.accountManager.avatarUrl, initials: w.accountManager.initials || (w.accountManager.name||'?').trim().charAt(0).toUpperCase(), color: w.accountManager.avatarColor, name: w.accountManager.name + (w.accountManager.title ? ', ' + w.accountManager.title : ''), cls: 'fav', size: 22 }) %>
                    <span style="font-size:var(--fs-sm)"><%= w.accountManager.name %></span>
                  </div>
                <% } else { %><span class="noval">—</span><% } %>

                <% var _rest = (w.team || []).filter(function(m){ return !w.accountManager || String(m._id) !== String(w.accountManager._id); }); %>
                <% if (_rest.length) { %>
                  <div class="av-stack" style="margin-top:6px">
                    <% _rest.slice(0, 5).forEach(function(m){ %>
                      <%- include('../partials/avatar', { url: m.avatarUrl, initials: m.initials || (m.name||'?').trim().charAt(0).toUpperCase(), color: m.avatarColor, name: m.name + (m.title ? ', ' + m.title : ''), cls: 'fav', size: 20 }) %>
                    <% }) %>
                    <% if (_rest.length > 5) { %><span class="av-more" title="<%= _rest.slice(5).map(function(m){ return m.name; }).join(', ') %>">+<%= _rest.length - 5 %></span><% } %>
                  </div>
                <% } %>
              </td>
              <td class="muted"><%= w.plan %></td><td class="num"><%- dash(r.aiVis) %></td><td class="num"><%- dash(r.seo) %></td><td class="num"><%= r.openTasks %></td>
              <td class="num"><%- r.hours ? r.hours : '<span class="noval">—</span>' %></td>
              <td class="num"<%- (r.live === false && r.mrr != null) ? ' title="Not counted in the total while the client is not active" style="opacity:.5;text-decoration:line-through"' : '' %>><%- r.mrr != null ? h.money(r.mrr) : '<span class="noval">—</span>' %></td>
              <td><%- riskChip(r.risk) %></td>

              <td class="rowact-cell">
                <div class="rowact">
                  <a class="rowact-b" href="/staff/clients/<%= w.slug %>/edit" title="Edit <%= w.name %>">
                    <svg viewBox="0 0 16 16" fill="none"><path d="M11.2 2.6l2.2 2.2M9.9 3.9l2.2 2.2-6.4 6.4-2.9.7.7-2.9z" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
                    <span>Edit</span>
                  </a>
                  <a class="rowact-b" href="/staff/view/<%= w.slug %>" title="Open <%= w.name %>'s portal as they see it">
                    <svg viewBox="0 0 16 16" fill="none"><path d="M1.4 8S3.9 3.4 8 3.4 14.6 8 14.6 8 12.1 12.6 8 12.6 1.4 8 1.4 8z" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/><circle cx="8" cy="8" r="1.9" stroke="currentColor" stroke-width="1.4"/></svg>
                    <span>Portal</span>
                  </a>
                  <a class="rowact-b" href="/staff/mission-control?w=<%= w.slug %>" title="Mission Control for <%= w.name %>">
                    <svg viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="5.9" stroke="currentColor" stroke-width="1.3"/><circle cx="8" cy="8" r="2.6" stroke="currentColor" stroke-width="1.3"/><path d="M8 1.5v1.6M8 12.9v1.6M14.5 8h-1.6M3.1 8H1.5" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>
                    <span>Mission&nbsp;Control</span>
                  </a>
                </div>
              </td>
            </tr>
          <% }) %>
        </tbody>
      </table>
      <% if(!_rows.length){ %><div class="card-p rr-meta" style="text-align:center; padding:34px">No clients yet. <b>Add client</b> above is the first move.</div><% } %>
    </div>
  </div>
</div>
