<%
  var c = cfg || {};
  var connected = workspaces.filter(function(w){ return w.trello && w.trello.boardId; });
  var labelsReady = function(w){
    var L = (w.trello && w.trello.labels) || {};
    return !!(L.todo && L.in_progress && L.done);
  };
  var KIND = {
    'created-card': { chip: 'pos',  label: 'card created' },
    'created-task': { chip: 'pos',  label: 'task imported' },
    'to-trello':    { chip: 'teal', label: '→ Trello' },
    'to-portal':    { chip: 'teal', label: '→ portal' },
    'conflict':     { chip: 'warn', label: 'conflict' },
    'skipped':      { chip: 'flat', label: 'skipped' },
    'error':        { chip: 'neg',  label: 'error' }
  };

  var _labelled = connected.filter(labelsReady).length;
  var _failing  = workspaces.filter(function(w){ return w.trello && w.trello.lastError; }).length;

  var _svgBolt = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M9 1.6L3.6 9h3.6l-.6 5.4L12.4 7H8.8z" stroke="currentColor" stroke-width="1.3" stroke-linejoin="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 _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 _svgList = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M5.4 4.2h8M5.4 8h8M5.4 11.8h8M2.6 4.2h.01M2.6 8h.01M2.6 11.8h.01" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>';

  var _acts = [];
  _acts.push({ href: '/staff/automation',      lb: 'Automation',      ic: _svgBolt, lead: true });
  _acts.push({ href: '#boards',                lb: 'Boards',          ic: _svgGrid, n: connected.length });
  _acts.push({ href: '#changelog',             lb: 'Change log',      ic: _svgList });
  _acts.push({ href: '/staff/mission-control', lb: 'Mission Control', ic: _svgDial });
%>

<div id="staff-trello-view">
<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Operations / Trello</div>
  </div>
  <div class="ph-right" style="display:flex; gap:8px; align-items:center">
    <span class="chip <%= c.enabled ? 'pos' : 'flat' %>">Sync <%= c.enabled ? 'on' : 'off' %></span>
  </div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (!configured) { %>
  <p class="claim-lede">Trello has no credentials here, so nothing syncs.</p>
<% } else if (_failing) { %>
  <p class="claim-lede"><em><%= _failing %></em> board<%= _failing === 1 ? '' : 's' %> failed on the last sync.</p>
<% } else if (connected.length && c.enabled) { %>
  <p class="claim-lede"><em><%= connected.length %></em> client board<%= connected.length === 1 ? '' : 's' %> in step with the portal.</p>
<% } else if (connected.length) { %>
  <p class="claim-lede"><em><%= connected.length %></em> board<%= connected.length === 1 ? ' is' : 's are' %> connected, with sync switched off.</p>
<% } else { %>
  <p class="claim-lede">No client has a board yet.</p>
<% } %>
<p class="claim-sub">One board per client. Tasks sync both ways <%= h.cronText(cron) %><%= scheduled ? '' : ' when schedules are on (they are off now)' %>.</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>

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

  <% if (!configured) { %>
  <div class="card card-p b12" style="border-color:var(--warn)">
    <b>Not connected.</b> The server needs a Trello API key and token. Send both to the developer to add.
    <div class="rr-meta">
      Get the pair at <a href="https://trello.com/power-ups/admin" target="_blank" rel="noopener">trello.com/power-ups/admin</a>:
      create a Power-Up to get the key, then generate a token for it.
      The token can read and write every board that account can see, so use a dedicated VOCTOS account.
    </div>
  </div>
  <% } %>

  <div class="vdark<%= (configured && connected.length) ? ' vd-cut vd-cut-sm' : '' %> b12">
    <% if (configured && connected.length) { %>
      <span class="vn-fillet"></span>

      <form class="inline-form js-async-run" method="POST" action="/staff/trello/sync" style="position:absolute;top:0;right:0">

        <input type="hidden" name="all" value="1">
        <button class="vn-cut" type="submit">Sync all <%= connected.length %>
          <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M10 6a4 4 0 11-1.2-2.85M10 1.6V4H7.6" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
        </button>
      </form>
    <% } %>
    <div class="vd-k">Boards connected</div>
    <div class="vd-row">
      <div class="vd-num tnum"><%= connected.length %></div>
    </div>
    <div class="vd-sub">Out of <b><%= workspaces.length %></b> client<%= workspaces.length === 1 ? '' : 's' %>. A client without a board is not out of sync, because there is simply nothing to read.</div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov"><div class="ovl">Linked tasks</div><div class="ovv tnum"><%= linked %></div>
        <div class="rr-meta" style="margin-top:5px">of <%= linked + unlinked %> tasks in the portal</div></div>
      <div class="ov"><div class="ovl">Not linked</div><div class="ovv tnum"><%= unlinked %></div></div>
      <div class="ov"><div class="ovl">Labels ready</div><div class="ovv tnum"><%= _labelled %></div>
        <div class="rr-meta" style="margin-top:5px">of <%= connected.length %> connected</div></div>

      <div class="ov"><div class="ovl">Last run</div><div class="ovv tnum" style="font-size:var(--fs-lg)"><%- (lastRun && lastRun.startedAt) ? h.timeAgo(lastRun.startedAt) : '<span class="noval">—</span>' %></div>
        <% if (lastRun && lastRun.startedAt && lastRun.summary) { %><div class="rr-meta clamp2" style="margin-top:5px" title="<%= lastRun.summary %>"><%= lastRun.summary %></div><% } %></div>
    </div>

    <% var _liveOn = live && live.ok; var _liveCount = connected.filter(function (w) { return w.trello && w.trello.webhookId; }).length; %>
    <div style="margin-top:16px; padding-top:14px; border-top:1px solid var(--line-2)">
      <span class="chip <%= _liveOn && _liveCount ? 'pos' : 'flat' %>"><%= _liveOn && _liveCount ? 'Live' : 'Not live' %></span>
      <span class="rr-meta" style="margin-left:8px">
        <% if (!_liveOn) { %>
          Changes arrive on the scheduled check only (<%= h.cronText(cron) %>). <%= live ? live.why : '' %>
        <% } else if (!_liveCount) { %>
          Trello can reach us, but no board is registered yet. Reconnect a client, or wait for the hourly check.
        <% } else { %>
          <b><%= _liveCount %></b> of <%= connected.length %> connected board<%= connected.length === 1 ? '' : 's' %> push changes here as they happen, with a scheduled check <%= h.cronText(cron) %> as backup.
        <% } %>
      </span>
    </div>
  </div>

  <details class="aa-note b12"><summary>What crosses over <span class="chip <%= c.enabled ? 'pos' : 'flat' %>"><%= c.enabled ? 'On' : 'Off' %></span></summary><div class="aa-note-b"><b>Tasks</b> come from the last column only. Columns to its left stay internal.
      <br><br>
      A card's <b>label</b> sets its status. A card with no status label, or two, is skipped.
      <br><br>
      Title, description, status and due date sync both ways. Category and priority are written to Trello but not read back.
      <br><br>
      <b>Roadmap</b> reads every open list as one month. Items added by hand in the portal are never changed.</div></details>

  <div class="card shelf-c b4 sc-violet"><div class="cl">Clients</div><div class="cv tnum"><%= workspaces.length %></div></div>
  <div class="card shelf-c b4 sc-lime"><div class="cl">With a board</div><div class="cv tnum"><%= connected.length %></div></div>
  <div class="card shelf-c b4 sc-sky"><div class="cl">Failing</div><div class="cv tnum"><%= _failing %></div></div>

  <div class="card b12" id="boards">
    <div class="card-h">
      <h3>Boards</h3>
      <span class="hint">one per client</span>
    </div>
    <div style="overflow-x:auto">
      <table class="tbl">
        <thead><tr><th>Client</th><th>Board</th><th>Column we read</th><th>Labels</th><th>Last run</th><th></th></tr></thead>
        <tbody>
          <% workspaces.forEach(function(w){ var t = w.trello || {}; %>
            <tr>
              <td class="strong"><%= w.name %><% if(w.isDemo){ %> <span class="chip flat">demo</span><% } %></td>
              <td>
                <% if (t.boardId) { %>
                  <a href="<%= t.boardUrl %>" target="_blank" rel="noopener"><%= t.boardName || t.boardId %> ↗</a>
                <% } else { %>

                  <form class="formrow js-async-run" method="POST" action="/staff/trello/connect/<%= w.slug %>" style="gap:6px; align-items:center">
                    <input name="boardId" placeholder="board link or id (blank creates one)" style="min-width:230px">
                    <button class="btn btn-sm" type="submit" <%= configured ? '' : 'disabled' %>>Connect</button>
                  </form>
                <% } %>
              </td>
              <td class="muted"><%= t.listName || '—' %></td>
              <td>
                <% if (!t.boardId) { %><span class="muted">—</span>
                <% } else if (labelsReady(w)) { %><span class="chip teal">Ready</span>
                <% } else { %><span class="chip warn">created on the next sync</span><% } %>
              </td>
              <td class="muted" style="white-space:nowrap">
                <% if (t.lastError) { %><span style="color:var(--neg)" title="<%= t.lastError %>">failed <%= t.lastPollAt ? h.timeAgo(t.lastPollAt) : '' %></span>
                <% } else if (t.lastPollAt) { %><%= h.timeAgo(t.lastPollAt) %><div class="rr-meta" style="white-space:normal"><%= h.syncResult(t.lastResult) %></div>
                <% } else if (t.boardId) { %>never
                <% } else { %>—<% } %>
              </td>
              <td style="white-space:nowrap">
                <% if (t.boardId) { %>

                  <form class="inline-form js-async-run" method="POST" action="/staff/trello/sync" style="display:inline">
                    <input type="hidden" name="slug" value="<%= w.slug %>">
                    <button class="btn btn-sm" type="submit">Sync</button>
                  </form>

                  <form class="inline-form js-ajax-form" data-refresh="#staff-trello-view" method="POST" action="/staff/trello/disconnect/<%= w.slug %>" style="display:inline">
                    <button class="btn btn-sm" type="submit" title="Forget this board. The board, its cards and their tasks are all left alone.">Unlink</button>
                  </form>
                <% } %>
              </td>
            </tr>
          <% }) %>
        </tbody>
      </table>
    </div>
    <div class="card-p rr-meta" style="padding-top:10px">
      <span class="ihelp-w" tabindex="0" role="button" aria-label="How a card becomes a task"><svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><circle cx="8" cy="8" r="6.4" stroke="currentColor" stroke-width="1.4"/><path d="M8 7.1v4M8 4.9v.1" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg> How a card becomes a task<span class="ihelp-pop" role="tooltip"><b>How a card becomes a task</b>A card typed straight into a client's board becomes one of their tasks, but only from
      <b>the last column</b>, and only once it carries one of
      <% statusLabels.forEach(function(sl, i){ %><b><%= sl[1] %></b><%= i < statusLabels.length - 1 ? ', ' : '' %><% }) %>.
      Anything to the left of that column is yours to work in; nothing there reaches the client.</span></span>
    </div>
  </div>

  <div class="card b12" id="changelog">
    <div class="card-h"><h3>Change log</h3><span class="hint">newest first, including conflicts</span></div>
    <div style="overflow-x:auto">
      <% if (!logs.length) { %>
        <div class="card-p rr-meta" style="text-align:center; padding:30px">Nothing yet. Every card created, field copied and conflict resolved is recorded here.</div>
      <% } else { %>
      <table class="tbl">
        <thead><tr><th>When</th><th>What</th><th>Client</th><th>Field</th><th>Became</th><th>Overwrote</th><th>Note</th></tr></thead>
        <tbody>
          <% logs.forEach(function(l){ var k = KIND[l.kind] || { chip:'flat', label: l.kind }; %>
            <tr>
              <td class="muted" style="white-space:nowrap"><%= h.timeAgo(l.at) %></td>
              <td><span class="chip <%= k.chip %>"><%= k.label %></span><% if(l.winner){ %> <span class="rr-meta"><%= l.winner %> won</span><% } %></td>
              <td class="muted"><%= l.workspace ? l.workspace.name : '—' %></td>
              <td class="muted" style="white-space:nowrap"><%= l.field || '—' %></td>
              <td class="wrap"><%= l.value ? String(l.value).slice(0,90) : '—' %></td>

              <td class="wrap"><% if(l.overwrote){ %><span style="color:var(--neg)"><%= String(l.overwrote).slice(0,90) %></span><% } else { %>—<% } %></td>
              <td class="muted wrap"><%= l.note || '' %></td>
            </tr>
          <% }) %>
        </tbody>
      </table>
      <% } %>
    </div>
  </div>
</div>
</div>
