<%
var d = locals.d || {}, cfg = locals.cfg || {};
var t = d.totals || {}, dl = d.deltas || {}, av = d.availability || {};
var waste = d.waste || null, opp = d.opportunity || null, search = d.search || null;
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 });
}
function n0(v){ return (v === undefined || v === null) ? '—' : Number(v).toLocaleString('en-US'); }
function p1(v){ return (v === undefined || v === null) ? '—' : Number(v).toFixed(2) + '%'; }

function chip(v, lowerBetter, unit){
  if (v === undefined || v === null || Math.abs(v) < 0.05) return '';
  var good = lowerBetter ? v < 0 : v > 0;
  return '<span class="chip ' + (good ? 'pos' : 'neg') + '">' + (v > 0 ? '+' : '') + Number(v).toFixed(1) + (unit || '%') + '</span>';
}

var nov = '<span class="noval">—</span>';
var hasData = (locals.campaigns || []).length > 0;
var accounts = locals.accounts || [];

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

var METRICS = {
  convrate: { label:'Conversion rate', val: p1(t.convRate), foot: (t.conversions!=null&&t.clicks!=null) ? n0(t.conversions)+' conversions from '+n0(t.clicks)+' clicks' : 'Awaiting data', chip: chip(dl.convRate, false, 'pt') },
  cpc:      { label:'Avg. CPC', val: m(t.cpc), foot: t.clicks!=null ? 'Across '+n0(t.clicks)+' clicks' : 'Awaiting data', chip: '' },
  cpm:      { label:'Cost per 1,000 impr.', val: (t.cost!=null&&t.impressions) ? m(t.cost/t.impressions*1000) : '—', foot: t.impressions!=null ? n0(t.impressions)+' impressions' : 'Awaiting data', chip: '' },
  roas:     { label:'ROAS', locked: !av.convValue, val: t.roas!=null ? Number(t.roas).toFixed(2)+'x' : '—',
              why:'Needs conversion <b>value</b> on the conversion action. This account records conversions but not their value.',
              fix:'Set conversion values in Google Ads', foot:'', chip:'' },
  revenue:  { label:'Tracked revenue', locked: !av.convValue, val: m(t.convValue),
              why:'Same dependency as ROAS. No value is passed with the conversion event.',
              fix:'Set conversion values in Google Ads', foot:'', chip:'' }
};

var campN = d.campaignCount != null ? d.campaignCount : (locals.campaigns || []).length;
var sel = METRICS[locals.m2] ? locals.m2 : 'convrate';
var chosen = METRICS[sel];

var _svgGrid = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><rect x="2.2" y="2.2" width="5" height="5" rx="1.2" stroke="currentColor" stroke-width="1.4"/><rect x="8.8" y="2.2" width="5" height="5" rx="1.2" stroke="currentColor" stroke-width="1.4"/><rect x="2.2" y="8.8" width="5" height="5" rx="1.2" stroke="currentColor" stroke-width="1.4"/><rect x="8.8" y="8.8" width="5" height="5" rx="1.2" stroke="currentColor" stroke-width="1.4"/></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 _svgCoin = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><ellipse cx="8" cy="4.4" rx="5.4" ry="2.2" stroke="currentColor" stroke-width="1.4"/><path d="M2.6 4.4v7.2c0 1.2 2.4 2.2 5.4 2.2s5.4-1 5.4-2.2V4.4" stroke="currentColor" stroke-width="1.4"/><path d="M2.6 8c0 1.2 2.4 2.2 5.4 2.2s5.4-1 5.4-2.2" stroke="currentColor" stroke-width="1.4"/></svg>';
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 _svgChk  = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none"><path d="M3.4 8.4l3 3 6.2-6.8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';

var _acts = [];
_acts.push({ href:'/ppc/campaigns', lb:'Campaigns',       ic:_svgGrid, lead:true, n: campN });
_acts.push({ href:'/ppc/keywords',  lb:'Keywords & terms', ic:_svgKey,  n: waste && waste.terms });
_acts.push({ href:'/ppc/budget',    lb:'Budget & pacing',  ic:_svgCoin });
_acts.push({ href:'/ppc/creatives', lb:'Ad creatives',     ic:_svgPen });
_acts.push({ href:'/ppc/approvals', lb:'Approvals',        ic:_svgChk });
%>

<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">Paid Media / PPC Overview</div>
  </div>
  <div class="ph-right">
    <%- include('../partials/range-picker') %>
    <% (d.syncStatus || []).forEach(function(s){ %>
      <span class="chip <%= s.state === 'ok' ? 'pos' : (s.state === 'failed' ? 'neg' : 'flat') %>" title="<%= s.msg || '' %>"><%= s.source %> <%= s.state === 'ok' ? '✓' : '✗' %></span>
    <% }) %>

  </div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (!accounts.length) { %>
  <p class="claim-lede">No ad account is connected to this workspace yet.</p>
<% } else if (!hasData) { %>
  <p class="claim-lede"><em><%= accounts.length %></em> ad account<%= accounts.length > 1 ? 's are' : ' is' %> linked. Figures appear after the first sync.</p>
<% } else if (d.rangeEmpty) { %>
  <p class="claim-lede">Nothing was spent in <%= range.label.toLowerCase() %>.</p>
<% } else if (t.cpa != null) { %>
  <p class="claim-lede">Every conversion cost you <em><%= m(t.cpa) %></em> in this period.</p>
<% } else if (t.cost != null) { %>
  <p class="claim-lede">Your ads spent <em><%= m(t.cost) %></em> in this period.</p>
<% } else { %>
  <p class="claim-lede">No ad data for this period.</p>
<% } %>
<p class="claim-sub"><%
  if (hasData && !d.rangeEmpty) { %>Every paid channel in one place<% if (d.window && d.window.start) { %>, <%= h.date(d.window.start) %> to <%= h.date(d.window.end) %><% } %>. Spend and conversions are from the ad platforms as of the last sync.<%
  } else if (accounts.length) { %>Every paid channel in one place. Figures appear after the first sync with the ad platforms.<%
  } else { %>Every paid channel in one place. Figures appear once an ad account is connected.<% }
%> <%- h.ihelp('What is counted here',
      '<b>Conversions</b> counts primary conversions only. Impression share uses the sync\'s own window.') %></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>

<% if (!accounts.length) { %>
  <div style="margin-top:22px">
  <%- include('../partials/ppc-empty', { title: 'No ad account connected yet', body: 'Figures appear here once an ad account is connected.', cfg: cfg, canWrite: canWrite }) %>
  </div>

<% } else if (!hasData) { %>
  <div class="card" style="margin-top:22px">
    <%- include('../partials/empty', { title: 'Waiting for the first sync', line: accounts.length + ' ad account' + (accounts.length > 1 ? 's are' : ' is') + ' linked. Figures appear after the next daily sync.' }) %>

    <% (d.syncStatus || []).filter(function(s){ return s.state === 'failed'; }).forEach(function(s){ %>

      <div style="display:flex;gap:10px;padding:11px 13px;border:1px solid rgba(229,72,77,.3);background:var(--neg-tint);border-radius:var(--r);font-size:var(--fs-sm);color:var(--neg);line-height:1.55;margin-top:12px">
        <b style="flex:none"><%= s.source %></b><div><%= s.msg %></div>
      </div>
    <% }) %>
  </div>

<% } else { %>

<%

  var rc = d.rangeCovered || null;
%>
<div class="card card-p" style="margin:22px 0 0">
  <% if (d.rangeEmpty) { %>

    <div style="display:flex;gap:10px;font-size:var(--fs-sm);color:#B5791E;line-height:1.55">
      <b style="flex:none">⚠</b>
      <div><b>No spend in <%= range.label.toLowerCase() %>.</b><% if (rc && rc.first) { %> Data covers <%= h.date(rc.first) %> to <%= h.date(rc.last) %>.<% } %></div>
    </div>
  <% } else if (rc && (rc.startsBeforeData || rc.endsAfterData)) { %>
    <div class="modelled" style="margin:0;border-top:0;padding-top:0">
      <b style="color:var(--muted)">Partial window.</b> You asked for <%= range.label.toLowerCase() %>, and daily rows only exist from
      <%= h.date(rc.first) %> to <%= h.date(rc.last) %>, (<%= rc.days %> day<%= rc.days === 1 ? '' : 's' %>). Totals cover those days.
    </div>
  <% } %>
  <div class="modelled" style="margin:0;border-top:0;padding-top:0">
    <% if (d.rangeApplied) { %>
      <b style="color:var(--muted)">What the date range moved.</b>
      Figures cover <b style="color:var(--muted)"><%= range.span %></b>. Items marked <span class="periodonly">period</span> are reported by Google for the whole period only.
    <% } else { %>
      <b style="color:var(--muted)">The date range can't be applied yet.</b>
      These figures are the window the last sync wrote.

      <% if (_staff) { %>Add the <span class="code">campaign_daily</span> tab to the
      Google Ads Script and every number below starts answering to the picker.<% } %>
    <% } %>
  </div>
</div>

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

  <div class="vdark vd-cut b8">
    <span class="vn-fillet"></span>
    <% if (_staff) { %>
      <form class="inline-form js-async-run" method="POST" action="/ppc/sync" style="position:absolute;top:0;right:0">
        <button class="vn-cut" type="submit">Sync now
          <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>
    <% } else { %>
      <a class="vn-cut" href="/ppc/campaigns">Campaigns
        <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">Ad spend</div>
    <div class="vd-row">
      <div class="vd-num tnum"><% if (t.cost != null) { %><%= m(t.cost) %><% } else { %><%- nov %><% } %></div>
      <%- chip(dl.cost, false) %>
    </div>
    <div class="vd-sub"><b><%= campN %></b> campaign<%= campN === 1 ? '' : 's' %> across <b><%= (d.channels || []).length %></b> channel<%= (d.channels || []).length === 1 ? '' : 's' %>.</div>

    <div class="ov-strip ov-2" style="margin-top:20px">
      <div class="ov">
        <div class="ovl">Conversions</div>
        <div class="ovv tnum"><% if (t.conversions != null) { %><%= n0(t.conversions) %><% } else { %><%- nov %><% } %> <%- chip(dl.conversions, false) %></div>
        <% var cb = d.conversionBasis || null; %>
        <div class="rr-meta" style="margin-top:5px">
          <% if (cb && cb.mode === 'single_action') { %><%= cb.action %> only
          <% } else if (cb && cb.multiplePrimary) { %><%= cb.countedCount %> actions counted as primary
          <% } else if (cb) { %>Primary action only · <%= cb.actions.length %> tracked
          <% } else { %>Primary conversion actions only<% } %>
        </div>
      </div>

      <div class="ov">
        <div class="ovl">Cost per conversion</div>
        <div class="ovv tnum"><% if (t.cpa != null) { %><%= m(t.cpa) %><% } else { %><%- nov %><% } %> <%- chip(dl.cpa, true) %></div>
        <div class="rr-meta" style="margin-top:5px"><% if (cfg.targetCpa) { %>Target <%= m(cfg.targetCpa) %><% if (t.cpa != null) { %> · <%= t.cpa <= cfg.targetCpa ? Math.round((1 - t.cpa/cfg.targetCpa)*100) + '% below' : Math.round((t.cpa/cfg.targetCpa - 1)*100) + '% above' %><% } %><% } else { %>No target CPA set<% } %></div>
        <% if (cfg.targetCpa && t.cpa != null) { %><div class="meter" style="margin-top:8px"><span style="width:<%= Math.max(4, Math.min(100, Math.round(cfg.targetCpa / t.cpa * 100))) %>%"></span></div><% } %>
      </div>

      <div class="ov">
        <div class="ovl">Clicks</div>
        <div class="ovv tnum"><% if (t.clicks != null) { %><%= n0(t.clicks) %><% } else { %><%- nov %><% } %></div>
        <div class="rr-meta" style="margin-top:5px"><% if (t.impressions != null) { %>from <%= n0(t.impressions) %> impressions<% } else { %>No impression data<% } %></div>
      </div>

      <div class="ov">
        <div class="ovl">Avg. CPC<%- h.ihelp('Avg. CPC', 'What one click cost on average across the window.') %></div>
        <div class="ovv tnum"><% if (t.cpc != null) { %><%= m(t.cpc) %><% } else { %><%- nov %><% } %></div>
      </div>

      <div class="ov">
        <div class="ovl">Search impr. share <span class="periodonly" title="Google reports impression share for a period, not per day, so this one keeps the sync's own window whatever range you pick">period</span></div>
        <% if (search) { %>
          <div class="ovv tnum"><%= Math.round(search.impressionShare) %><small>%</small> <% if (search.lostIsBudget > 10) { %><span class="chip warn"><%= Math.round(search.lostIsBudget) %>% lost</span><% } %></div>
          <div class="rr-meta" style="margin-top:5px"><%= Math.round(search.lostIsBudget) %>% lost to budget · <%= Math.round(search.lostIsRank) %>% to rank</div>
        <% } else { %>
          <div class="ovv tnum"><%- nov %></div>
          <div class="lockwhy">Impression share is reported for Search and Shopping campaigns only.</div>
        <% } %>
      </div>

      <div class="ov<%= chosen.locked ? ' locked' : '' %>">
        <form method="GET" action="/ppc" class="ovl" style="display:flex;align-items:center;gap:8px;margin-bottom:7px">
          <select class="metricsel" name="m2" onchange="this.form.submit()" aria-label="Choose metric">
            <% Object.keys(METRICS).forEach(function(k){ var x = METRICS[k]; %>
              <option value="<%= k %>" <%= k === sel ? 'selected' : '' %>><%= x.label %><%= x.locked ? ' (not tracked)' : '' %></option>
            <% }) %>
          </select>
          <% if (chosen.locked) { %><span class="chip flat">Not tracked</span><% } else { %><%- chosen.chip %><% } %>
          <noscript><button class="btn btn-sm" type="submit">Go</button></noscript>
        </form>
        <% if (chosen.locked) { %>
          <div class="ovv tnum"><%- nov %></div>
          <div class="lockwhy"><%- chosen.why %> <a href="/integrations"><%= chosen.fix %></a></div>
        <% } else { %>
          <div class="ovv tnum"><%= chosen.val %></div>
          <div class="rr-meta" style="margin-top:5px"><%= chosen.foot %></div>
        <% } %>
      </div>
    </div>

  </div>

  <div class="card card-p b4">
    <div class="card-h" style="padding:0 0 12px"><h3>What this account can measure<%- h.ihelp('What this account can measure',
      'Greyed rows need a setup step in Google Ads before the metric can be shown.') %></h3></div>

    <div style="display:flex;flex-direction:column;gap:9px;font-size:var(--fs-sm)">
      <div class="row-between"><span>Conversions</span><span class="chip <%= t.conversions != null ? 'pos' : 'flat' %>"><%= t.conversions != null ? 'tracked' : 'not tracked' %></span></div>
      <div class="row-between"><span>Conversion values</span><span class="chip <%= av.convValue ? 'pos' : 'flat' %>"><%= av.convValue ? 'tracked' : 'not configured' %></span></div>
      <div class="row-between"><span>Impression share</span><span class="chip <%= av.impressionShare ? 'pos' : 'flat' %>"><%= av.impressionShare ? 'available' : 'no eligible campaigns' %></span></div>
      <div class="row-between"><span>Quality Score</span><span class="chip <%= av.qualityScore ? 'pos' : 'flat' %>"><%= av.qualityScore ? 'available' : 'not in the export' %></span></div>
      <div class="row-between"><span>Daily history</span><span class="chip <%= av.daily ? 'pos' : 'flat' %>"><%= av.daily ? 'available' : 'not yet' %></span></div>
    </div>
  </div>

  <%

    var _shelf = [
      { l: 'Ad accounts', v: accounts.length },
      { l: 'Campaigns',   v: campN },
      { l: 'Channels',    v: (d.channels || []).length },
      { l: 'Recommendations', v: (d.findings || []).length }
    ];
    var _tints = ['sc-violet', 'sc-lime', 'sc-navy', 'sc-sky', 'sc-sand', 'sc-rose'];
  %>
  <% _shelf.forEach(function (s, i) { %>
    <div class="card shelf-c b3 <%= _tints[i % _tints.length] %>">
      <div class="cl"><%= s.l %></div>
      <div class="cv tnum"><% if (s.v != null) { %><%= s.v %><% } else { %><%- nov %><% } %></div>
    </div>
  <% }) %>

  <div class="card wastecard card-p b6">
    <% if (!cfg.targetCpa) { %>
      <div class="eyebrow" style="color:var(--warn-ink)">Cannot run yet</div>
      <div class="rr-title" style="margin-top:8px">No target CPA on file</div>

      <div class="muted" style="font-size:var(--fs-sm);margin-top:7px">Waste is flagged against a multiple of the target CPA. Set one to turn it on.</div>
      <% if (_staff) { %><div style="margin-top:14px"><a class="btn btn-sm btn-primary" href="/staff/clients">Set the target CPA</a></div><% } %>
    <% } else if (!waste || !waste.total) { %>
      <div class="eyebrow">Action needed</div>
      <div class="bigmoney" style="margin-top:8px;color:var(--pos)"><%= m(0) %></div>

      <div class="muted" style="font-size:var(--fs-sm);margin-top:7px">No campaign or search term spent <%= m(waste ? waste.threshold : cfg.wasteMultiple * cfg.targetCpa) %> or more without converting.</div>
    <% } else { %>
      <div class="row-between" style="align-items:flex-start">
        <div>
          <div class="eyebrow" style="color:var(--neg)">Action needed</div>
          <div class="bigmoney burn" style="margin-top:8px"><%= m(waste.total) %></div>

          <div class="muted" style="font-size:var(--fs-sm);margin-top:7px;max-width:340px">
            Spend on entities that produced no conversion after the <%= waste.lagDays %>-day lag window closed<% if (waste.campaigns) { %>, covering <%= waste.campaigns %> campaign<%= waste.campaigns > 1 ? 's' : '' %> (<%= m(waste.campaignCost) %>)<% } %><% if (waste.terms) { %><%= waste.campaigns ? ' and ' : ', covering ' %><%= waste.terms %> search term<%= waste.terms > 1 ? 's' : '' %> (<%= m(waste.termCost) %>)<% } %>.
          </div>
        </div>
        <span class="chip neg"><%= (waste.campaigns || 0) + (waste.terms ? 1 : 0) %> items</span>
      </div>
      <div style="display:flex;gap:9px;margin-top:16px">
        <% if (waste.terms) { %><a class="btn btn-sm btn-primary" href="/ppc/keywords">Review the <%= waste.terms %> terms</a><% } %>
        <a class="btn btn-sm" href="/ppc/campaigns">See campaigns</a>
      </div>
      <div class="modelled">
        <b style="color:var(--muted)">How this is calculated.</b> Sum of window cost for every campaign, keyword and
        search term with <b style="color:var(--muted)">0 conversions</b> and cost ≥ <%= waste.multiple %>× target CPA
        (<%= m(waste.threshold) %>), excluding the last <%= waste.lagDays %> days. This is spend already incurred.
      </div>
    <% } %>
  </div>

  <div class="card oppcard card-p b6">
    <% if (!opp) { %>
      <div class="eyebrow">Opportunity</div>
      <div class="rr-title" style="margin-top:8px">Nothing is capped right now</div>

      <div class="muted" style="font-size:var(--fs-sm);margin-top:7px">No campaign is below target CPA, losing over 10% of impression share to budget, and above 30 conversions at the same time.</div>
    <% } else { %>
      <div class="row-between" style="align-items:flex-start">
        <div>
          <div class="eyebrow">Opportunity (modelled)</div>

          <div class="bigmoney saving" style="margin-top:8px">≈ <%= opp.expected %><span style="font-size:var(--fs-base);color:var(--muted);font-weight:500"> conv/mo</span></div>

          <div class="muted" style="font-size:var(--fs-sm);margin-top:7px;max-width:340px"><b style="color:var(--ink)"><%= opp.name %></b> runs at <%= m(opp.cpa) %> against a <%= m(cfg.targetCpa) %> target and is capped by its own budget. Closing the gap costs about <%= m(opp.extraSpend) %>/mo.</div>
        </div>
        <span class="chip teal">Recommended</span>
      </div>
      <div style="display:flex;gap:9px;margin-top:16px">
        <a class="btn btn-sm btn-teal" href="/ppc/budget">Model the reallocation</a>
        <a class="btn btn-sm" href="/ppc/campaigns/<%= opp.campaign %>">Open campaign</a>
      </div>
      <div class="modelled">
        <b style="color:var(--muted)">How this is calculated.</b> Capturing the impression share lost to budget costs
        roughly <%= m(opp.extraSpend) %>. At the campaign's current <%= m(opp.cpa) %> CPA that would buy
        <%= opp.ceiling %> conversions, but marginal auctions cost more than average ones, so applying the
        <%= cfg.incrementalFactor %>× incremental factor (<%= m(opp.incCpa) %>) gives roughly <%= opp.expected %>.
        <%= opp.ceiling %> is the theoretical maximum.
      </div>
    <% } %>
  </div>

  <div class="col b12">
<%- include('../partials/ppc-trend', { d: d, cfg: cfg, m: m }) %>
  </div>

  <div class="card b8">
    <div class="card-h"><h3>Campaigns</h3><span class="hint">by spend</span>
      <a class="more" href="/ppc/campaigns">All <%= campN %></a></div>
    <div style="overflow-x:auto">
    <table class="tbl">
      <thead><tr><th>Campaign</th><th>Channel</th><th style="text-align:right">Spend</th><th style="text-align:right">Conv</th><th style="text-align:right">CPA</th><th style="text-align:right">Conv. rate</th><th></th></tr></thead>
      <tbody>
      <% campaigns.slice(0, 8).forEach(function(c){
           var mm = c.metrics || {};
           var cpa = (mm.cost != null && mm.conversions) ? mm.cost / mm.conversions : null;
           var cr = (mm.conversions != null && mm.clicks) ? (mm.conversions / mm.clicks * 100) : null;
           var bad = cfg.targetCpa && cpa != null && cpa > cfg.targetCpa;
           var dead = mm.cost > 0 && mm.conversions === 0;
           var good = cfg.targetCpa && cpa != null && cpa <= cfg.targetCpa * 0.8;
      %>
        <tr class="<%= dead ? 'is-waste linked' : (good ? 'is-winner linked' : 'linked') %>">
          <td class="strong"><a href="/ppc/campaigns/<%= c._id %>"><%= c.name %></a></td>
          <td><span class="chan <%= c.channel %>"><%= c.channel === 'pmax' ? 'PMax' : c.channel %></span></td>
          <td class="num" style="text-align:right"><%= m(mm.cost) %></td>
          <td class="num" style="text-align:right<%= dead ? ';color:var(--neg)' : '' %>"><%= n0(mm.conversions) %></td>
          <td class="num" style="text-align:right<%= cpa == null ? '' : (bad ? ';color:var(--neg)' : (good ? ';color:var(--pos)' : '')) %>"><%= cpa == null ? '—' : m(cpa) %></td>
          <td class="num" style="text-align:right"><%= cr == null ? '—' : cr.toFixed(2) + '%' %></td>
          <td><% if (dead) { %><span class="flag waste">Waste</span><% } else if (good) { %><span class="flag winner">Winner</span><% } %></td>
        </tr>
      <% }) %>
      </tbody>
    </table>
    </div>
  </div>

  <div class="col b4">
    <%- include('../partials/ppc-channels', { d: d, campaigns: campaigns, groups: locals.groups || [], m: m, n0: n0 }) %>

    <%- include('../partials/ppc-conversions', { d: d }) %>

    <% if (d.pacing) { var pc = d.pacing; %>
    <div class="card card-p">
      <div class="row-between"><div class="rr-lbl"><%= pc.month %> pacing</div><span class="chip <%= pc.state === 'over' ? 'warn' : (pc.state === 'under' ? 'flat' : 'pos') %>"><%= pc.state === 'on_track' ? 'on track' : (Math.abs(Math.round(pc.variancePct)) + '% ' + pc.state) %></span></div>

      <div class="rr-title"><%= m(pc.spent) %> <span class="muted" style="font-size:var(--fs-sm);font-weight:400">of <%= m(pc.budget) %></span></div>
      <div class="rr-meta">Day <%= pc.dayOfMonth %> of <%= pc.daysInMonth %> · forecast <b style="color:var(--<%= pc.state === 'over' ? 'neg' : 'ink' %>)"><%= m(pc.forecast) %></b></div>
      <div class="meter" style="margin-top:12px"><span style="width:<%= Math.max(2, Math.min(100, Math.round(pc.spent / pc.budget * 100))) %>%;background:var(--<%= pc.state === 'over' ? 'warn' : 'teal' %>)"></span></div>
      <div class="rr-actions"><a class="btn btn-sm" href="/ppc/budget">Budget &amp; pacing</a></div>
    </div>
    <% } %>
  </div>

  <div class="col b12">
<%- include('../partials/ppc-done', { done: locals.done || [], doneStats: locals.doneStats || {} }) %>
  </div>

  <div class="col b12">
<%- include('../partials/ppc-findings', { findings: locals.findings || [], d: d, cfg: cfg }) %>
  </div>
</div>
<% } %>
