<%
var cfg = locals.cfg || {};
var cur = cfg.currency || 'USD';
var SYM = { USD:'$', EUR:'€', GBP:'£', EGP:'E£', SAR:'SAR ', AED:'AED ' };
function m(n){
  if (n === undefined || n === null) return '—';
  var s = SYM[cur] || (cur + ' '), v = Number(n);
  var dp = Math.abs(v) < 100 ? 2 : 0;
  return s + v.toLocaleString('en-US', { minimumFractionDigits: dp, maximumFractionDigits: dp });
}

var _staff = (locals.canPush === true && !locals.isExport) || (locals.showStaff);
var creatives = locals.creatives || [], changes = locals.changes || [], requests = locals.requests || [];
var names = locals.names || {}, publishing = locals.publishing || {};
var nothing = !creatives.length && !changes.length && !requests.length;

var queued = changes.filter(function(c){ return c.status === 'queued' || c.status === 'sent'; }).length;
var failed = changes.filter(function(c){ return c.status === 'failed'; }).length;

var onUs = locals.waitingOnUs, onGoogle = locals.waitingOnGoogle;
var nov = '<span class="noval">—</span>';

var VERB = { add_negative:'Add negative', remove_negative:'Remove negative', add_keyword:'Add keyword',
             pause_keyword:'Pause keyword', enable_ad:'Switch on ad', apply_draft:'Apply campaign draft' };
var STATE = { queued:'queued', sent:'with the script', applied:'applied in Google', failed:'failed', cancelled:'cancelled' };

var _svgPen = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M11.2 2.4l2.4 2.4-8 8-3.2.8.8-3.2z" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/></svg>';
var _svgKey = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><circle cx="7" cy="7" r="4.4" stroke="currentColor" stroke-width="1.4"/><path d="M10.3 10.3l3.1 3.1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>';
var _svgTask = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><rect x="2.4" y="2.4" width="11.2" height="11.2" rx="2" stroke="currentColor" stroke-width="1.4"/><path d="M5.2 8.2l2 2 3.6-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
var _acts = [];
_acts.push({ href:'/ppc/keywords',  lb:'Keywords & terms', ic:_svgKey, lead: !_staff });
_acts.push({ href:'/ppc/creatives', lb:'Ad creatives', ic:_svgPen, lead: _staff, n: _staff ? creatives.length : 0 });
if (_staff) _acts.push({ href:'/tasks', lb:'Tasks', ic:_svgTask, n: requests.length });
%>

<div id="ppc-approvals-view">
<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Paid Media / Approvals</div>
  </div>
  <div class="ph-right">
    <% if (onUs) { %><span class="chip warn"><%= onUs %> waiting on <%= _staff ? 'us' : 'VOCTOS' %></span><% } %>
    <% if (onGoogle) { %><span class="chip flat"><%= onGoogle %> waiting on Google</span><% } %>
  </div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (failed) { %>
  <p class="claim-lede"><em><%= failed %></em> change<%= failed === 1 ? '' : 's' %> failed and <%= failed === 1 ? 'is' : 'are' %> going nowhere.</p>
<% } else if (nothing) { %>
  <p class="claim-lede">Nothing in Paid Media is waiting on anyone.</p>
<% } else if (onUs) { %>
  <p class="claim-lede"><em><%= onUs %></em> thing<%= onUs === 1 ? '' : 's' %> <%= onUs === 1 ? 'is' : 'are' %> waiting on <%= _staff ? 'us' : 'VOCTOS' %>.</p>
<% } else if (onGoogle) { %>
  <p class="claim-lede">Everything is with Google, with <em><%= onGoogle %></em> item<%= onGoogle === 1 ? '' : 's' %> in review.</p>
<% } else { %>
  <p class="claim-lede">Nothing waiting on a decision.</p>
<% } %>
<p class="claim-sub"><% if (_staff) { %>Everything in Paid Media waiting on a decision or on Google. <% } else { %>What you have asked for, and where it has got to.<% } %> <%- h.ihelp('What lands on this page',
  'Everything in Paid Media waiting on a decision, on a sync, or on Google\'s own review. Each row lives on its own page '
  + '(Ad Creatives, Keywords &amp; Terms) and is gathered here.'
  + '<br><br>A change reaches Google on the next scheduled run. <b>Waiting on Google</b> means it is in Google\'s review.') %></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">

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

    <% if (_staff && creatives.length) { %>
      <a class="vn-cut" href="#adcopy">Approve ad copy
        <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M2.5 6l2.6 2.6L9.8 3.4" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </a>
    <% } else { %>
      <a class="vn-cut" href="/ppc/keywords?tab=terms">Ask for a change
        <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M6 2v8M2 6h8" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>
      </a>
    <% } %>
    <div class="vd-k">Waiting on <%= _staff ? 'us' : 'VOCTOS' %></div>
    <div class="vd-row">
      <div class="vd-num tnum"><% if (onUs != null) { %><%= onUs %><% } else { %><%- nov %><% } %></div>
    </div>
    <div class="vd-sub"><% if (_staff) { %>Ad copy without a decision, open client requests, and changes that failed to apply.<% } else { %>What VOCTOS still has to decide on or act on for you.<% } %></div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov"><div class="ovl">Waiting on Google</div>
        <div class="ovv tnum"><% if (onGoogle != null) { %><%= onGoogle %><% } else { %><%- nov %><% } %></div>
        <div class="rr-meta" style="margin-top:5px">in Google's review</div></div>
      <div class="ov"><div class="ovl">Queued for the account</div>
        <div class="ovv tnum"><%= queued %></div>
        <div class="rr-meta" style="margin-top:5px"><%= _staff ? 'written to the sheet the Ads Script owns' : 'sent, waiting for Google Ads to apply it' %></div></div>
      <div class="ov"><div class="ovl">Could not be applied</div>
        <div class="ovv tnum"><%= failed %></div>
        <div class="rr-meta" style="margin-top:5px"><%= _staff ? 'the script tried and Google refused' : 'Google Ads refused the change' %></div></div>
      <div class="ov"><div class="ovl"><%= _staff ? 'Open client requests' : 'Your open requests' %></div>
        <div class="ovv tnum"><%= requests.length %></div>
        <div class="rr-meta" style="margin-top:5px">a person reads and decides on each one</div></div>
    </div>
  </div>

  <%

    var _shelf = [
      { l: 'Changes on this page', v: changes.length }
    ];
    if (_staff) _shelf.push({ l: 'Ad copy gathered here', v: creatives.length });
    var _sw = { 1:'b12', 2:'b6', 3:'b4', 4:'b3', 6:'b2', 12:'b1' }[_shelf.length] || 'b2';
    var _tints = ['sc-violet', 'sc-lime', 'sc-navy', 'sc-sky', 'sc-sand', 'sc-rose'];
  %>
  <% _shelf.forEach(function (s, i) { %>
    <div class="card shelf-c <%= _sw %> <%= _tints[i % _tints.length] %>">
      <div class="cl"><%= s.l %></div>
      <div class="cv tnum"><%= s.v %></div>
    </div>
  <% }) %>

  <% if (nothing) { %>

  <div class="voff b12">
    <div class="voff-h"><b>Nothing is waiting.</b></div>
    <div class="voff-i">
      <% if (_staff) { %>
        <span class="n">No ad is in review, no change is queued for the account, and no client request is open.</span>
      <% } else { %>
        <span class="n">No open requests on Paid Media.</span>
        <a href="/ppc/keywords?tab=terms">Ask for a change</a>
      <% } %>
    </div>
  </div>
  <% } %>

  <% if (_staff && creatives.length) { %>
  <div class="card b12" id="adcopy">
    <div class="card-h"><h3>Ad copy</h3><span class="hint">built in Google Ads, waiting to go live</span>
      <a class="more" href="/ppc/creatives">Open Ad Creatives</a></div>
    <div class="card-p" style="padding-bottom:0">

      <div class="muted" style="font-size:var(--fs-sm)">Approving records the decision; switching on is the separate step after it.</div>
    </div>
    <div style="overflow-x:auto">
    <table class="tbl">
      <thead><tr>
        <th>Ad</th><th>Where</th><th>Assets</th><th>Status</th><th></th>
      </tr></thead>
      <tbody>
      <% creatives.forEach(function(a){
           var hs = a.headlines || [], ds = a.descriptions || [];
           var pub = publishing[String(a._id)];
      %>
        <tr>
          <td class="strong" style="max-width:320px">
            <a href="/ppc/creatives"><%= hs[0] || '(no headline read from the account)' %></a>

            <div class="muted" style="font-size:var(--fs-xs);font-weight:500">
              <% if (a.origin === 'draft') { %>Campaign draft “<%= a.draftName || 'untitled' %>”
              <% } else if (a.origin === 'paused') { %>Paused in the account
              <% } else { %>Written in the portal, not in Google Ads yet<% } %>
            </div>
          </td>
          <td class="muted"><%= a.baseCampaignName || names[String(a.campaign)] || '—' %><%= a.adGroupName ? ' · ' + a.adGroupName : '' %></td>
          <td class="num">
            <%= hs.length %>/15 headlines
            <% if (hs.length && hs.length < 15) { %><span class="chip warn"><%= 15 - hs.length %> short</span><% } %>

            <div class="muted" style="font-size:var(--fs-xs)"><%= ds.length %>/4 descriptions</div>
          </td>
          <td>
            <% if (a.status === 'approved') { %>
              <span class="chip pos">approved</span>
              <% if (pub) { %><span class="chip warn"><%= pub === 'sent' ? 'with the script' : 'queued' %></span><% } %>
            <% } else { %><span class="chip warn">in review</span><% } %>
          </td>
          <td>
            <% if (a.status !== 'approved') { %>
              <form class="inline-form js-ajax-form" data-refresh="#ppc-approvals-view" method="POST" action="/ppc/creatives/<%= a._id %>/approve">
                <button class="btn btn-sm btn-primary" type="submit">Approve</button>
              </form>
            <% } else if (!pub && a.source === 'google') { %>

              <form class="inline-form js-ajax-form" data-refresh="#ppc-approvals-view" method="POST" action="/ppc/creatives/<%= a._id %>/publish"
                    <% if (a.origin === 'draft') { %>data-confirm="Apply the draft “<%= a.draftName || 'untitled' %>”?&#10;&#10;This lands EVERY change in that draft on the live campaign at once, not just this ad."<% } %>>
                <button class="btn btn-sm btn-primary" type="submit"><%= a.origin === 'draft' ? 'Apply draft' : 'Switch it on' %></button>
              </form>
            <% } else if (!pub) { %>

              <span class="muted" style="font-size:var(--fs-xs)">Build it in Google Ads first</span>
            <% } %>
          </td>
        </tr>
      <% }) %>
      </tbody>
    </table>
    </div>
  </div>
  <% } %>

  <% if (changes.length) { %>
  <div class="card b12">
    <div class="card-h"><h3>Changes to the ad account</h3><span class="hint"><%= _staff ? 'every change in flight' : 'from your requests' %></span>
      <a class="more" href="/ppc/keywords?tab=negatives">Keywords &amp; Terms</a></div>
    <div class="card-p" style="padding-bottom:0">

      <div class="muted" style="font-size:var(--fs-sm);line-height:1.6;max-width:820px">
        <% if (_staff) { %>
          Applied by the Google Ads Script on its next run. A row reads <b style="color:var(--ink)">queued</b> until Google confirms it.
        <% } else { %>
          Changes from your requests. They reach Google on the next scheduled run.
        <% } %>
      </div>
    </div>
    <div style="overflow-x:auto">
    <table class="tbl">
      <thead><tr>
        <th>Change</th><th>Where</th><th>Raised by</th><th>Status</th><% if (_staff) { %><th></th><% } %>
      </tr></thead>
      <tbody>
      <% changes.forEach(function(c){ %>
        <tr class="<%= c.status === 'failed' ? 'is-waste' : '' %>">
          <td class="strong" dir="auto">
            <%= VERB[c.action] || c.action %>: <%= c.text %>
            <% if (c.matchType && /negative|keyword/.test(c.action)) { %><span class="chip flat"><%= c.matchType %></span><% } %>
            <% if (c.snapshot && c.snapshot.cost != null) { %>

              <div class="muted" style="font-size:var(--fs-xs);font-weight:500">was costing <%= m(c.snapshot.cost) %> with <%= c.snapshot.conversions || 0 %> conversions when it was flagged</div>
            <% } %>
          </td>
          <td class="muted">
            <%= c.level === 'account' ? (c.negativeList || 'shared list (all campaigns)') : (names[String(c.campaign)] || '—') %><%= c.adGroupName ? ' · ' + c.adGroupName : '' %>
          </td>

          <td class="muted"><%= c.requestedByName || '—' %><br><span style="font-size:var(--fs-xs)"><%= h.date(c.createdAt) %></span></td>
          <td>
            <span class="chip <%= c.status === 'failed' ? 'neg' : 'warn' %>"><%= STATE[c.status] || c.status %></span>

            <% if (c.error) { %>
              <% if (_staff) { %>
                <div class="muted" style="font-size:var(--fs-xs);margin-top:3px;color:var(--neg)"><%= c.error %></div>
              <% } else { %>
                <div class="muted" style="font-size:var(--fs-xs);margin-top:3px">VOCTOS is looking into it.</div>
              <% } %>
            <% } %>
          </td>
          <% if (_staff) { %>
          <td>
            <% if (c.status === 'queued') { %>
              <form class="inline-form js-ajax-form" data-refresh="#ppc-approvals-view" method="POST" action="/ppc/changes/<%= c._id %>/cancel">
                <input type="hidden" name="tab" value="negatives">
                <button class="btn btn-sm" type="submit">Cancel</button>
              </form>
            <% } %>
          </td>
          <% } %>
        </tr>
      <% }) %>
      </tbody>
    </table>
    </div>
    <% if (_staff) { %>
    <div class="card-p" style="border-top:1px solid var(--line)">

      <div class="muted" style="font-size:var(--fs-sm);line-height:1.6">
        A change can be cancelled while it says <b style="color:var(--ink)">queued</b>. After that, undo it in Google Ads.
      </div>
    </div>
    <% } %>
  </div>
  <% } %>

  <% if (requests.length) { %>
  <div class="card b12">
    <div class="card-h"><h3><%= _staff ? 'Requests from the client' : 'Your requests' %></h3><span class="hint">read and decided on by a person</span>
      <% if (_staff) { %><a class="more" href="/tasks">Open Tasks</a><% } %></div>
    <div class="card-p" style="padding-bottom:0">

      <div class="muted" style="font-size:var(--fs-sm)"><%= _staff
        ? 'Requests raised from the portal.'
        : 'A specialist reviews each of these before anything reaches the account.' %></div>
    </div>

    <div style="overflow-x:auto">
    <table class="tbl">
      <thead><tr><th>Request</th><th>Priority</th><th>Raised</th><th>Status</th><% if (_staff) { %><th></th><% } %></tr></thead>
      <tbody>
      <% requests.forEach(function(t){ %>
        <tr>
          <td class="strong" dir="auto">
            <%= t.title %>

            <% if (t.description) { %><div class="muted" style="font-size:var(--fs-xs);font-weight:500"><%= t.description %></div><% } %>
          </td>
          <td><span class="chip <%= t.priority === 'high' ? 'neg' : 'flat' %>"><%= t.priority || 'normal' %></span></td>
          <td class="muted"><%= h.date(t.createdAt) %></td>
          <td><span class="chip <%= t.status === 'doing' ? 'warn' : 'flat' %>"><%= t.status === 'doing' ? 'in progress' : (t.status || 'to do') %></span></td>
          <% if (_staff) { %><td><a class="btn btn-sm" href="/tasks">Open in Tasks</a></td><% } %>
        </tr>
      <% }) %>
      </tbody>
    </table>
    </div>
  </div>
  <% } %>
</div>
</div>
