<%

  var d = locals.dash;
  var clUrl = projectId ? 'https://clarity.microsoft.com/projects/view/' + encodeURIComponent(projectId) + '/dashboard' : 'https://clarity.microsoft.com/';
  var n1 = function (v) { return v == null ? '—' : (Math.round(v * 100) / 100).toLocaleString('en-US'); };
  var pct = function (v) { return v == null ? '—' : (Math.round(v * 10) / 10) + '%'; };
  var secs = function (v) { if (v == null) return '—'; v = Math.round(v); var m = Math.floor(v / 60), s = v % 60; return m ? m + 'm ' + s + 's' : s + 's'; };
  var path = function (u) { try { var x = new URL(u); return decodeURIComponent(x.pathname + (x.search || '')) || '/'; } catch (e) { return u || ''; } };
  var ov = (d && d.overview) || {};
  var S = ov.sessions || 0;
  var share = function (n) { return S ? Math.round(n / S * 1000) / 10 : 0; };
  var BEH = [
    ['rageClicks', 'Rage clicks', 'Repeated fast clicks on one spot: something looked clickable and did not respond.'],
    ['deadClicks', 'Dead clicks', 'Clicks that did nothing.'],
    ['excessiveScroll', 'Excessive scrolling', 'Scrolling up and down more than reading needs: often a sign they cannot find something.'],
    ['quickbacks', 'Quick-backs', 'Visitors who opened a page and went straight back.'],
    ['scriptErrors', 'JavaScript errors', 'Sessions where a script error happened on the page.'],
    ['errorClicks', 'Error clicks', 'Clicks that triggered a script error.']
  ];
  var rate = function (k, v) {
    if (v == null) return ['flat', '—'];
    if (k === 'lcp') return v <= 2500 ? ['pos', 'good'] : v <= 4000 ? ['warn', 'needs improvement'] : ['neg', 'poor'];
    if (k === 'inp') return v <= 200 ? ['pos', 'good'] : v <= 500 ? ['warn', 'needs improvement'] : ['neg', 'poor'];
    if (k === 'cls') return v <= 0.1 ? ['pos', 'good'] : v <= 0.25 ? ['warn', 'needs improvement'] : ['neg', 'poor'];
    return v >= 90 ? ['pos', 'good'] : v >= 50 ? ['warn', 'needs improvement'] : ['neg', 'poor'];
  };
  var failed = function (k) { return d && (d.failed || []).some(function (f) { return f.section === k; }); };
%>
<div class="pg-head" style="margin-bottom:0">
  <div><div class="eyebrow">SEO &amp; Content / User Behavior</div></div>
  <div class="ph-right" style="display:flex; gap:10px; align-items:center; flex-wrap:wrap">
    <% if (connected) { %><a class="btn btn-sm" href="<%= clUrl %>" target="_blank" rel="noopener">Heatmaps &amp; recordings in Clarity ↗</a><% } %>
    <%- include('../partials/range-picker') %>
  </div>
</div>

<div id="ub-view">
<h1 class="claim"><%= title %></h1>
<% if (!connected) { %>
  <p class="claim-lede">Clarity is not connected for this account yet.</p>
  <p class="claim-sub">Your VOCTOS team connects it from your Clarity project. Ask on <a href="/messages">Messages</a>.</p>
<% } else if (locals.pending) { %>
  <p class="claim-lede">Reading your Clarity data for <%= from %> to <%= to %>…</p>
  <p class="claim-sub">This takes about 15 seconds the first time. After that it is kept for 6 hours.</p>
  <div class="ub-load"><span></span><span></span><span></span></div>
  <script>
  (function () {
    var u = new URL(location.href); u.searchParams.set('load', '1');
    fetch(u.toString(), { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
      .then(function (r) { return r.text(); })
      .then(function (html) {
        var fresh = new DOMParser().parseFromString(html, 'text/html').getElementById('ub-view');
        var cur = document.getElementById('ub-view');
        if (fresh && cur) { cur.replaceWith(fresh); document.dispatchEvent(new CustomEvent('voctos:refreshed', { detail: { selector: '#ub-view' } })); }
        else location.href = u.toString();
      })
      .catch(function () { location.href = u.toString(); });
  })();
  </script>
<% } else if (!d || !d.ok) { %>
  <p class="claim-lede">Clarity did not answer for these dates.</p>
  <p class="claim-sub"><%= (d && d.failed && d.failed[0] && d.failed[0].error) || (d && d.reason) || 'Try again in a few minutes.' %></p>
<% } else { %>
  <p class="claim-lede"><em><%= h.int(S) %></em> sessions from <%= h.int(ov.users) %> people between <%= d.from %> and <%= d.to %>.</p>
  <p class="claim-sub">From your Clarity dashboard<%= ov.botSessions ? ', ' + h.int(ov.botSessions) + ' bot sessions left out' : '' %>. Updated <%= h.time(d.at) %>.</p>

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

  <% if (locals.showStaff) { var iss = locals.issues || []; %>
  <div class="card b12" id="ub-issues">
    <div class="card-h"><h3>Issues to look at</h3><span class="hint">staff only · <%= iss.length ? iss.length + ' found for these dates' : 'nothing above the thresholds' %> · sent to the team monthly</span></div>
    <div class="card-p">
      <% if (!iss.length) { %><div class="rr-meta">Frustration signals, speed and errors are all within normal ranges for these dates.</div><% } else { %>
      <div class="ub-iss">
        <% iss.forEach(function (i) { %>
          <div class="ub-is <%= i.level %>"><span class="chip <%= i.level === 'high' ? 'neg' : 'warn' %>"><%= i.level === 'high' ? 'serious' : 'check' %></span>
            <div><div class="strong"><%= i.title %></div><div class="rr-meta"><%= i.detail %></div></div></div>
        <% }) %>
      </div>
      <% } %>
    </div>
  </div>
  <% } %>
  <% var us = d.users || {}; var tu = (us.newSessions || 0) + (us.returningSessions || 0); %>
  <div class="card shelf-c b3 sc-violet"><div class="cl">Sessions</div><div class="cv tnum"><%= h.int(S) %></div>
    <div class="rr-meta" style="margin-top:4px"><% if (tu) { %><%= Math.round(us.newSessions / tu * 100) %>% new · <%= Math.round(us.returningSessions / tu * 100) %>% returning<% } else { %><%= h.int(ov.users) %> unique users<% } %></div></div>
  <div class="card shelf-c b3 sc-lime"><div class="cl">Pages per session</div><div class="cv tnum"><%= n1(ov.pagesPerSession) %></div><div class="rr-meta" style="margin-top:4px"><%= h.int(ov.users) %> unique users</div></div>
  <div class="card shelf-c b3 sc-sky"><div class="cl">Scroll depth</div><div class="cv tnum"><%= pct(ov.scrollDepth) %></div><div class="rr-meta" style="margin-top:4px">How far down the page, on average</div></div>
  <div class="card shelf-c b3 sc-navy"><div class="cl">Active time</div><div class="cv tnum"><%= secs(ov.activeTime) %></div><div class="rr-meta" style="margin-top:4px"><%= ov.totalTime != null ? 'out of ' + secs(ov.totalTime) + ' on the site' : 'per session' %></div></div>

  <% if ((d.daily || []).length > 1) { var mx = Math.max.apply(null, d.daily.map(function (t) { return t.sessions; })) || 1; %>
  <div class="card b12">
    <div class="card-h"><h3>Sessions per day</h3><span class="hint"><%= d.daily.length %> days</span></div>
    <div class="card-p"><div class="ub-trend">
      <% d.daily.forEach(function (t) { %><div class="ub-col" title="<%= t.day %>: <%= h.int(t.sessions) %> sessions<%= t.users != null ? ', ' + t.users + ' users' : '' %>"><i style="height:<%= Math.max(2, Math.round(t.sessions / mx * 100)) %>%"></i><span><%= d.daily.length > 20 ? (t.day.slice(8) === '01' || t.day === d.daily[0].day ? t.day.slice(5) : '') : t.day.slice(8) %></span></div><% }) %>
    </div></div>
  </div>
  <% } %>

  <div class="card b7">
    <div class="card-h"><h3>Where visitors got stuck</h3><span class="hint">share of sessions</span></div>
    <div class="card-p ub-beh">
      <% var ins = d.insights || {}; BEH.forEach(function (b) { var v = ins[b[0]]; var p = share(v || 0); %>
        <div class="ub-b" title="<%= b[2] %>">
          <div class="row-between"><span class="strong"><%= b[1] %></span><span class="tnum <%= p >= 5 ? 'neg' : '' %>"><%= v == null ? '—' : pct(p) %></span></div>
          <div class="ub-bar"><i class="<%= p >= 5 ? 'hi' : '' %>" style="width:<%= Math.min(100, p * 4) %>%"></i></div>
          <div class="rr-meta"><%= v == null ? 'not available' : h.int(v) + ' session' + (v === 1 ? '' : 's') %></div>
        </div>
      <% }) %>
    </div>
  </div>

  <% var pf = d.performance || {}; var sc = rate('score', pf.score); %>
  <div class="card b5">
    <div class="card-h"><h3>Site speed</h3><span class="hint"><%= pf.pageViews ? 'from ' + h.int(pf.pageViews) + ' page views' : '' %></span></div>
    <div class="card-p">
      <% if (pf.score == null) { %><div class="rr-meta">Clarity has no speed data for these dates.</div><% } else { %>
      <div style="display:flex; align-items:baseline; gap:10px"><span class="ub-score"><%= Math.round(pf.score) %></span><span class="rr-meta">/ 100 performance score</span></div>
      <% if (pf.good != null) { %>
        <div class="ub-split"><i class="pos" style="width:<%= pf.good %>%"></i><i class="warn" style="width:<%= pf.needsImprovement || 0 %>%"></i><i class="neg" style="width:<%= pf.poor || 0 %>%"></i></div>
        <div class="rr-meta"><%= pct(pf.good) %> good · <%= pct(pf.needsImprovement) %> needs improvement · <%= pct(pf.poor) %> poor</div>
      <% } %>
      <div class="ub-vitals">
        <% [['lcp', 'LCP', 'Largest Contentful Paint', pf.lcp != null ? (Math.round(pf.lcp / 100) / 10) + 's' : '—'], ['inp', 'INP', 'Interaction to Next Paint', pf.inp != null ? Math.round(pf.inp) + 'ms' : '—'], ['cls', 'CLS', 'Cumulative Layout Shift', pf.cls != null ? (Math.round(pf.cls * 100) / 100) : '—']].forEach(function (x) { var r = rate(x[0], pf[x[0]]); %>
          <div><div class="ub-vv"><%= x[3] %></div><div class="strong" style="font-size:12.5px"><%= x[1] %></div><div class="rr-meta" style="font-size:11.5px"><%= x[2] %></div><span class="chip <%= r[0] %>" style="font-size:10.5px; margin-top:4px"><%= r[1] %></span></div>
        <% }) %>
      </div>
      <% } %>
    </div>
  </div>

  <%
    var cards = [
      ['channels', 'Channels'], ['sources', 'Sources'], ['referrers', 'Referrers'],
      ['countries', 'Countries'], ['devices', 'Devices'], ['browsers', 'Browsers'],
      ['os', 'Operating systems'], ['events', 'Smart events'], ['campaigns', 'Campaigns']
    ];
  %>
  <% cards.forEach(function (x) { var list = d[x[0]] || []; if (x[0] === 'campaigns' && !list.length) return; %>
  <div class="card b4">
    <div class="card-h"><h3><%= x[1] %></h3><span class="hint"><%= failed(x[0]) ? 'not available' : (x[0] === 'events' ? 'sessions' : 'share of sessions') %></span></div>
    <div class="card-p ub-list" style="display:flex; flex-direction:column; gap:9px">
      <% if (!list.length) { %><span class="rr-meta"><%= failed(x[0]) ? 'Clarity did not answer this one.' : 'Nothing recorded.' %></span><% } %>
      <% list.forEach(function (r) { var s = share(r.sessions); %>
        <div><div class="row-between" style="font-size:13px; gap:10px"><span style="word-break:break-word"><%= r.value %></span><span class="tnum" style="white-space:nowrap"><%= h.int(r.sessions) %> <span class="rr-meta">· <%= s %>%</span></span></div>
          <div class="ub-bar"><i style="width:<%= Math.min(100, s) %>%"></i></div></div>
      <% }) %>
    </div>
  </div>
  <% }) %>

  <% [['entry', 'Entry pages', 'where sessions started'], ['exit', 'Exit pages', 'where sessions ended']].forEach(function (x) { var list = d[x[0]] || []; %>
  <div class="card b6">
    <div class="card-h"><h3><%= x[1] %></h3><span class="hint"><%= x[2] %></span></div>
    <div class="card-p ub-list" style="display:flex; flex-direction:column; gap:9px">
      <% if (!list.length) { %><span class="rr-meta">Nothing recorded.</span><% } %>
      <% list.forEach(function (r) { var s = share(r.sessions); %>
        <div><div class="row-between" style="font-size:13px; gap:10px"><a href="<%= r.value %>" target="_blank" rel="noopener" style="word-break:break-all"><%= path(r.value) %></a><span class="tnum" style="white-space:nowrap"><%= h.int(r.sessions) %> <span class="rr-meta">· <%= s %>%</span></span></div>
          <div class="ub-bar"><i style="width:<%= Math.min(100, s) %>%"></i></div></div>
      <% }) %>
    </div>
  </div>
  <% }) %>

  <div class="card b12">
    <div class="card-h"><h3>Pages</h3><span class="hint"><%= (d.pages || []).length %> pages by sessions · counts are sessions that had the problem on that page</span></div>
    <% if (!(d.pages || []).length) { %><div class="card-p rr-meta"><%= failed('pages') ? 'Clarity did not answer this one.' : 'Nothing recorded.' %></div><% } else { %>

    <div class="ub-tbl"><table class="tbl">
      <thead><tr><th>Page</th><th>Sessions</th><th>Scroll depth</th><th>Active time</th><th>Dead clicks</th><th>Rage clicks</th><th>Quick-backs</th><th>Excessive scroll</th></tr></thead>
      <tbody>
      <% d.pages.forEach(function (p) { %>
        <tr>
          <td style="max-width:420px; word-break:break-all"><a href="<%= p.value %>" target="_blank" rel="noopener"><%= path(p.value) %></a></td>
          <td class="tnum"><%= h.int(p.sessions) %></td>
          <td class="tnum"><%= pct(p.scrollDepth) %></td>
          <td class="tnum"><%= secs(p.activeTime) %></td>
          <% ['deadClicks', 'rageClicks', 'quickbacks', 'excessiveScroll'].forEach(function (k) { %><td class="tnum<%= p[k] ? (k === 'rageClicks' ? ' neg' : '') : ' muted' %>"><%= h.int(p[k] || 0) %></td><% }) %>
        </tr>
      <% }) %>
      </tbody>
    </table></div>
    <% } %>
  </div>

  <div class="card b12">
    <div class="card-h"><h3>JavaScript errors</h3><span class="hint"><%= (d.errors || []).length ? '' : 'none' %></span></div>
    <div class="card-p">
      <% if (!(d.errors || []).length) { %><span class="rr-meta"><%= failed('errors') ? 'Clarity did not answer this one.' : 'No script errors recorded.' %></span><% } else { %>
      <table class="tbl"><thead><tr><th>Error</th><th>Times</th><th>Sessions</th></tr></thead><tbody>
        <% d.errors.forEach(function (e) { %><tr><td class="code" style="word-break:break-word"><%= e.message %></td><td class="tnum"><%= h.int(e.count) %></td><td class="tnum"><%= h.int(e.sessions) %></td></tr><% }) %>
      </tbody></table>
      <% } %>
    </div>
  </div>
</div>
<% if ((d.failed || []).length) { %><p class="rr-meta" style="margin-top:12px">Not available this time: <%= d.failed.map(function (f) { return f.section; }).join(', ') %>.</p><% } %>
<% } %>
</div>

<style>
  .ub-trend{display:flex; align-items:flex-end; gap:3px; height:160px}
  .ub-col{flex:1; display:flex; flex-direction:column; align-items:center; justify-content:flex-end; height:100%; min-width:0}
  .ub-col i{display:block; width:100%; max-width:28px; background:var(--accent-strong); border-radius:4px 4px 0 0; opacity:.85}
  .ub-col span{font-size:10px; color:var(--muted-2); margin-top:4px; white-space:nowrap; height:12px}
  .ub-beh{display:grid; grid-template-columns:repeat(auto-fit, minmax(200px, 1fr)); gap:16px 26px}
  .ub-b{display:flex; flex-direction:column; gap:5px}
  .ub-bar{height:6px; border-radius:99px; background:var(--surface-2); overflow:hidden; margin-top:3px}
  .ub-bar i{display:block; height:100%; border-radius:99px; background:var(--accent-strong)}
  .ub-bar i.hi{background:var(--neg)}
  .ub-beh .neg{color:var(--neg)}
  .ub-score{font-family:var(--font-display, inherit); font-size:40px; font-weight:700; line-height:1; color:var(--ink)}
  .ub-split{display:flex; height:8px; border-radius:99px; overflow:hidden; margin:12px 0 6px; background:var(--surface-2)}
  .ub-split i{display:block; height:100%} .ub-split i.pos{background:var(--pos)} .ub-split i.warn{background:#E2A03F} .ub-split i.neg{background:var(--neg)}
  .ub-vitals{display:grid; grid-template-columns:repeat(3, 1fr); gap:12px; margin-top:16px}
  .ub-vitals>div{border:1px solid var(--line); border-radius:10px; padding:10px}
  .ub-vv{font-size:22px; font-weight:700; color:var(--ink); line-height:1.1; margin-bottom:4px}
  .ub-tbl{overflow:auto; max-height:70vh}

  .ub-list{max-height:400px; overflow-y:auto; scrollbar-width:thin}
  .ub-tbl thead th{position:sticky; top:0; z-index:2; background:var(--surface); box-shadow:inset 0 -1px 0 var(--line)}
  .ub-iss{display:grid; grid-template-columns:repeat(auto-fit, minmax(300px, 1fr)); gap:10px 22px}
  .ub-is{display:flex; gap:10px; align-items:flex-start; padding:10px 0; border-bottom:1px solid var(--line-2)}
  .ub-is .chip{flex:none; font-size:10.5px; margin-top:2px}
  .ub-is .rr-meta{margin-top:3px; line-height:1.5}
  .ub-load{display:flex; gap:8px; margin:26px 0}
  .ub-load span{width:10px; height:10px; border-radius:50%; background:var(--accent-strong); animation:ubp 1s infinite ease-in-out}
  .ub-load span:nth-child(2){animation-delay:.15s} .ub-load span:nth-child(3){animation-delay:.3s}
  @keyframes ubp{0%,80%,100%{opacity:.25; transform:scale(.8)} 40%{opacity:1; transform:none}}
</style>
