<%
var d = locals.d || {}, 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 waste = d.waste || {};
var wasteTerms = (locals.terms || []).filter(function(t){ return t.flag === 'waste'; });
var wasteCost = wasteTerms.reduce(function(a, t){ return a + (t.cost || 0); }, 0);
var noCost = (locals.terms || []).filter(function(t){ return t.costAvailable === false; }).length;
var campId = locals.campId || '';
function tabUrl(t){ return '/ppc/keywords?tab=' + t + (campId ? '&c=' + campId : ''); }

var sort = locals.sort || { key: 'cost', dir: -1 };
function sortUrl(k){

  var dir = (sort.key === k && sort.dir === -1) ? 'asc' : 'desc';

  return (tabUrl(tab) + '&sort=' + k + '&dir=' + dir).replace(/&/g, '&amp;');
}
function sortTh(k, label, align){
  var on = sort.key === k;
  var arrow = on ? (sort.dir === -1 ? '▾' : '▴') : '';
  return '<th class="sortable' + (on ? ' on' : '') + '" style="text-align:' + (align || 'left') + '">'
    + '<a href="' + sortUrl(k) + '">' + label + '<span class="sarrow">' + arrow + '</span></a></th>';
}
function pct(v){ return (v === undefined || v === null) ? '—' : (Number(v) * 100).toFixed(2) + '%'; }
function ctrOf(r){ return (r.impressions > 0) ? r.clicks / r.impressions : null; }
function cpaOf(r){ return (r.conversions > 0 && r.cost != null && r.costAvailable !== false) ? r.cost / r.conversions : null; }

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

var nov = '<span class="noval">—</span>';
var _terms = locals.terms || [], _kws = locals.keywords || [], _negs = locals.negatives || [];
var converting = _terms.filter(function(t){ return t.conversions > 0; }).length;
%>

<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Paid Media / Keywords &amp; Search Terms</div>
  </div>
  <div class="ph-right">
    <%

      var camps = locals.campaigns || [], rc = locals.rowCount || {};
    %>
    <form method="GET" class="picker-wrap">
      <input type="hidden" name="tab" value="<%= tab %>">
      <label for="campSel">Campaign</label>
      <select class="picker picker-sm" id="campSel" name="c" onchange="this.form.submit()">
        <option value="">All campaigns</option>
        <% camps.forEach(function(c){ var n = rc[String(c._id)] || {}; %>
          <option value="<%= c._id %>" <%= campId === String(c._id) ? 'selected' : '' %>>
            <%= c.name %><%= n.n ? ' (' + n.n + ')' : '' %><%= n.waste ? ' · ' + n.waste + ' flagged' : '' %>
          </option>
        <% }) %>
      </select>
      <noscript><button class="btn btn-sm" type="submit">Go</button></noscript>
    </form>
    <%- include('../partials/range-picker') %>
    <% if (wasteTerms.length) { %><span class="chip neg"><%= m(wasteCost) %><%= campId ? '' : '/mo' %> recoverable</span><% } %>
  </div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (wasteTerms.length) { %>
  <p class="claim-lede"><em><%= m(wasteCost) %></em> went on search terms with no conversions.</p>
<% } else if (_terms.length) { %>
  <p class="claim-lede">None of <em><%= _terms.length %></em> search terms crossed the waste line.</p>
<% } else if (_kws.length) { %>
  <p class="claim-lede"><em><%= _kws.length %></em> keywords are bidding, and no search terms have arrived.</p>
<% } else { %>
  <p class="claim-lede">No keyword or search-term rows are in the latest export.</p>
<% } %>
<p class="claim-sub">What you bid on, what people typed, and what was wasted. <%- h.ihelp('Keywords vs search terms',
  'A <b>keyword</b> is what you bid on; a <b>search term</b> is what someone typed. '
  + 'Terms are judged after the ' + cfg.lagDays + '-day conversion lag. '
  + (waste.threshold ? '<b>Flagged as waste</b>: spent ' + m(waste.threshold) + ' or more (' + waste.multiple + '× target CPA) with no conversions, a candidate for a negative keyword.' : 'Waste is flagged once a target CPA is set.')) %></p>

<% if (locals.selected) { %>

  <div class="rr-meta" style="margin:14px 0 0;display:flex;align-items:center;gap:10px;flex-wrap:wrap">
    Showing <b style="color:var(--ink)"><%= selected.name %></b> only. Counts and totals below are for this campaign.
    <a class="more" href="/ppc/keywords?tab=<%= tab %>">Show all campaigns</a>
    <a class="more" href="/ppc/campaigns/<%= selected._id %>">Open the campaign</a>
  </div>
<% } %>

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

  <div class="vdark vd-cut b12">
    <span class="vn-fillet"></span>
    <% if (_staff) { %>
      <a class="vn-cut" href="#change">Change the account
        <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>
    <% } else { %>
      <a class="vn-cut" href="/ppc/approvals">Your requests
        <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">Flagged as waste</div>
    <div class="vd-row">
      <div class="vd-num tnum"><% if (_terms.length) { %><%= m(wasteCost) %><% } else { %><%- nov %><% } %></div>
    </div>
    <div class="vd-sub"><% if (_terms.length) { %>Spend on <b><%= wasteTerms.length %></b> search term<%= wasteTerms.length === 1 ? '' : 's' %> with no conversion after the lag window closed.<% } else { %>No search terms have arrived yet.<% } %></div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov"><div class="ovl">Search terms</div>
        <div class="ovv tnum"><%= _terms.length %></div>
        <div class="rr-meta" style="margin-top:5px">what people actually typed</div></div>
      <div class="ov"><div class="ovl">Converting terms</div>
        <div class="ovv tnum"><%= converting %></div>
        <div class="rr-meta" style="margin-top:5px">at least one conversion in this window</div></div>
      <div class="ov"><div class="ovl">Flagged as waste</div>
        <div class="ovv tnum"><%= wasteTerms.length %></div>
        <div class="rr-meta" style="margin-top:5px">candidates for a negative keyword</div></div>
      <div class="ov"><div class="ovl">Waste threshold</div>
        <div class="ovv tnum"><% if (waste.threshold) { %><%= m(waste.threshold) %><% } else { %><%- nov %><% } %></div>
        <div class="rr-meta" style="margin-top:5px"><% if (waste.threshold) { %><%= waste.multiple %>× the agreed target CPA<% } else { %>no target CPA on file to multiply<% } %></div></div>
    </div>
  </div>

  <%

    var _shelf = [
      { l: 'Active keywords', v: _kws.length },
      { l: 'Negatives on file', v: _negs.length },
      { l: 'Rows with no cost reported', v: noCost }
    ];
    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="card b12" id="ppc-kw-table">
  <div class="tabs" style="padding:0 6px">
    <a class="tab <%= tab === 'terms' ? 'on' : '' %>" href="<%= tabUrl('terms') %>">Search terms <span class="pilln"><%= (locals.terms || []).length %></span></a>
    <a class="tab <%= tab === 'keywords' ? 'on' : '' %>" href="<%= tabUrl('keywords') %>">Keywords <span class="pilln"><%= (locals.keywords || []).length %></span></a>
    <a class="tab <%= tab === 'negatives' ? 'on' : '' %>" href="<%= tabUrl('negatives') %>">Negatives <span class="pilln"><%= (locals.negatives || []).length %></span></a>
  </div>

  <% if (tab === 'terms') { %>
    <% if (!(locals.terms || []).length) { %>
      <div class="card-p"><div class="muted" style="font-size:var(--fs-sm)"><% if (campId) { %>No search-term rows for <b style="color:var(--ink)"><%= selected ? selected.name : 'this campaign' %></b>. <a class="more" href="/ppc/keywords?tab=terms">Show all campaigns</a><% } else { %>No search-term rows in the latest export.<% if (_staff) { %> Add the <span class="code">search_terms</span> tab to the Ads Script. It is the single most useful report on this page.<% } %><% } %></div></div>
    <% } else { %>

      <div style="overflow-x:auto">
      <table class="tbl">
        <thead><tr>
          <%- sortTh('text', 'Search term') %>
          <% if (!campId) { %><th>Campaign</th><% } %>
          <%- sortTh('clicks', 'Clicks', 'right') %>
          <%- sortTh('ctr', 'CTR', 'right') %>
          <%- sortTh('cost', 'Cost', 'right') %>
          <%- sortTh('conversions', 'Conv', 'right') %>
          <%- sortTh('cpa', 'CPA', 'right') %>
          <th>Flag</th><th></th>
        </tr></thead>
        <tbody>
        <% terms.forEach(function(t){ %>
          <tr class="<%= t.flag === 'waste' ? 'is-waste' : (t.flag === 'winner' ? 'is-winner' : '') %>">
            <td dir="auto" class="strong"><%= t.text %></td>
            <% if (!campId) { %><td class="muted"><%= names[String(t.campaign)] || '—' %></td><% } %>
            <td class="num" style="text-align:right"><%= n0(t.clicks) %></td>
            <td class="num" style="text-align:right"><%= pct(ctrOf(t)) %></td>
            <td class="num" style="text-align:right<%= t.flag === 'waste' ? ';color:var(--neg)' : '' %>"><%= t.costAvailable === false ? 'n/a' : m(t.cost) %></td>
            <td class="num" style="text-align:right"><%= n0(t.conversions) %></td>
            <% var tc = cpaOf(t); %>
            <td class="num" style="text-align:right<%= (tc != null && cfg.targetCpa && tc > cfg.targetCpa) ? ';color:var(--neg)' : ((tc != null && cfg.targetCpa && tc <= cfg.targetCpa * 0.8) ? ';color:var(--pos)' : '') %>"><%= tc == null ? '—' : m(tc) %></td>
            <td>
              <% if (t.costAvailable === false) { %><span class="chip flat" title="Performance Max reports search categories without cost">no cost data</span>
              <% } else if (t.flag) { %><span class="flag <%= t.flag %>"><%= t.flagReason || t.flag %></span><% if (t.flagConfidence === 'low') { %> <span class="chip warn">low conf.</span><% } %><% } %>
            </td>
            <td>
              <% var inflight = (locals.queued || {})[String(t.text).toLowerCase()]; %>
              <% if (inflight) { %>
                <span class="chip warn" title="<%= _staff ? 'Waiting for the Ads Script to run. The account has not changed yet' : 'Sent, waiting for Google Ads to apply it. The account has not changed yet' %>"><%= inflight === 'sent' ? 'with the script' : 'queued' %></span>
              <% } else if (t.flag === 'waste' && _staff) { %>
                <form class="inline-form js-ajax-form" data-refresh="#ppc-kw-table #change" method="POST" action="/ppc/changes">
                  <input type="hidden" name="action" value="add_negative">
                  <input type="hidden" name="text" value="<%= t.text %>">
                  <input type="hidden" name="campaign" value="<%= t.campaign || '' %>">
                  <input type="hidden" name="sourceTerm" value="<%= t._id %>">
                  <input type="hidden" name="matchType" value="phrase">
                  <input type="hidden" name="level" value="campaign">
                  <input type="hidden" name="tab" value="terms">
                  <input type="hidden" name="c" value="<%= campId %>">
                  <button class="btn btn-sm btn-primary" type="submit" title="Queues a phrase negative on this campaign. It reaches Google on the next script run.">Add negative</button>
                </form>
              <% } else if (t.flag === 'waste') { %>

                <form class="inline-form js-ajax-form" data-success-text="Requested ✓" method="POST" action="/ppc/keywords/<%= t._id %>/request-negative">
                  <button class="btn btn-sm" type="submit">Request negative</button>
                </form>
              <% } %>
            </td>
          </tr>
        <% }) %>
        </tbody>
      </table>
      </div>
      <% if (noCost) { %>
      <div class="card-p" style="border-top:1px solid var(--line)">

        <div class="muted" style="font-size:var(--fs-sm);line-height:1.6"><b style="color:var(--ink)"><%= noCost %> row<%= noCost > 1 ? 's carry' : ' carries' %> no cost.</b><%- h.ihelp('Rows that carry no cost',
          'Performance Max search categories: Google reports volume for them but no spend. They can be excluded with an account-level negative list.') %></div>
      </div>
      <% } %>
    <% } %>

  <% } else if (tab === 'keywords') { %>
    <% if (!(locals.keywords || []).length) { %>
      <div class="card-p"><div class="muted" style="font-size:var(--fs-sm)"><% if (campId) { %>No keyword rows for <b style="color:var(--ink)"><%= selected ? selected.name : 'this campaign' %></b>. <a class="more" href="/ppc/keywords?tab=keywords">Show all campaigns</a><% } else { %>No keyword rows in the latest export.<% } %></div></div>
    <% } else { %>
      <div style="overflow-x:auto">
      <table class="tbl">
        <thead><tr>
          <%- sortTh('text', 'Keyword') %>
          <th>Match</th>
          <% if (!campId) { %><th>Campaign</th><% } %>
          <%- sortTh('clicks', 'Clicks', 'right') %>
          <%- sortTh('ctr', 'CTR', 'right') %>
          <%- sortTh('cost', 'Cost', 'right') %>
          <%- sortTh('conversions', 'Conv', 'right') %>
          <%- sortTh('cpa', 'CPA', 'right') %>
          <%- sortTh('qualityScore', 'QS', 'center') %>
          <th>Weak component<%- h.ihelp('Why the weak-component column is here',
            'The part of Quality Score Google rates below average: ad relevance, expected CTR or landing page. '
            + 'A dash means none is below average.') %></th>
        </tr></thead>
        <tbody>
        <% keywords.forEach(function(k){
             var kc = (k.cost != null && k.conversions) ? k.cost/k.conversions : null;
             var q = k.qualityScore; var qcls = q == null ? '' : (q >= 7 ? 'good' : (q >= 5 ? 'ok' : 'bad'));
             var weak = [['Expected CTR', k.qsExpectedCtr], ['Ad relevance', k.qsAdRelevance], ['Landing page', k.qsLandingPage]]
               .filter(function(p){ return /below/i.test(p[1] || ''); }).map(function(p){ return p[0]; });
        %>
          <tr class="<%= k.flag === 'waste' ? 'is-waste' : (k.flag === 'winner' ? 'is-winner' : '') %>">
            <td dir="auto" class="strong"><%= k.text %></td>
            <td><span class="chip flat"><%= k.matchType %></span></td>
            <% if (!campId) { %><td class="muted"><%= names[String(k.campaign)] || '—' %></td><% } %>
            <td class="num" style="text-align:right"><%= n0(k.clicks) %></td>
            <td class="num" style="text-align:right"><%= pct(ctrOf(k)) %></td>
            <td class="num" style="text-align:right"><%= m(k.cost) %></td>
            <td class="num" style="text-align:right"><%= n0(k.conversions) %></td>
            <td class="num" style="text-align:right<%= (kc != null && cfg.targetCpa && kc > cfg.targetCpa) ? ';color:var(--neg)' : ((kc != null && cfg.targetCpa && kc <= cfg.targetCpa * 0.8) ? ';color:var(--pos)' : '') %>"><%= kc == null ? '—' : m(kc) %></td>
            <td style="text-align:center"><% if (q != null) { %><span class="qs <%= qcls %>"><%= q %></span><% } else { %>—<% } %></td>
            <td style="<%= weak.length ? 'color:var(--neg)' : 'color:var(--muted-2)' %>"><%= weak.length ? weak.join(', ') : '—' %></td>
          </tr>
        <% }) %>
        </tbody>
      </table>
      </div>
    <% } %>

  <% } else { %>
    <% if (!(locals.negatives || []).length) { %>

      <%- include('../partials/empty', { title: 'No negative keywords yet', line: _staff ? 'Add the <span class="code">negatives</span> tab to the Ads Script to list them here.' : 'Excluded search terms appear here once they are added.', pad: 'sm' }) %>
    <% } else { %>
      <div class="card-p" style="padding-bottom:0">
        <div class="muted" style="font-size:var(--fs-sm);line-height:1.65">
          <span class="ihelp-w" tabindex="0" role="button" aria-label="What these figures are"><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 these figures are
            <span class="ihelp-pop" role="tooltip"><b>What these figures are</b>
              Google reports no metrics on a negative. A negative blocks spend, so it has no metrics of its own.
              The figures below are what the blocked queries were measured at:
              <b>recorded</b> means VOCTOS excluded that term from this portal and we kept its numbers from the
              window we did it in; <b>matched</b> means we added up the queries in the current export this
              negative would block. A dash is normal for an older negative, since the queries it blocks no longer appear.
            </span>
          </span>
        </div>
      </div>
      <div style="overflow-x:auto">
      <table class="tbl">
        <thead><tr>
          <%- sortTh('text', 'Negative') %><th>List</th><th>Match</th>
          <% if (!campId) { %><th>Campaign</th><% } %>
          <th style="text-align:right">Clicks</th>
          <th style="text-align:right">CTR</th>
          <th style="text-align:right">Cost</th>
          <th style="text-align:right">Conv</th>
          <th style="text-align:right">CPA</th>
          <th>Evidence</th>
          <%- sortTh('createdAt', 'Added') %>
          <th>Added by</th>
          <% if (_staff) { %><th></th><% } %>
        </tr></thead>
        <tbody>
        <% negatives.forEach(function(t){
             var st = (locals.negMetrics || {})[String(t._id)] || { source: 'none' };
             var has = st.source === 'recorded' || st.source === 'matched';
        %>
          <tr>
            <td dir="auto" class="strong"><%= t.text %></td>
            <td class="muted"><%= t.negativeList || 'campaign level' %></td>
            <td><span class="chip flat"><%= t.matchType %></span></td>
            <% if (!campId) { %><td class="muted"><%= names[String(t.campaign)] || 'shared' %></td><% } %>
            <td class="num" style="text-align:right"><%= has ? n0(st.clicks) : '—' %></td>
            <td class="num" style="text-align:right"><%= has ? pct(ctrOf(st)) : '—' %></td>
            <td class="num" style="text-align:right<%= (has && st.cost) ? ';color:var(--neg)' : '' %>"><%= has && st.cost != null ? m(st.cost) + (st.costPartial ? '+' : '') : '—' %></td>
            <td class="num" style="text-align:right"><%= has ? n0(st.conversions) : '—' %></td>
            <% var nc = has ? cpaOf(st) : null; %>
            <td class="num" style="text-align:right"><%= nc == null ? '—' : m(nc) %></td>
            <td>
              <% if (st.source === 'recorded') { %>
                <span class="chip pos" title="<%= st.note %>">recorded</span>
              <% } else if (st.source === 'matched') { %>
                <%

                  var shown = st.terms || [], extra = (st.matched || 0) - shown.length;
                  var tip = shown.length
                    ? shown.join(' · ') + (extra > 0 ? ' · +' + extra + ' more' : '')
                    : st.note;
                %>
                <span class="chip warn" title="<%= tip %>">matched <%= st.matched %></span>
                <% if (st.costPartial) { %><span class="chip flat" title="Some of the matched queries are Performance Max categories, which report volume but no cost, so the spend shown is the part Google prices">partial cost</span><% } %>
              <% } else { %>
                <span class="chip flat" title="<%= st.note %>">no history</span>
              <% } %>
            </td>
            <td class="muted"><%= h.date(t.createdAt) %></td>
            <td class="muted">
              <% if (st.addedBy) { %><%= st.addedBy %>

              <% } else { %><span title="<%= _staff ? 'Google\'s export carries no author on a negative, and an Ads Script cannot read change history, so for anything added directly in Google Ads there is no name to show.' : 'No name was recorded for this one.' %>">—</span><% } %>
            </td>
            <% if (_staff) { %>
            <td>
              <% var pending = (locals.removing || {})[String(t._id)]; %>
              <% if (pending) { %>
                <span class="chip warn" title="<%= _staff ? 'Waiting for the Ads Script to run. The negative is still live until then' : 'Sent, waiting for Google Ads to remove it. It is still active until then' %>"><%= pending === 'sent' ? 'removing' : 'queued to remove' %></span>
              <% } else { %>

                <form class="inline-form js-ajax-form" data-refresh="#ppc-kw-table #change" method="POST" action="/ppc/negatives/<%= t._id %>/remove"
                      data-confirm="Remove &quot;<%= t.text %>&quot; from the negatives?&#10;&#10;Those queries can start spending again as soon as the script runs.">
                  <input type="hidden" name="tab" value="negatives"><input type="hidden" name="c" value="<%= campId %>">
                  <button class="btn btn-sm" type="submit" title="Queues the removal. The negative stays live until the script runs, and this row keeps its figures either way.">Remove from negatives</button>
                </form>
              <% } %>
            </td>
            <% } %>
          </tr>
        <% }) %>
        </tbody>
      </table>
      </div>
    <% } %>
  <% } %>
</div>

<% if (_staff) { %>
<%
  var changes = locals.changes || [];
  var open = changes.filter(function(c){ return c.status === 'queued' || c.status === 'sent'; });
  var recent = changes.filter(function(c){ return c.status === 'applied' || c.status === 'failed'; }).slice(0, 8);
  var STATE = { queued:'queued', sent:'with the script', applied:'applied in Google', failed:'failed', cancelled:'cancelled' };
%>

<div class="card staff-only b12" id="change">
  <div class="card-h">
    <h3>Change the account <span class="chip flat">VOCTOS only</span></h3>
    <span class="hint">not visible to the client</span>

    <a class="more" href="/ppc/approvals">Approvals</a>
  </div>

  <div class="card-p" style="padding-bottom:4px">
    <div class="muted" style="font-size:var(--fs-sm);line-height:1.65">
      Changes sent from here are applied in Google Ads on the next script run. A row shows <b style="color:var(--ink)">queued</b> until Google confirms it.
    </div>
  </div>

  <div class="chg-forms">
    <form method="POST" action="/ppc/changes" class="chg-form js-ajax-form" data-refresh="#ppc-kw-table #change">
      <input type="hidden" name="action" value="add_negative">
      <input type="hidden" name="tab" value="<%= tab %>">
      <input type="hidden" name="c" value="<%= campId %>">
      <div class="chg-t">Add a negative</div>
      <div class="chg-grid">
        <label>Term<input class="inp" type="text" name="text" dir="auto" required placeholder="e.g. مجاني"></label>
        <label>Match
          <select class="inp" name="matchType">
            <option value="phrase" selected>phrase (blocks the theme)</option>
            <option value="exact">exact (blocks one query)</option>
            <option value="broad">broad (widest, use carefully)</option>
          </select>
        </label>
        <label>Level
          <select class="inp" name="level">
            <option value="campaign" selected>this campaign</option>
            <option value="account">shared list (every campaign)</option>
            <option value="adgroup">one ad group</option>
          </select>
        </label>
        <label>Campaign
          <select class="inp" name="campaign">
            <option value="">—</option>
            <% (locals.campaigns || []).forEach(function(c){ %><option value="<%= c._id %>" <%= campId === String(c._id) ? 'selected' : '' %>><%= c.name %></option><% }) %>
          </select>
        </label>
        <label>Ad group <span class="opt">only for ad-group level</span><input class="inp" type="text" name="adGroupName" placeholder="optional"></label>
      </div>
      <button class="btn btn-sm btn-primary" type="submit">Queue negative</button>
    </form>

    <form method="POST" action="/ppc/changes" class="chg-form js-ajax-form" data-refresh="#ppc-kw-table #change">
      <input type="hidden" name="action" value="add_keyword">
      <input type="hidden" name="tab" value="<%= tab %>">
      <input type="hidden" name="c" value="<%= campId %>">
      <div class="chg-t">Add a keyword</div>
      <div class="chg-grid">
        <label>Keyword<input class="inp" type="text" name="text" dir="auto" required placeholder="e.g. تحليل دم شامل"></label>
        <label>Match
          <select class="inp" name="matchType">
            <option value="phrase" selected>phrase</option>
            <option value="exact">exact</option>
            <option value="broad">broad</option>
          </select>
        </label>
        <label>Campaign
          <select class="inp" name="campaign" required>
            <option value="">—</option>
            <% (locals.campaigns || []).forEach(function(c){ if (c.channel === 'search' || c.channel === 'shopping') { %><option value="<%= c._id %>" <%= campId === String(c._id) ? 'selected' : '' %>><%= c.name %></option><% } }) %>
          </select>
        </label>
        <label>Ad group<input class="inp" type="text" name="adGroupName" required placeholder="required"></label>
        <label>Max CPC <span class="opt">blank = inherit the ad group</span><input class="inp" type="number" step="0.01" min="0" name="cpcBid" placeholder="—"></label>
      </div>
      <button class="btn btn-sm btn-primary" type="submit">Queue keyword</button>

      <div class="muted" style="font-size:var(--fs-xs);margin-top:6px">Search and Shopping campaigns only.</div>
    </form>
  </div>

  <% if (open.length || recent.length) { %>
  <div style="border-top:1px solid var(--line)">

    <div style="overflow-x:auto">
    <table class="tbl">
      <thead><tr><th>Change</th><th>Where</th><th>Requested by</th><th>Status</th><th></th></tr></thead>
      <tbody>
      <% open.concat(recent).forEach(function(c){ %>
        <tr>
          <% var VERB = { add_keyword: 'add keyword', add_negative: 'add negative', remove_negative: 'remove negative', pause_keyword: 'pause keyword' }; %>
          <td dir="auto" class="strong"><%= VERB[c.action] || c.action %>: <%= c.text %> <span class="chip flat"><%= c.matchType %></span></td>
          <td class="muted"><%= c.level === 'account' ? (c.negativeList || 'shared list') : (names[String(c.campaign)] || '—') %><%= c.adGroupName ? ' · ' + c.adGroupName : '' %></td>
          <td class="muted"><%= c.requestedByName || '—' %> · <%= h.date(c.createdAt) %></td>
          <td>
            <span class="chip <%= c.status === 'applied' ? 'pos' : (c.status === 'failed' ? 'neg' : 'warn') %>"><%= STATE[c.status] || c.status %></span>

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