<%
var cfg = locals.cfg || {}, 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 });
}
function n0(v){ return (v === undefined || v === null) ? '—' : Number(v).toLocaleString('en-US'); }

var nov = '<span class="noval">—</span>';
var pending = locals.pending || [], liveAds = locals.liveAds || [];
var rejected = liveAds.filter(function(a){ return a.status === 'rejected'; });
var running  = liveAds.filter(function(a){ return a.status === 'live'; });
var approved = pending.filter(function(a){ return a.status === 'approved'; });
var inReview = pending.filter(function(a){ return a.status !== 'approved'; });
var known = pending.length + liveAds.length;
var host = '';

var _staff = (locals.canPush === true && !locals.isExport) || (locals.showStaff);

var thin = pending.filter(function(a){ var hs = a.headlines || []; return hs.length && hs.length < 15; }).length;
var drafts = pending.filter(function(a){ return a.origin === 'draft'; }).length;
%>

<div id="ppc-creatives-view">
<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Paid Media / Ad Creatives</div>
  </div>
  <div class="ph-right">
    <%- include('../partials/range-picker') %>
    <% if (pending.length) { %><span class="chip warn"><%= pending.length %> awaiting approval</span><% } %>
    <% if (rejected.length) { %><span class="chip neg"><%= rejected.length %> disapproved</span><% } %>
  </div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (rejected.length) { %>
  <p class="claim-lede"><em><%= rejected.length %></em> ad<%= rejected.length === 1 ? '' : 's' %> <%= rejected.length === 1 ? 'is' : 'are' %> disapproved.</p>
<% } else if (pending.length) { %>
  <p class="claim-lede"><em><%= pending.length %></em> ad<%= pending.length === 1 ? ' is' : 's are' %> built and not running yet.</p>
<% } else if (liveAds.length) { %>
  <p class="claim-lede"><em><%= running.length %></em> of your ads <%= running.length === 1 ? 'is' : 'are' %> live right now.</p>
<% } else { %>
  <p class="claim-lede">No ad rows have arrived from the ad account yet.</p>
<% } %>
<p class="claim-sub">Ads waiting on you, ads running, and what each one is doing.<% if (!liveAds.length && _staff) { %> Add the <span class="code">ads</span> tab to the Google Ads Script and per-ad performance (and any disapproval) appears here.<% } %> <%- h.ihelp('Approving an ad',
  'VOCTOS reviews and publishes ads. An approved ad goes live on the next sync. '
  + '<b>Disapproved</b> means the platform rejected it in policy review.') %></p>

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

  <div class="vdark vd-cut b<%= rejected.length ? 8 : 12 %>">
    <span class="vn-fillet"></span>
    <% if (_staff) { %>
      <a class="vn-cut" href="#staged">Review the 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/approvals">Where it stands
        <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">Built and not running</div>
    <div class="vd-row">
      <div class="vd-num tnum"><% if (known) { %><%= pending.length %><% } else { %><%- nov %><% } %></div>
    </div>
    <div class="vd-sub"><% if (known) { %>Ads built in the account and waiting to go live (drafts or paused ads).<% } else { %>No ads have come through from Google Ads yet.<% } %></div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov"><div class="ovl">In review</div>
        <div class="ovv tnum"><% if (known) { %><%= inReview.length %><% } else { %><%- nov %><% } %></div>
        <div class="rr-meta" style="margin-top:5px">with VOCTOS, no decision recorded</div></div>
      <div class="ov"><div class="ovl">Approved, not switched on</div>
        <div class="ovv tnum"><% if (known) { %><%= approved.length %><% } else { %><%- nov %><% } %></div>
        <div class="rr-meta" style="margin-top:5px">signed off, and switching on is the separate step</div></div>
      <div class="ov"><div class="ovl">Running now</div>
        <div class="ovv tnum"><% if (known) { %><%= running.length %><% } else { %><%- nov %><% } %></div>
        <div class="rr-meta" style="margin-top:5px">serving in the account today</div></div>
      <div class="ov"><div class="ovl">Disapproved</div>
        <div class="ovv tnum"><% if (known) { %><%= rejected.length %><% } else { %><%- nov %><% } %></div>
        <div class="rr-meta" style="margin-top:5px">rejected by the platform's policy review</div></div>
    </div>
  </div>

  <% if (rejected.length) { %>
  <div class="card card-p b4" style="border-color:var(--neg)">
    <div class="card-h" style="padding:0 0 12px"><h3 style="color:var(--neg)">Serving nothing</h3><span class="rr-end"><span class="chip neg"><%= rejected.length %></span></span></div>

    <div class="muted" style="font-size:var(--fs-sm);line-height:1.6">
      <%= rejected.map(function(a){ return '“' + ((a.headlines || [])[0] || a.externalId || 'Ad') + '”'; }).join(', ') %>
      <%= rejected.length > 1 ? 'were' : 'was' %> rejected by the platform's policy review. A disapproved ad spends nothing
      and earns nothing.
    </div>
  </div>
  <% } else { %>
  <% } %>

  <%

    var _shelf = [
      { l: 'Ads in the export', v: known },
      { l: 'Staged ads short of 15 headlines', v: thin },
      { l: 'Campaign drafts staged', v: drafts }
    ];
    var _tints = ['sc-violet', 'sc-lime', 'sc-navy', 'sc-sky', 'sc-sand', 'sc-rose'];
  %>
  <% _shelf.forEach(function (s, i) { %>
    <div class="card shelf-c b4 <%= _tints[i % _tints.length] %>">
      <div class="cl"><%= s.l %></div>
      <div class="cv tnum"><%= s.v %></div>
    </div>
  <% }) %>

  <div class="b12" id="staged">
    <div class="section-title"><%= _staff ? 'Awaiting approval' : 'Not live yet' %></div>

    <div class="muted" style="font-size:var(--fs-sm);margin:2px 0 14px">
      <span class="ihelp-w" tabindex="0" role="button" aria-label="What this copy is"><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> What this copy is
        <span class="ihelp-pop" role="tooltip"><b>What this copy is</b>
          <% if (_staff) { %>
            VOCTOS approves and publishes these. They come straight out of Google Ads (either a
            <b>campaign draft</b> or an ad built and left <b>paused</b> in the account),
            exactly as they will run.
          <% } else { %>
            Ads built in Google Ads and waiting to go live (a <b>campaign draft</b> or a <b>paused</b> ad). VOCTOS reviews and publishes them.
            Anything you want changed, tell your account manager.
          <% } %>
        </span>
      </span>
    </div>

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

      <div class="card card-p"><div class="muted" style="font-size:var(--fs-sm)">No ads waiting. New ads appear here after they are built in Google Ads.</div></div>
    <% } else { %>
      <div class="grid g-2">
      <% pending.forEach(function(a){
           var hs = a.headlines || [], ds = a.descriptions || [];
           try { host = a.finalUrl ? new URL(a.finalUrl).host + new URL(a.finalUrl).pathname : ''; } catch (e) { host = a.finalUrl || ''; }
      %>
        <div class="rsa">
          <div class="rsa-h">
            <span class="chan search"><%= (a.type || 'rsa').toUpperCase() %></span>
            <div style="flex:1">
              <div class="rsa-t"><%= a.baseCampaignName || names[String(a.campaign)] || 'Campaign' %><%= a.adGroupName ? ' · ' + a.adGroupName : '' %></div>
              <div class="rsa-m">
                <% if (a.origin === 'draft') { %>
                  Campaign draft <b style="color:var(--ink)">“<%= a.draftName || 'untitled' %>”</b> in Google Ads
                <% } else if (a.origin === 'paused') { %>
                  Built and paused in Google Ads
                <% } else { %>
                  Drafted in the portal
                <% } %>
                · seen <%= h.timeAgo(a.updatedAt) %><%= (a.clientNote && _staff) ? ' · note on file' : '' %>
              </div>
            </div>
            <% if (a.status === 'approved') { %>
              <span class="chip pos" title="Approved by VOCTOS, waiting for a specialist to switch it on in the account">Approved</span>
            <% } else { %>
              <span class="chip warn">Review</span>
            <% } %>
          </div>
          <div class="rsa-body">
            <% if (a.origin === 'draft' && !hs.length) { %>
              <div class="subnote" style="margin-bottom:14px"><b>This draft changes no ad copy.</b> It is a change to budget, targeting or structure inside <%= a.baseCampaignName || 'the campaign' %>. Open it in Google Ads to see the diff. Applying it lands every change in the draft at once.</div>
            <% } %>
            <div class="serp">
              <div><span class="sp-badge">Sponsored</span><span class="sp-url"><%= host %></span></div>
              <div class="sp-title"><%= hs.slice(0, 2).join(' · ') || 'Headline' %></div>
              <div class="sp-desc"><%= ds[0] || '' %></div>
            </div>
            <% if (hs.length) { %>

              <div style="font-size:var(--fs-xs);font-weight:700;color:var(--muted-2);letter-spacing:.06em;text-transform:uppercase;margin:16px 0 8px">Headlines (<%= hs.length %> of 15)</div>
              <div class="asset-list"><% hs.slice(0, 8).forEach(function(x){ %><span class="asset"><%= x %></span><% }) %><% if (hs.length > 8) { %><span class="asset">+<%= hs.length - 8 %> more</span><% } %></div>
            <% } %>
            <% if (ds.length) { %>

              <div style="font-size:var(--fs-xs);font-weight:700;color:var(--muted-2);letter-spacing:.06em;text-transform:uppercase;margin:16px 0 8px">Descriptions (<%= ds.length %> of 4)</div>
              <div class="asset-list"><% ds.slice(0, 3).forEach(function(x){ %><span class="asset"><%= x %></span><% }) %></div>
            <% } %>
            <% if (hs.length && hs.length < 15) { %>

              <div style="display:flex;gap:10px;padding:11px 13px;border:1px solid rgba(232,161,58,.35);background:var(--warn-tint);border-radius:var(--r);font-size:var(--fs-sm);color:#B5791E;line-height:1.5;margin-top:14px">
                <b style="flex:none">⚠</b>
                <div><b><%= 15 - hs.length %> headlines short of the 15 Google allows.</b> Fewer assets means fewer combinations to test, and ad strength drops with them. Worth filling before this goes live.</div>
              </div>
            <% } %>
            <% if (a.clientNote && _staff) { %><div class="subnote" style="margin-top:12px"><b>Note on file:</b> <%= a.clientNote %></div><% } %>
          </div>
          <div class="rsa-foot">
            <% var pub = (locals.publishing || {})[String(a._id)]; %>
            <% if (!_staff) { %>

              <span class="chip <%= a.status === 'approved' ? 'pos' : 'warn' %>"><%= a.status === 'approved' ? 'Approved' : 'In review' %></span>

              <span class="muted" style="font-size:var(--fs-xs)">
                <% if (a.status === 'approved') { %>Approved by VOCTOS, going live shortly.
                <% } else { %>With VOCTOS for review.<% } %>
              </span>
            <% } else if (a.status !== 'approved') { %>
              <form class="inline-form js-ajax-form" data-refresh="#ppc-creatives-view" method="POST" action="/ppc/creatives/<%= a._id %>/approve">
                <button class="btn btn-sm btn-primary" type="submit">Approve</button>
              </form>

              <span class="muted" style="font-size:var(--fs-xs)">Approved ads go live in the next step.</span>
            <% } else if (pub) { %>
              <span class="chip warn"><%= pub === 'sent' ? 'with the script' : 'queued' %></span>

              <span class="muted" style="font-size:var(--fs-xs)">Approved, and <%= a.origin === 'draft' ? 'the draft is applied' : 'it switches on' %> at the next script run.</span>
            <% } else if (a.source === 'google') { %>

              <form class="inline-form js-ajax-form" data-refresh="#ppc-creatives-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>

              <span class="muted" style="font-size:var(--fs-xs)">Approved <%= a.approvedAt ? h.timeAgo(a.approvedAt) : '' %></span>
            <% } else { %>
              <span class="chip pos">Approved</span>

              <span class="muted" style="font-size:var(--fs-xs)">Next step: build it in Google Ads.</span>
            <% } %>

            <span class="muted" style="margin-left:auto;font-size:var(--fs-xs)">
              <% if (a.source === 'google') { %>Already built in the account<% } else { %>Written in the portal<% } %>
            </span>
          </div>
        </div>
      <% }) %>
      </div>
    <% } %>
  </div>

  <div class="card b12">
    <div class="card-h"><h3>Live ads</h3><span class="hint">performance per ad</span></div>
    <% if (!liveAds.length) { %>

      <div class="card-p"><div class="muted" style="font-size:var(--fs-sm)">No ad rows in the latest export.<% if (_staff) { %> Add the <span class="code">ads</span> tab to the Ads Script to see per-ad performance and catch disapprovals here.<% } %></div></div>
    <% } else { %>
    <div style="overflow-x:auto">
    <table class="tbl">
      <thead><tr><th>Ad</th><th>Campaign</th><th>Strength</th><th style="text-align:right">Impr.</th><th style="text-align:right">CTR</th><th style="text-align:right">Conv</th><th style="text-align:right">CPA</th><th>Status</th></tr></thead>
      <tbody>
      <% liveAds.forEach(function(a){
           var am = a.metrics || {};
           var ctr = (am.clicks != null && am.impressions) ? am.clicks / am.impressions * 100 : null;
           var cpa = (am.cost != null && am.conversions) ? am.cost / am.conversions : null;
           var bad = cfg.targetCpa && cpa != null && cpa > cfg.targetCpa;
      %>
        <tr class="<%= a.status === 'rejected' ? 'is-waste' : '' %>"<%= a.status === 'paused' ? ' style="opacity:.6"' : '' %>>
          <td class="strong"><%= (a.headlines || [])[0] || a.externalId || 'Ad' %></td>
          <td class="muted"><%= names[String(a.campaign)] || '—' %></td>
          <td><% if (a.adStrength) { %><span class="chip <%= /excellent|good/i.test(a.adStrength) ? 'pos' : 'warn' %>"><%= a.adStrength %></span><% } else { %><span class="chip flat">n/a</span><% } %></td>
          <td class="num" style="text-align:right"><%= n0(am.impressions) %></td>
          <td class="num" style="text-align:right"><%= ctr == null ? '—' : ctr.toFixed(2) + '%' %></td>
          <td class="num" style="text-align:right"><%= n0(am.conversions) %></td>
          <td class="num" style="text-align:right<%= bad ? ';color:var(--neg)' : '' %>"><%= m(cpa) %></td>
          <td><span class="chip <%= a.status === 'rejected' ? 'neg' : (a.status === 'live' ? 'pos' : 'flat') %>"><%= a.status === 'rejected' ? (a.policySummary || 'disapproved') : a.status %></span></td>
        </tr>
      <% }) %>
      </tbody>
    </table>
    </div>
    <div class="card-p" style="border-top:1px solid var(--line)">

      <div class="muted" style="font-size:var(--fs-sm);line-height:1.6"><span class="ihelp-w" tabindex="0" role="button" aria-label="How to read this table"><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 to read this table<span class="ihelp-pop" role="tooltip"><b>How to read this table</b>Performance per ad, so “test a new creative” stops being a hunch. A dash means no figure for that ad.</span></span></div>
    </div>
    <% } %>
  </div>
</div>
</div>
