<%

  var _jobs  = jobs || [];
  var _sched = _jobs.filter(function (j) { return j.scheduled; }).length;
  var _failed = _jobs.filter(function (j) { return j.last && j.last.ok === false; }).length;
  var _never  = _jobs.filter(function (j) { return !j.last; }).length;
  var _paid   = _jobs.filter(function (j) { return j.def.cost === 'paid'; }).length;
  var _ran    = _jobs.filter(function (j) { return j.last && j.last.startedAt; });
  var _latest = _ran.length ? _ran.map(function (j) { return j.last; }).sort(function (a, b) {
    return new Date(b.startedAt) - new Date(a.startedAt);
  })[0] : null;

  var _svgTrello = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><rect x="2" y="2.4" width="12" height="11.2" rx="1.8" stroke="currentColor" stroke-width="1.3"/><rect x="4.2" y="4.6" width="3.2" height="6.6" rx=".8" stroke="currentColor" stroke-width="1.2"/><rect x="8.6" y="4.6" width="3.2" height="4" rx=".8" stroke="currentColor" stroke-width="1.2"/></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 _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 _acts = [];

  if (_jobs.length) _acts.push({ href: '#jobs', lb: 'The jobs', ic: _svgBolt, lead: true, n: _jobs.length });
  _acts.push({ href: '/staff/trello',          lb: 'Trello Sync',     ic: _svgTrello });
  _acts.push({ href: '/staff/clients',         lb: 'All clients',     ic: _svgGrid });
  _acts.push({ href: '/staff/mission-control', lb: 'Mission Control', ic: _svgDial });
%>
<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Operations / Automation</div>
  </div>
  <div class="ph-right"><%- include('../partials/demo-toggle') %></div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (_failed) { %>
  <p class="claim-lede"><em><%= _failed %></em> job<%= _failed === 1 ? '' : 's' %> failed on the last run.</p>
<% } else if (!schedulerOn) { %>
  <p class="claim-lede">Nothing runs on its own, because schedules are switched off.</p>
<% } else if (_sched) { %>
  <p class="claim-lede"><em><%= _sched %></em> job<%= _sched === 1 ? ' runs' : 's run' %> on a schedule of <%= _sched === 1 ? 'its' : 'their' %> own.</p>
<% } else { %>
  <p class="claim-lede">No job is on a schedule right now.</p>
<% } %>
<p class="claim-sub">Syncs, AI engine runs and reputation checks. If a job fails, clients keep seeing the previous data, so check the last-run time. <b>Run now</b> does exactly what the schedule does.</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(!schedulerOn){ %>
  <div class="card card-p b12" style="border-color:var(--warn)">
    <b>Schedules are switched off</b> on the server, so nothing runs automatically. <b>Run now</b> still works.
  </div>
  <% } %>

  <div class="vdark vd-cut vd-cut-sm b8">
    <span class="vn-fillet"></span>

    <% if (_jobs.length) { %>
    <a class="vn-cut" href="#jobs">Run a job
      <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M3.4 2.4l5.6 3.6-5.6 3.6z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></svg>
    </a>
    <% } %>
    <div class="vd-k">On a schedule</div>
    <div class="vd-row">
      <div class="vd-num tnum"><%= _sched %></div>
    </div>
    <div class="vd-sub">Of <b><%= _jobs.length %></b> job<%= _jobs.length === 1 ? '' : 's' %><%= schedulerOn ? '' : ', with schedules switched off' %>. The rest only run from <b>Run now</b>.</div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov"><div class="ovl">Failed last run</div><div class="ovv tnum"><%= _failed %></div></div>
      <div class="ov"><div class="ovl">Never run</div><div class="ovv tnum"><%= _never %></div></div>
      <div class="ov"><div class="ovl">Cost money to run</div><div class="ovv tnum"><%= _paid %></div>
        <div class="rr-meta" style="margin-top:5px">paid engine calls, per prompt</div></div>

      <div class="ov"><div class="ovl">Anything run</div><div class="ovv tnum" style="font-size:var(--fs-lg)"><%- _latest ? h.timeAgo(_latest.startedAt) : '<span class="noval">—</span>' %></div>
        <% if (_latest) { %><div class="rr-meta" style="margin-top:5px">the most recent of any job</div><% } %></div>
    </div>
  </div>

  <div class="card card-p b4">
    <div class="card-h" style="padding:0 0 12px"><h3>Server switches</h3></div>

    <div style="display:flex; flex-direction:column; gap:10px; font-size:var(--fs-sm)">
      <div class="row-between"><span>Scheduled jobs</span><span class="chip <%= env.syncEnabled?'pos':'neg' %>"><%= env.syncEnabled?'on':'off' %></span></div>
      <div class="row-between"><span>Site crawler</span><span class="chip <%= env.crawl?'pos':'flat' %>"><%= env.crawl?'on':'off' %></span></div>
      <div class="row-between"><span>AI web search</span><span class="chip <%= env.webSearch?'pos':'flat' %>"><%= env.webSearch?'on':'off' %></span></div>
    </div>
    <div class="rr-meta" style="margin-top:12px; line-height:1.65">
      These and each job's schedule are set in the server configuration, so a switch that costs money cannot be flipped by accident.
    </div>
  </div>

  <% _jobs.forEach(function(j, i){ var l = j.last; %>
    <div class="card b12"<%- i === 0 ? ' id="jobs"' : '' %>>
      <div class="card-h">
        <h3><%= j.def.label %></h3>
        <span class="chip <%= j.def.cost==='paid'?'warn':'flat' %>"><%= j.def.cost==='paid'?'costs money':'free' %></span>
        <span class="hint" style="margin-left:auto"><%= j.scheduled ? 'Runs ' + h.cronText(j.cron) + (j.external ? ' (cPanel cron)' : '') : 'Not scheduled' %></span>
      </div>
      <div class="card-p">
        <div class="rr-meta" style="margin-bottom:12px"><%= j.def.what %></div>

        <div class="row-between" style="gap:12px; flex-wrap:wrap">
          <div>
            <% if(!l){ %>
              <span class="rr-meta">Never run yet.</span>
            <% } else { %>
              <span class="chip <%= l.ok===false?'neg':(l.finishedAt?'pos':'warn') %>"><%= l.ok===false ? 'failed' : (l.finishedAt ? 'ok' : 'running…') %></span>
              <span class="rr-meta" style="margin-left:8px">
                last run <%= h.timeAgo(l.startedAt) %> (<%= l.trigger === 'cron' ? 'scheduled' : l.trigger %><% if(l.ms){ %>, <%= (l.ms/1000).toFixed(1) %>s<% } %><% if(l.workspacesRun){ %>, <%= l.workspacesRun %> client<%= l.workspacesRun===1?'':'s' %><% } %>)
              </span>
            <% } %>
          </div>
          <form method="POST" action="/staff/automation/<%= j.key %>/run" class="inline-form js-async-run" style="gap:8px"
                <%= j.def.cost==='paid' ? 'onsubmit="return confirm(\'This calls the paid AI engines for every tracked prompt. Run it now?\')"' : '' %>>

            <select class="picker picker-sm" name="workspace">
              <option value=""><%= locals.isAdmin ? 'All clients' : 'My clients' %></option>
              <% workspaces.forEach(function(w){ %><option value="<%= w._id %>"><%= w.name %><%= w.isDemo ? ' (demo)' : '' %></option><% }) %>
            </select>
            <button class="btn <%= j.def.cost==='paid'?'btn-sm':'btn-primary btn-sm' %>" type="submit">Run now</button>
          </form>
        </div>

        <% if(l && l.error){ %><div class="rr-meta" style="margin-top:10px; color:var(--neg)"><%= l.error %></div><% } %>

        <% if(l && l.summary){ %><div class="bubble" style="margin-top:10px; font-size:var(--fs-sm); white-space:pre-wrap; max-height:120px; overflow:auto"><%= l.summary %></div><% } %>

        <% if(j.runs.length > 1){ %>
          <details style="margin-top:12px">
            <summary class="more" style="cursor:pointer">Recent runs</summary>

            <div style="overflow-x:auto">
            <table class="tbl" style="margin-top:8px">
              <thead><tr><th>Started</th><th>Trigger</th><th>Clients</th><th>Took</th><th>Result</th></tr></thead>
              <tbody>
                <% j.runs.forEach(function(r){ %>
                  <tr>
                    <td class="muted"><%= h.timeAgo(r.startedAt) %></td>
                    <td class="muted"><%= r.trigger === 'cron' ? 'scheduled' : r.trigger %></td>
                    <td class="num"><%- r.workspacesRun ? r.workspacesRun : '<span class="noval">—</span>' %></td>
                    <td class="num muted"><%- r.ms ? (r.ms/1000).toFixed(1)+'s' : '<span class="noval">—</span>' %></td>
                    <td><span class="chip <%= r.ok===false?'neg':(r.finishedAt?'pos':'warn') %>"><%= r.ok===false ? 'failed' : (r.finishedAt?'ok':'running') %></span></td>
                  </tr>
                <% }) %>
              </tbody>
            </table>
            </div>
          </details>
        <% } %>
      </div>
    </div>
  <% }) %>
</div>
