<%
  var sub = (ws && ws.subscription) || {};

  var isStaff = !!locals.showStaff && currentUser && currentUser.role === 'admin';

  var _inv      = invoices || [];
  var _paidRows = _inv.filter(function (i) { return i.status === 'paid'; });
  var _paid     = _paidRows.reduce(function (s, i) { return s + (i.amount || 0); }, 0);
  var _pendRows = _inv.filter(function (i) { return i.status === 'pending'; });
  var _total    = _inv.reduce(function (s, i) { return s + (i.amount || 0); }, 0);

  var _od      = function (i) { return i.status === 'pending' && i.dueDate && new Date(i.dueDate) < new Date(); };
  var _overdue = _pendRows.filter(_od).length;

  var _svgInv  = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><rect x="1.9" y="3.9" width="12.2" height="8.2" rx="1.6" stroke="currentColor" stroke-width="1.4"/><path d="M1.9 6.9h12.2" stroke="currentColor" stroke-width="1.4"/></svg>';
  var _svgDoc  = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M3.4 2.2h5.2l4 4v7.6a.8.8 0 0 1-.8.8H3.4a.8.8 0 0 1-.8-.8V3a.8.8 0 0 1 .8-.8z" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/><path d="M8.6 2.2v4.2h4" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/></svg>';
  var _svgMsg  = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M13.6 10.2a1.4 1.4 0 0 1-1.4 1.4H4.9L2.4 14V3.2a1.4 1.4 0 0 1 1.4-1.4h8.4a1.4 1.4 0 0 1 1.4 1.4z" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/></svg>';

  var _acts = [];

  _acts.push({ href: '/documents', lb: 'Contracts', ic: _svgDoc, lead: !isStaff });
  _acts.push({ href: '/messages',  lb: isStaff ? 'Message the client' : 'Message your manager', ic: _svgMsg });
  if (_pendRows.length) _acts.push({ href: '#history', lb: 'Awaiting payment', ic: _svgInv, n: _pendRows.length });
%>
<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Business</div>
  </div>
  <div class="ph-right">
    <%- include('../partials/range-picker') %></div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (pending && pending.amount) { %>
  <p class="claim-lede">You owe <em><%= h.money(pending.amount, pending.currency || sub.currency) %></em> right now.</p>
<% } else if (_paid) { %>
  <p class="claim-lede">You are paid up: <em><%= h.money(_paid, sub.currency) %></em> settled this year.</p>
<% } else if (_inv.length) { %>
  <p class="claim-lede">Nothing is outstanding.</p>
<% } else { %>
  <p class="claim-lede">No invoices yet.</p>
<% } %>
<p class="claim-sub"><%
  if (pending) { %>Invoice <b><%= pending.number %></b><% if (pending.dueDate) { %>, due <%= h.date(pending.dueDate) %><% } %>.<%
  } else if (_inv.length) { %>Your retainer and invoice history, paid by bank transfer.<%
  } else { %>Your retainer and invoice history, paid by bank transfer.<% }
%></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 (isStaff) { %>

<% var _invNewOpen = !!(locals.query && locals.query.new); %>
<div class="card card-p" id="new"<%= _invNewOpen ? '' : ' hidden' %> style="margin-top:22px">
  <div class="card-h" style="padding:0 0 12px"><h3>New invoice</h3><span class="rr-end"><a class="more js-panel-cancel" data-panel="#new" href="/invoices">Cancel</a></span></div>
  <form class="addform js-ajax-form" id="newinvoiceform" method="POST" action="/api/invoices"
        data-refresh="#invoices-body" data-hide-after="#new" data-reset-after="#newinvoiceform">
    <div class="fld"><label for="inv-new-number">Number</label><input id="inv-new-number" name="number" placeholder="#INV-2026-08"></div>
    <div class="fld"><label for="inv-new-period">Period</label><input id="inv-new-period" name="period" placeholder="Aug 2026"></div>
    <div class="fld" style="width:120px"><label for="inv-new-amount">Amount (<%= sub.currency || 'USD' %>)</label><input id="inv-new-amount" name="amount" type="number" min="0.01" step="0.01" required></div>
    <div class="fld"><label for="inv-new-duedate">Due date</label><input id="inv-new-duedate" name="dueDate" type="date" required></div>
    <div class="fld" style="flex:1 1 100%"><label for="inv-new-description">Description</label><input id="inv-new-description" name="description" placeholder="What this invoice covers" required></div>
    <button class="btn btn-primary btn-sm" type="submit">Create invoice</button>
  </form>
</div>
<% } %>

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

  <div class="vdark vd-cut b8">
    <span class="vn-fillet"></span>
    <% if (isStaff && pending) { %>
      <form class="inline-form js-ajax-form" data-refresh="#invoices-body" method="POST" action="/api/invoices/<%= pending._id %>/pay" style="position:absolute;top:0;right:0">
        <button class="vn-cut" type="submit">Mark paid
          <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M2.6 6.3l2.5 2.5 4.3-5" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
        </button>
      </form>
    <% } else if (isStaff) { %>
      <a class="vn-cut js-panel-open" data-panel="#new" href="/invoices?new=1#new">New invoice
        <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="/messages">Ask about it
        <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">Outstanding</div>
    <div class="vd-row">

      <div class="vd-num tnum"><%= pending ? h.money(pending.amount, pending.currency || sub.currency) : h.money(0, sub.currency) %></div>
      <% if(pending && pending.dueDate){ %><span class="vd-d flat">Due <%= h.date(pending.dueDate) %></span><% } %>
    </div>
    <div class="vd-sub">
      <% if(pending){ %>Payment details are on invoice <b><%= pending.number %></b>.
      <% } else { %><b>Nothing outstanding.</b><% } %>
    </div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov"><div class="ovl">Paid this year</div><div class="ovv tnum"><%- _paid ? h.money(_paid, sub.currency) : '<span class="noval">—</span>' %></div>
        <div class="rr-meta" style="margin-top:5px">over the <%= _paidRows.length %> invoice<%= _paidRows.length === 1 ? '' : 's' %> marked paid</div></div>
      <div class="ov"><div class="ovl">Monthly retainer</div><div class="ovv tnum"><%- sub.price ? h.money(sub.price, sub.currency) : '<span class="noval">—</span>' %></div>
        <div class="rr-meta" style="margin-top:5px"><%= sub.plan || 'no plan set yet' %></div></div>
      <div class="ov"><div class="ovl">Invoiced in total</div><div class="ovv tnum"><%- _total ? h.money(_total, sub.currency) : '<span class="noval">—</span>' %></div>
        <div class="rr-meta" style="margin-top:5px">the <%= _inv.length %> invoice<%= _inv.length === 1 ? '' : 's' %> listed below</div></div>
    </div>
  </div>

  <div class="card card-p rr b4">
    <div class="rr-lbl">Subscription</div>
    <div class="rr-title"><%= sub.plan || 'No plan set' %></div>
    <div class="rr-meta"><% if(sub.price){ %><%= h.money(sub.price, sub.currency) %> a month, billed monthly<% } else { %>Your VOCTOS team will confirm your retainer.<% } %></div>
    <div class="divider" style="margin:14px 0"></div>
    <div class="rr-meta">Questions about your plan or an invoice? <a href="/messages" style="color:var(--teal-600)">Message your account manager</a>.</div>
  </div>

  <div class="card shelf-c b3 sc-violet"><div class="cl">Invoices</div><div class="cv tnum"><%= _inv.length %></div></div>
  <div class="card shelf-c b3 sc-lime"><div class="cl">Paid</div><div class="cv tnum"><%= _paidRows.length %></div></div>
  <div class="card shelf-c b3 sc-navy"><div class="cl">Awaiting payment</div><div class="cv tnum"><%= _pendRows.length %></div></div>
  <div class="card shelf-c b3 sc-sky"><div class="cl">Overdue</div><div class="cv tnum"><%= _overdue %></div></div>

  <div class="card b8" id="history">
    <div class="card-h"><h3>Payment history</h3><span class="hint">all invoices</span><span class="rr-end"><%- h.ihelp('Invoices and payment',
      '<b>Paid this year</b> counts invoices marked paid in the range shown. <b>Awaiting payment</b> is anything issued '
      + 'and not yet settled. An unpaid invoice past its due date is counted as overdue as well.') %></span></div>
    <div style="overflow-x:auto">
      <% if(!invoices.length){ %><%- include('../partials/empty', { title: 'No invoices yet', line: isStaff ? 'Raise the first one for this client.' : 'Invoices from your VOCTOS team appear here.', cta: isStaff ? { href: '/invoices?new=1#new', label: 'New invoice', cls: 'js-panel-open', attrs: ' data-panel="#new"' } : null }) %><% } else { %>

      <table class="tbl" data-clarity-mask="true"><thead><tr><th>Invoice</th><th>Period</th><th>Amount</th><th>Status</th><th>Date</th><th></th></tr></thead><tbody>
        <% invoices.forEach(function(i){ %>

          <tr id="inv-<%= i._id %>">
            <td class="strong"><%= i.number %><% if(i.description){ %><div class="rr-meta"><%= i.description %></div><% } %></td><td class="muted"><%= i.period %></td><td class="num"><%= h.money(i.amount, i.currency || sub.currency) %></td>
            <td><span class="tag <%= i.status==='paid'?'paid':(_od(i)?'overdue':'pending') %>"><%= i.status==='paid'?'Paid':(_od(i)?'Overdue':'Pending') %></span></td>
            <td class="muted"><%= i.status==='pending' ? 'due '+h.date(i.dueDate) : h.date(i.issuedDate) %></td>
            <td style="white-space:nowrap"><% if(i.status==='pending' && isStaff){ %><form class="inline-form js-ajax-form" data-refresh="#invoices-body" method="POST" action="/api/invoices/<%= i._id %>/pay"><button class="more" style="background:none;border:0;cursor:pointer;color:var(--teal-600)">Mark paid</button></form><% } else if(i.status==='pending'){ %><span class="muted">Awaiting payment</span><% } else { %><a class="more">PDF</a><% } %><% if(isStaff){ %> <form class="inline-form js-delete-form" data-confirm="Delete this invoice?" data-refresh="#invoices-body" method="POST" action="/api/invoices/<%= i._id %>/delete"><button class="icon-btn" title="Delete" aria-label="Delete invoice">&times;</button></form><% } %></td>
          </tr>
        <% }) %>
      </tbody></table><% } %>
    </div>
  </div>

  <div class="card card-p rr b4">
    <div class="rr-lbl">How to pay</div>
    <div class="rr-title">Bank transfer</div>
    <div class="rr-meta">Payment details are on each invoice. Your account manager marks it paid once the transfer arrives.</div>
  </div>
</div>
