<% var canManage = locals.showStaff; %>
<%

  var _showSoV = true;
%>
<%

  var _rows    = rows || [];
  var _you     = _rows.filter(function(r){ return r.isYou; })[0];
  var _counted = _rows.filter(function(r){ return r.mentions != null; })
                      .sort(function(a,b){ return b.mentions - a.mentions; });

  var _rank    = locals.brandStanding ? locals.brandStanding.rank : 0;

  var _movers  = _rows.filter(function(r){ return r.growth; })
                      .sort(function(a,b){ return Math.abs(b.growth)-Math.abs(a.growth); });
  var _auto    = _rows.filter(function(r){ return r.discovered; }).length;

  var _srcHelp = h.ihelp('Where these brands come from',
    'The brands the AI engines name beside you when they answer your tracked questions. New ones are '
    + '<b>suggested</b> at the bottom of this page, with the sentence that named them.');
%>
<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">AI Search / Competitors</div>
  </div>
  <div class="ph-right">
    <%- include('../partials/range-picker') %></div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (_showSoV && _you && _you.shareOfVoice) { %>
  <p class="claim-lede">You hold <em><%= _you.shareOfVoice %>%</em> of every brand mention.</p>
<% } else if (_showSoV && _you && _you.shareOfVoice === 0) { %>
  <p class="claim-lede">No answer named you alongside the brands we track.</p>
<% } else if (_rank) { %>
  <p class="claim-lede">You are <em>#<%= _rank %></em> of the brands the engines name.</p>
<% } else if (_rows.length) { %>
  <p class="claim-lede">Nothing has been measured against these brands yet.</p>
<% } else { %>
  <p class="claim-lede">No brand is being tracked against you yet.</p>
<% } %>
<p class="claim-sub"><%
  if (_you && _rank) { var _stT = locals.brandStanding.total; %>#<%= _rank %> of the <%= _stT %> brand<%= _stT===1?'':'s' %> named in the answers<% if (locals.brandStanding.suggested) { %> (<%= locals.brandStanding.tracked %> tracked, <%= locals.brandStanding.suggested %> suggested below)<% } %>.<%
  } else if (_rows.length) { %><%= _rows.length %> brand<%= _rows.length===1?' is':'s are' %> tracked. The columns fill in after the next AI Visibility run.<%
  } else { %>Each run suggests the brands named beside you. Track the ones that matter and they appear here.<% }
%></p>

<% if (canManage) { %>
<details class="addbox" style="margin-top:22px">
  <summary>+ Track competitor</summary>
  <form class="addform js-ajax-form" id="newcompform" method="POST" action="/api/competitors"
        data-refresh="#competitors-body" data-reset-after="#newcompform">
    <div class="fld" style="flex:1;min-width:240px"><label for="comp-new-name">Competitor brand name (exactly as AI would write it)</label><input id="comp-new-name" name="name" placeholder="e.g. VOCTOS" required></div>
    <button class="btn btn-primary btn-sm" type="submit">Track competitor</button>
    <div class="rr-meta" style="flex:1 1 100%; margin-top:6px">Each run also <b>suggests</b> brands from the answers at the bottom of this page; tracking one from there marks it <span class="chip flat">auto</span>.</div>
  </form>
</details>
<% } %>

<%

  var _sovSpan = _you ? 'b7' : 'b12';
%>
<div class="bento" id="competitors-body" style="margin-top:22px">

  <% if (_you) { %>

  <div class="vdark vd-cut b5">
    <span class="vn-fillet"></span>

    <a class="vn-cut" href="/prompt-explorer">See the answers
      <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>
    <% if (_showSoV) { %>
    <div class="vd-k">Your share of voice <%- h.ihelp('Share of voice',
      'Your mentions as a share of every brand mention in the run.') %></div>
    <div class="vd-row">
      <div class="vd-num tnum"><% if (_you.shareOfVoice != null) { %><%= _you.shareOfVoice %><small>%</small><% } else { %><span class="noval">—</span><% } %></div>
    </div>
    <div class="vd-sub"><b><%= Math.max(0, _rows.length - 1) %></b> other brand<%= Math.max(0, _rows.length - 1) === 1 ? ' is' : 's are' %> counted alongside you.</div>
    <% } else { %>
    <div class="vd-k">Your rank</div>
    <div class="vd-row">
      <div class="vd-num tnum"><% if (_rank) { %>#<%= _rank %><% } else { %><span class="noval">—</span><% } %></div>
    </div>
    <div class="vd-sub">Where you stand among the <b><%= Math.max(0, _rows.length - 1) %></b> other brand<%= Math.max(0, _rows.length - 1) === 1 ? '' : 's' %> tracked alongside you, by how often each is mentioned.</div>
    <% } %>
    <div class="ov-strip ov-2" style="margin-top:20px">
      <% if (_showSoV) { %>
      <div class="ov"><div class="ovl">Your rank</div>
        <div class="ovv tnum"><% if (_rank) { %>#<%= _rank %><% } else { %><span class="noval">—</span><% } %></div>
        <div class="rr-meta" style="margin-top:5px">of <%= locals.brandStanding.total %> brand<%= locals.brandStanding.total===1?'':'s' %> named in the answers</div></div>
      <% } else { %>
      <div class="ov"><div class="ovl">Brands tracked</div>
        <div class="ovv tnum"><%= _rows.length %></div>
        <div class="rr-meta" style="margin-top:5px"><%= _counted.length %> with a measurement</div></div>
      <% } %>
      <div class="ov"><div class="ovl">Your mention rate</div>
        <div class="ovv tnum"><% if (_you.mentionRate != null) { %><%= _you.mentionRate %>%<% } else { %><span class="noval">—</span><% } %></div>
        <div class="rr-meta" style="margin-top:5px">of the answers we checked</div></div>
    </div>

  </div>
  <% } %>

  <% var _byShare = _showSoV; if (_rows.length) { %>

  <div class="card <%= _sovSpan %>">
    <div class="card-h"><h3><%= _byShare ? 'Share of Voice' : 'Mentions' %></h3><span class="hint"><%= _byShare ? 'current' : 'latest run' %></span><span class="rr-end"><%- _srcHelp %></span></div>
    <div class="card-p" style="padding-top:12px; display:flex; flex-direction:column; gap:12px">
      <% var _val = function (r) { return (_byShare ? r.shareOfVoice : r.mentions) || 0; };
         var maxSoV = Math.max.apply(null, (rows||[]).map(_val).concat([1]));
         (rows||[]).slice().sort(function(a,b){ return _val(b)-_val(a); }).forEach(function(r){ var pct = Math.round((_val(r)/maxSoV)*100); %>

        <div><div class="row-between" style="font-size:var(--fs-sm)"><span><%= r.name %><%= r.isYou?' (you)':'' %></span><span class="num"><%= _val(r) %><%= _byShare ? '%' : '' %></span></div><div class="meter"><span style="width:<%= pct %>%;<%= r.isYou?'background:var(--teal)':'' %>"></span></div></div>
      <% }) %>
      <% if(!(rows&&rows.length)){ %><div class="rr-meta">No brands tracked yet.</div><% } %>
    </div>
  </div>
  <% } %>

  <% if (_rows.length) { %>

  <div class="card shelf-c b3 sc-violet"><div class="cl">Brands named alongside you</div><div class="cv tnum"><%= Math.max(0, _rows.length - 1) %></div></div>
  <div class="card shelf-c b3 sc-lime"><div class="cl">Found automatically</div><div class="cv tnum"><%= _auto %></div></div>
  <div class="card shelf-c b3 sc-navy"><div class="cl">Brands with a measurement</div><div class="cv tnum"><%= _counted.length %></div></div>
  <div class="card shelf-c b3 sc-sky"><div class="cl">Moved since the last run</div><div class="cv tnum"><%= _movers.length %></div></div>
  <% } %>

  <% if (_rows.length && !_counted.length) { %>

  <div class="voff b12">
    <div class="voff-h"><b>No run yet.</b> Rates fill in after the next AI Visibility run.</div>
    <div class="voff-i">
      <span class="n">Mention rate<%= _showSoV ? ', share of voice' : '' %>, mentions</span>
      <a href="/ai-visibility">Run AI Visibility</a>
    </div>
  </div>
  <% } %>

  <div class="card b8">
    <div class="card-h"><h3><%= workspace ? workspace.name : 'You' %> vs tracked competitors</h3><span class="hint">latest run</span><span class="rr-end"><%- _showSoV
      ? h.ihelp('What the two rate columns mean',
          '<b>Mention rate</b> is how often a brand was named, out of the answers we checked. '
          + '<b>Share of voice</b> is that brand\'s share of all brand mentions in the run.')
      : _srcHelp %></span></div>
    <div style="overflow-x:auto">
      <table class="tbl cmp-tbl">

        <thead><tr><th class="c-brand">Brand<% if(canManage){ %><span class="th-note" title="Their own website. Citations from this domain are marked as theirs on Citation Center.">and website</span><% } %></th><th title="Share of the answers we checked that named this brand">Mention rate</th><% if(_showSoV){ %><th title="This brand's mentions as a share of every brand mention in the run">Share of voice</th><% } %><th>Mentions</th><th title="Change in mentions since the previous run">Change</th><% if(canManage){ %><th></th><% } %></tr></thead>
        <tbody>
          <% rows.forEach(function(r){ %>
            <tr <%= r.isYou?'style="background:var(--teal-tint)"':'' %>>

              <td class="strong c-brand"><span class="c-brand-in"><span class="dot" style="background:<%= r.color %>"></span><span class="c-brand-n"><%= r.name %></span><%- r.isYou?'<span class="chip navy">You</span>':'' %><%- r.discovered?'<span class="chip flat" title="Found automatically in AI answers">auto</span>':'' %></span>
              <% if(canManage && !r.isYou){ %>

              <div class="c-site-row">
                <% var _sug = (locals.suggestions || {})[String(r._id)]; %>
                  <% if(r.domain){ %>
                    <span style="display:inline-flex;align-items:center;gap:6px">
                      <a href="<%= h.safeUrl('https://' + r.domain) %>" target="_blank" rel="noopener noreferrer nofollow"
                         title="Open <%= r.domain %>. Citations from this site are marked as theirs."><%= r.domain %></a>
                      <form method="POST" action="/api/competitors/<%= r._id %>/domain" class="inline-form">
                        <input type="hidden" name="domain" value="">
                        <button class="icon-btn" title="Clear this domain" aria-label="Clear domain for <%= r.name %>">&times;</button>
                      </form>
                    </span>
                  <% } else { %>
                    <form method="POST" action="/api/competitors/<%= r._id %>/domain" class="inline-form c-site">
                      <input type="text" name="domain" value="<%= _sug || '' %>" placeholder="their site"
                             aria-label="Website for <%= r.name %>">
                      <button class="btn btn-sm">Save</button>

                      <% if(_sug){ %><span class="chip flat" title="An engine cited this domain and its name matches this brand. Edit it or clear it. Nothing is stored until you press Save.">suggested</span><% } %>
                    </form>
                  <% } %>
              </div>

              <details class="c-alias">
                <summary><%= (r.aliases && r.aliases.length) ? 'Also: ' + r.aliases.join(', ') : '+ Other names' %></summary>
                <form method="POST" action="/api/competitors/<%= r._id %>/aliases" class="c-alias-f">
                  <textarea name="aliases" rows="2" placeholder="One name per line" aria-label="Other names for <%= r.name %>"><%= (r.aliases || []).join('\n') %></textarea>
                  <button class="btn btn-sm">Save</button>
                </form>
              </details>
              <% } %>
              </td>
              <td class="num"><%= r.mentionRate!=null ? r.mentionRate+'%' : '—' %></td>
              <% if(_showSoV){ %><td class="num"><%= r.shareOfVoice!=null ? r.shareOfVoice+'%' : '—' %></td><% } %>
              <td class="num"><%= h.int(r.mentions) %></td>
              <td><% if(r.growth==null){ %><span class="muted">—</span>
                <% } else if(r.growth>0){ %><span class="chip pos">▲ <%= r.growth %></span>
                <% } else if(r.growth<0){ %><span class="chip neg">▼ <%= Math.abs(r.growth) %></span>
                <% } else { %><span class="chip flat">no change</span><% } %></td>
              <% if(canManage){ %><td><% if(!r.isYou){ %><form method="POST" action="/api/competitors/<%= r._id %>/delete" class="inline-form js-delete-form" data-confirm="Remove competitor?" data-refresh="#competitors-body"><button class="icon-btn" title="Remove" aria-label="Remove competitor">&times;</button></form><% } %></td><% } %>
            </tr>
          <% }) %>
        </tbody>
      </table>
      <% if(!rows.length){ %><%- include('../partials/empty', { title: 'No brands tracked yet', line: 'Track a suggested brand below, or add one above.', pad: 'sm' }) %><% } %>
    </div>
  </div>

  <div class="card card-p b4">
    <div class="card-h" style="padding:0 0 12px"><h3>Biggest movers</h3><span class="hint">vs the previous run</span></div>
    <% var movers = _movers.slice(0,6); %>
    <% if(!movers.length){ %>
      <div class="rr-meta"><b style="color:var(--ink)">No movement yet</b><br>Changes show here after two runs.</div>
    <% } else { %>

      <div style="display:flex; flex-direction:column; gap:10px; font-size:var(--fs-sm)">
        <% movers.forEach(function(r){ %>
          <div class="row-between">
            <span><span class="dot" style="background:<%= r.color %>;margin-right:8px"></span><%= r.name %><%= r.isYou?' (you)':'' %></span>
            <span class="chip <%= r.growth>0?'pos':'neg' %>"><%= r.growth>0?'▲ +'+r.growth:'▼ '+r.growth %> mention<%= Math.abs(r.growth)===1?'':'s' %></span>
          </div>
        <% }) %>
      </div>
    <% } %>
  </div>

  <% var _all = (locals.ideas || []);
     var _ideas = _all.filter(function(i){ return !i.outOfMarket; });
     var _far = _all.filter(function(i){ return i.outOfMarket; }); %>
  <% if (_all.length) { %>
  <details class="card b12 kideas" open>
    <summary class="card-h kidea-sum">
      <h3>Suggested by the answers</h3>
      <span class="hint"><%= _all.length %> waiting on a decision</span>
      <span class="rr-end" style="display:flex; align-items:center; gap:10px">
        <%- h.ihelp('Where these come from',
          'Brands the engines named beside this client, with the sentence that named each one. '
          + 'Tracking one uses a competitor slot. Dismissed brands are not suggested again.') %>
        <svg class="kidea-chev" viewBox="0 0 12 12" width="13" height="13" fill="none" aria-hidden="true"><path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </span>
    </summary>
    <div class="kidea-list">
      <% _ideas.concat(_far.length ? ['__far__'] : [], _far).forEach(function(idea){
           if (idea === '__far__') { %>
    </div>
    <details class="kidea-far">
      <summary><%= _far.length %> more named only for searches without a country</summary>
      <div class="kidea-list">
      <% return; }
           var ev = (idea.evidence||[])[0]; %>
        <div class="kidea">
          <div class="kidea-top">

            <span class="kidea-name" dir="auto"><%= idea.name %></span>

            <span class="kidea-meta"><b><%= idea.mentions %></b> of <%= idea.answersRead || 0 %> answers<% if ((idea.runs||1) > 1) { %> · named in <%= idea.runs %> runs<% } %></span>
            <% if (canManage) { %>
            <span class="kidea-act">
              <form method="POST" action="/api/competitor-ideas/<%= idea._id %>/track" class="inline-form js-ajax-form" data-refresh="#competitors-body">
                <button class="btn btn-sm btn-track" type="submit">Track</button>
              </form>
              <form method="POST" action="/api/competitor-ideas/<%= idea._id %>/dismiss" class="inline-form js-delete-form"
                    data-confirm="Dismiss “<%= idea.name %>”? It won't be suggested again." data-refresh="#competitors-body">
                <button class="btn btn-sm btn-quiet" type="submit">Dismiss</button>
              </form>
            </span>
            <% } %>
          </div>
          <% if (ev && ev.quote) { %>
            <p class="kidea-q" dir="auto"><%= ev.quote %></p>
            <div class="kidea-src"><%= ev.engine || 'an engine' %><% if (ev.prompt) { %> · <span dir="auto"><%= ev.prompt %></span><% } %></div>
          <% } %>
        </div>
      <% }) %>
    </div>
    <% if (_far.length) { %></details><% } %>
  </details>
  <% } %>
</div>
