<%

  var _rows   = rows || [];
  var _active = _rows.filter(function (r) { return r.m.active !== false; }).length;
  var _admins = _rows.filter(function (r) { return r.m.role === 'admin'; }).length;

  var _hRows    = _rows.filter(function (r) { return r.hours != null; });
  var _hours    = _hRows.reduce(function (s, r) { return s + r.hours; }, 0);
  var _hasHours = _hRows.length > 0 && _hours > 0;

  var _seen = {}, _amCount = 0, _noClient = 0;
  _rows.forEach(function (r) {
    if (!r.clients.length) _noClient++;
    var isAm = false;
    r.clients.forEach(function (c) {
      _seen[String(c._id)] = 1;
      if (String(c.accountManager || '') === String(r.m._id)) isAm = true;
    });
    if (isAm) _amCount++;
  });
  var _covered = Object.keys(_seen).length;
  var _pending = (pending || []).length;

  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 _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 _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 _svgMail = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><rect x="1.9" y="3.4" width="12.2" height="9.2" rx="1.6" stroke="currentColor" stroke-width="1.4"/><path d="M2.4 4.4L8 8.6l5.6-4.2" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/></svg>';

  var _acts = [];
  _acts.push({ href: '/staff/clients',         lb: 'Clients',         ic: _svgUsr, lead: true });
  _acts.push({ href: '/staff/time',            lb: 'Log time',        ic: _svgClk });
  _acts.push({ href: '/staff/mission-control', lb: 'Mission Control', ic: _svgDial });

  if (_pending) _acts.push({ href: '#invites', lb: 'Pending invites', ic: _svgMail, n: _pending });
%>

<div id="staff-team-view">
<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 (_hasHours) { %>
  <p class="claim-lede">Your team logged <em><%= _hours %>h</em> this month.</p>
<% } else if (_rows.length) { %>
  <p class="claim-lede"><em><%= _rows.length %></em> <%= _rows.length === 1 ? 'person works' : 'people work' %> here.</p>
<% } else { %>
  <p class="claim-lede">Nobody is on the team yet.</p>
<% } %>
<p class="claim-sub"><%
  if (isAdmin) { %>Who works here, which clients they're on, and how much they logged this month.<%
  } else { %>Who works here and which clients they're on. Hours are shown to admins only.<% }
%></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 %><% if (a.n) { %> <b class="qn"><%= a.n %></b><% } %></span></a>
    <% }) %>
  </div>
</div>

<% if (isAdmin) { %>

<div class="card card-p" id="invite" style="margin-top:22px"<%= (locals.query && locals.query.new) ? '' : ' hidden' %>>
  <div class="card-h" style="padding:0 0 12px"><h3>Invite a team member</h3><span class="rr-end"><a class="more js-panel-cancel" data-panel="#invite" href="/staff/team">Cancel</a></span></div>
  <form class="addform js-ajax-form" data-refresh="#staff-team-view" data-hide-after="#invite" data-reset-after="#inviteForm" id="inviteForm" method="POST" action="/staff/team/invite">
    <div class="fld" style="flex:1;min-width:180px"><label>Name</label><input name="name" placeholder="Full name"></div>
    <div class="fld" style="flex:1;min-width:220px"><label>Work email</label><input name="email" type="email" placeholder="name@voctos.com" required></div>
    <div class="fld" style="min-width:160px"><label>Title</label><input name="title" placeholder="SEO Specialist"></div>
    <div class="fld" style="min-width:130px"><label>Role</label>
      <select name="role" title="Admins can invite people, assign clients and change roles. Staff work on the clients they are assigned.">
        <option value="staff" selected>Staff</option>
        <option value="admin">Admin</option>
      </select></div>
    <button class="btn btn-primary btn-sm" type="submit">Send invite</button>
    <div class="rr-meta" style="flex:1 1 100%; margin-top:6px">They get a link to set their own password, so you never handle it.</div>
  </form>
</div>
<% } else { %>
<div class="rr-meta" style="margin:18px 0 0">Only an admin can invite people or change roles.</div>
<% } %>

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

  <div class="vdark vd-cut b12">
    <span class="vn-fillet"></span>
    <% if (isAdmin) { %>
      <a class="vn-cut js-panel-open" data-panel="#invite" href="/staff/team?new=1#invite">Invite someone
        <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>
    <% } else { %>
      <a class="vn-cut" href="/staff/clients">See the clients
        <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M3 9L9 3M9 3H4.2M9 3v4.8" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </a>
    <% } %>
    <div class="vd-k">The team</div>
    <div class="vd-row">
      <div class="vd-num tnum"><%- _rows.length ? _rows.length : '<span class="noval">—</span>' %></div>
    </div>
    <div class="vd-sub">Everyone with a VOCTOS login, active or not. <b><%= _covered %></b> client<%= _covered === 1 ? ' has' : 's have' %> at least one of them on it<%= _noClient ? ', and ' + _noClient + ' ' + (_noClient === 1 ? 'person is' : 'people are') + ' on none' : '' %>.</div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov"><div class="ovl">Active</div><div class="ovv tnum"><%- _active ? _active : '<span class="noval">—</span>' %></div></div>
      <div class="ov"><div class="ovl">Admins</div><div class="ovv tnum"><%- _admins ? _admins : '<span class="noval">—</span>' %></div></div>
      <% if (isAdmin) { %>
      <div class="ov"><div class="ovl">Hours this month</div><div class="ovv tnum"><%- _hasHours ? _hours + 'h' : '<span class="noval">—</span>' %></div>
        <div class="rr-meta" style="margin-top:5px">summed over the <%= _hRows.length %> <%= _hRows.length === 1 ? 'person' : 'people' %> whose hours are visible here</div></div>
      <% } %>
    </div>
  </div>

  <details class="aa-note b12"><summary>Roles and access</summary><div class="aa-note-b"><b>Staff</b> work on the clients they are assigned to. <b>Admin</b> also sees billing, API usage and the audit log, and can invite people and change roles.
      <br><br>
      A client user belongs to one workspace and cannot open another.
      <br><br>
      Assign clients from <b>Edit</b>. Account managers are set on each client's own page.</div></details>

  <div class="card shelf-c b3 sc-violet"><div class="cl">Clients covered</div><div class="cv tnum"><%- _covered ? _covered : '<span class="noval">—</span>' %></div></div>
  <div class="card shelf-c b3 sc-lime"><div class="cl">Account managers</div><div class="cv tnum"><%- _amCount ? _amCount : '<span class="noval">—</span>' %></div></div>
  <div class="card shelf-c b3 sc-navy"><div class="cl">On no client</div><div class="cv tnum"><%= _noClient %></div></div>
  <div class="card shelf-c b3 sc-sky"><div class="cl">Pending invites</div><div class="cv tnum"><%= _pending %></div></div>

  <% if(pending && pending.length){ %>

  <div class="card b12" id="invites">
    <div class="card-h"><h3>Pending invites</h3><span class="hint"><%= pending.length %> waiting</span></div>
    <div class="card-p" style="display:flex; flex-direction:column; gap:8px">
      <% pending.forEach(function(p){ %>
        <div class="row-between"><span><%= p.name || p.email %> <span class="rr-meta"><%= p.email %></span></span><span class="rr-meta">sent <%= h.timeAgo(p.createdAt) %>, expires <%= h.date(p.expiresAt) %></span></div>
      <% }) %>
    </div>
  </div>
  <% } %>

  <div class="card b12">
    <div class="card-h"><h3>Team members</h3><span class="hint"><%= isAdmin ? 'hours are this month' : '' %></span></div>
    <% if(!rows.length){ %>
      <div class="card-p rr-meta" style="text-align:center; padding:34px">No team members yet<%= isAdmin ? '. Invite someone above.' : '.' %></div>
    <% } else { %>
    <div style="overflow-x:auto">
      <table class="tbl">
        <thead><tr><th>Member</th><th>Title</th><th>Role</th><th>Hours (mo)</th><th>Clients</th><th>Status</th><th></th></tr></thead>
        <tbody>
          <% rows.forEach(function(r){ var m = r.m; %>
            <tr style="<%= m.active===false?'opacity:.55':'' %>">
              <td class="strong">
                <% if(m.avatarUrl){ %><img src="<%= m.avatarUrl %>" alt="" style="width:24px;height:24px;border-radius:50%;object-fit:cover;vertical-align:middle;margin-right:8px">
                <% } else { %><%- include('../partials/avatar', { url: m.avatarUrl, initials: m.initials || '—', color: m.avatarColor, name: m.name, cls: 'fav', size: 24, style: 'display:inline-flex;vertical-align:middle;margin-right:8px;' }) %><% } %>
                <%= m.name %><% if (m.isDemo) { %> <span class="chip flat" title="Seeded with the demo client">Demo</span><% } %>
                <div class="rr-meta" style="margin-left:32px"><%= m.email %></div>
              </td>
              <td class="muted"><%= m.title || '—' %></td>
              <td><span class="chip <%= m.role==='admin'?'navy':'flat' %>"><%= m.role %></span></td>

              <td class="num"><%- isAdmin ? (r.hours ? r.hours : '<span class="noval">—</span>') : '' %></td>
              <td>
                <% if (!r.clients.length) { %><span class="muted">none yet</span>
                <% } else { %>
                  <div class="cl-chips">
                    <% r.clients.forEach(function(c){ var am = String(c.accountManager||'') === String(m._id); %>
                      <span class="chip <%= am ? 'teal' : 'flat' %>" title="<%= am ? 'Account manager' : 'On the team' %>"><%= c.name %><%= am ? ' ★' : '' %></span>
                    <% }) %>
                  </div>
                  <div class="rr-meta" style="margin-top:3px"><%= r.clients.length %> client<%= r.clients.length===1?'':'s' %></div>
                <% } %>
              </td>
              <td><span class="chip <%= m.active===false?'neg':'pos' %>"><%= m.active===false?'Inactive':'Active' %></span></td>
              <td>
                <details>
                  <summary class="more" style="cursor:pointer; list-style:none">Edit</summary>
                  <form class="js-ajax-form" data-refresh="#staff-team-view" method="POST" action="/staff/team/<%= m._id %>" style="display:flex; flex-direction:column; gap:9px; padding:10px 0; min-width:210px">
                    <div class="fld"><label>Name</label><input name="name" value="<%= m.name %>"></div>
                    <div class="fld"><label>Title</label><input name="title" value="<%= m.title || '' %>"></div>
                    <% if (isAdmin) { %>
                      <div class="fld"><label>Role</label><select name="role"><option value="staff" <%= m.role==='staff'?'selected':'' %>>staff</option><option value="admin" <%= m.role==='admin'?'selected':'' %>>admin</option></select></div>
                      <div class="fld"><label>Status</label><select name="active"><option value="1" <%= m.active!==false?'selected':'' %>>Active</option><option value="0" <%= m.active===false?'selected':'' %>>Inactive</option></select></div>
                    <% } %>
                    <button class="btn btn-primary btn-sm" type="submit">Save</button>
                  </form>

                  <% if (isAdmin) { %>

                    <form class="js-ajax-form" data-refresh="#staff-team-view" method="POST" action="/staff/team/<%= m._id %>/clients"
                          style="border-top:1px solid var(--line-2); padding:11px 0 4px; min-width:230px">
                      <div class="fld"><label>Clients they work on</label></div>
                      <% if (!(allClients || []).length) { %>
                        <div class="rr-meta">No clients yet.</div>
                      <% } else { %>
                        <div class="cl-pick">
                          <% allClients.forEach(function(c){
                               var on = r.clients.some(function(x){ return String(x._id) === String(c._id); });
                               var am = String(c.accountManager || '') === String(m._id); %>
                            <label class="cl-opt<%= am ? ' is-am' : '' %>">
                              <input type="checkbox" name="clients" value="<%= c._id %>" <%= on ? 'checked' : '' %> <%= am ? 'disabled' : '' %>>
                              <% if (am) { %><input type="hidden" name="clients" value="<%= c._id %>"><% } %>
                              <span><%= c.name %><% if (c.isDemo) { %> <span class="rr-meta">demo</span><% } %></span>
                              <% if (am) { %><span class="chip teal" title="Account manager (change this on the client's own page)">AM</span><% } %>
                            </label>
                          <% }) %>
                        </div>
                        <div class="rr-meta" style="margin:7px 0 8px">
                          Being on a client is what lets someone open that client's data. Account managers are
                          locked here, and changing that happens on the client's page, where a replacement gets named.
                        </div>
                        <button class="btn btn-sm" type="submit">Save clients</button>
                      <% } %>
                    </form>
                  <% } %>
                </details>
              </td>
            </tr>
          <% }) %>
        </tbody>
      </table>
    </div>
    <% } %>
  </div>
</div>
</div>
