<%

var daily = (d.daily || []).filter(function(r){ return r && r.date; });
var weeks = [];
if (daily.length) {
  var bucket = {};
  daily.forEach(function(r){
    var dt = new Date(r.date);
    var k = new Date(dt); k.setDate(dt.getDate() - ((dt.getDay() + 6) % 7));
    var key = k.toISOString().slice(0, 10);
    bucket[key] = bucket[key] || { label: k, cost: 0, conv: 0 };
    bucket[key].cost += r.cost || 0;
    bucket[key].conv += r.conversions || 0;
  });
  weeks = Object.keys(bucket).sort().map(function(k){ return bucket[k]; }).slice(-12)
    .map(function(b){ return { label: b.label, cost: b.cost, conv: b.conv, cpa: b.conv ? b.cost / b.conv : null }; });
}

var enough = weeks.filter(function(w){ return w.cpa !== null; }).length >= 3;
%>

<div class="card" style="margin-top:16px">
  <div class="card-h"><h3>Cost per conversion vs conversions</h3>
    <span class="hint"><%= weeks.length ? 'last ' + weeks.length + ' weeks' : 'weekly' %></span></div>
  <div class="card-p">
  <% if (!enough) { %>

    <div class="muted" style="font-size:var(--fs-sm);line-height:1.6">
      The trend appears after three weeks with conversions (<%= weeks.length %> week<%= weeks.length === 1 ? '' : 's' %> so far).

      <% if (!(d.availability || {}).daily && locals.showStaff) { %> The export is not writing a <span class="code">daily</span> tab; add it to the Ads Script and this fills in on the next sync.<% } %>
    </div>
  <% } else {
      var cpas = weeks.map(function(w){ return w.cpa; }).filter(function(v){ return v !== null; });
      var convs = weeks.map(function(w){ return w.conv; });
      var loC = Math.min.apply(null, cpas), hiC = Math.max.apply(null, cpas);
      if (cfg.targetCpa) { loC = Math.min(loC, cfg.targetCpa); hiC = Math.max(hiC, cfg.targetCpa); }
      var padC = Math.max(1, (hiC - loC) * 0.15); loC -= padC; hiC += padC;
      var hiV = Math.max.apply(null, convs.concat([1]));
      var X0 = 60, X1 = 700, Y0 = 190, Y1 = 40;
      var n = weeks.length;
      var px = function(i){ return n < 2 ? X0 : X0 + i * ((X1 - X0) / (n - 1)); };
      var pyC = function(v){ return Y0 - ((v - loC) / (hiC - loC)) * (Y0 - Y1); };
      var pyV = function(v){ return Y0 - (v / hiV) * (Y0 - Y1); };
      var lineC = weeks.map(function(w, i){ return w.cpa === null ? null : (Math.round(px(i)) + ',' + Math.round(pyC(w.cpa) * 10) / 10); }).filter(Boolean).join(' ');
      var lineV = weeks.map(function(w, i){ return Math.round(px(i)) + ',' + Math.round(pyV(w.conv) * 10) / 10; }).join(' ');
      var first = weeks.find(function(w){ return w.cpa !== null; });
      var last = weeks.slice().reverse().find(function(w){ return w.cpa !== null; });
      var cpaChange = (first && last && first.cpa) ? Math.round((last.cpa - first.cpa) / first.cpa * 100) : null;
      var convChange = (weeks[0].conv) ? Math.round((weeks[n-1].conv - weeks[0].conv) / weeks[0].conv * 100) : null;
  %>
    <div class="legend">
      <span><i class="lg navy"></i> Cost per conversion (left)</span>
      <span><i class="lg"></i> Conversions (right)</span>
      <% if (cfg.targetCpa) { %><span><i class="lg dash"></i> Target CPA <%= m(cfg.targetCpa) %></span><% } %>
      <% if (cpaChange !== null && convChange !== null) { %>
        <span style="margin-left:auto;font-weight:600;color:var(--<%= (cpaChange <= 0 && convChange >= 0) ? 'pos' : 'muted' %>)">CPA <%= cpaChange > 0 ? '+' : '' %><%= cpaChange %>% · conversions <%= convChange > 0 ? '+' : '' %><%= convChange %>%</span>
      <% } %>
    </div>
    <svg class="chart" viewBox="0 0 770 210" role="img" aria-label="Weekly cost per conversion against conversion volume">
      <g stroke="var(--line-2)" stroke-width="1">
        <line x1="60" y1="40" x2="700" y2="40"/><line x1="60" y1="77.5" x2="700" y2="77.5"/>
        <line x1="60" y1="115" x2="700" y2="115"/><line x1="60" y1="152.5" x2="700" y2="152.5"/>
        <line x1="60" y1="190" x2="700" y2="190" stroke="var(--line)"/>
      </g>

      <line class="ax" x1="60" y1="40" x2="60" y2="190"/>
      <% if (cfg.targetCpa) { var ty = pyC(cfg.targetCpa); %>
        <line x1="60" y1="<%= ty.toFixed(1) %>" x2="700" y2="<%= ty.toFixed(1) %>" stroke="var(--muted-2)" stroke-width="1.5" stroke-dasharray="5 4"/>
      <% } %>
      <g font-size="10" fill="var(--muted-2)" text-anchor="end">
        <% [0,1,2,3,4].forEach(function(i){ var v = hiC - (hiC - loC) * (i / 4); %>
          <text x="52" y="<%= (40 + i * 37.5 + 3).toFixed(0) %>"><%= m(v) %></text>
        <% }) %>
      </g>
      <g font-size="10" fill="var(--muted-2)" text-anchor="start">
        <% [0,1,2,3,4].forEach(function(i){ var v = hiV - hiV * (i / 4); %>
          <text x="710" y="<%= (40 + i * 37.5 + 3).toFixed(0) %>"><%= Math.round(v).toLocaleString('en-US') %></text>
        <% }) %>
      </g>
      <polyline fill="none" stroke="var(--navy)" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" points="<%= lineC %>"/>
      <polyline fill="none" stroke="var(--teal)" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" points="<%= lineV %>"/>
    </svg>
    <div class="axis-x" style="padding:0 12px 0 52px">
      <% weeks.forEach(function(w, i){ if (i % Math.ceil(n / 6) === 0 || i === n - 1) { %><span><%= h.date(w.label) %></span><% } }) %>
    </div>
    <div class="modelled">
      <span class="ihelp-w" tabindex="0" role="button" aria-label="Why CPA and conversions"><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> Why CPA and conversions
        <span class="ihelp-pop" role="tooltip"><b>Why CPA and conversions.</b>
          CPA falling while conversions rise shows the account getting more efficient. Weeks with no
          conversions are left out of the CPA line.
        </span>
      </span>
    </div>
  <% } %>
  </div>
</div>
