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

  var _ps      = prompts || [];
  var _seen    = _ps.filter(function(p){ return p.appeared; }).length;
  var _ranked  = _ps.filter(function(p){ return p.ourRank; });
  var _best    = _ranked.length ? Math.min.apply(null, _ranked.map(function(p){ return p.ourRank; })) : null;
  var _firsts  = _ranked.filter(function(p){ return p.ourRank === 1; }).length;

  var _asked   = _ps.filter(function(p){ return (p.perEngine || []).length; }).length;
  var _beaten  = _ps.filter(function(p){ return p.beatBy && p.beatBy.length; }).length;
  var _engines = (typeof engines !== 'undefined' && engines) ? engines : 0;
%>
<div class="pg-head" style="margin-bottom:0">
  <div>
    <div class="eyebrow">AI Search / Prompt Explorer</div>
  </div>
  <div class="ph-right">

    <%- include('../partials/range-picker') %></div>
</div>

<h1 class="claim"><%= title %></h1>
<% if (_ps.length && _asked && _seen) { %>
  <p class="claim-lede">You are named in <em><%= _seen %></em> of the <%= _ps.length %> question<%= _ps.length===1?'':'s' %> we ask.</p>
<% } else if (_ps.length && _asked) { %>
  <p class="claim-lede">No answer has named you in the questions we ask.</p>
<% } else if (_ps.length) { %>
  <p class="claim-lede">Your prompts have not been put to the engines yet.</p>
<% } else { %>
  <p class="claim-lede">No question is being tracked for you yet.</p>
<% } %>
<p class="claim-sub"><%
  if (_asked && _best) { %>Your best position is <b>#<%= _best %></b>, across <%= _engines || 'the connected' %> engine<%= _engines===1?'':'s' %><% if (_firsts) { %>, and <b><%= _firsts %></b> answer<%= _firsts===1?'':'s' %> named you first<% } %>.<%
  } else if (_asked) { %>No answer ranked you yet.<%
  } else if (_ps.length) { %>Results appear here after the first run.<%
  } else { %>Add the questions your buyers ask, and every connected engine answers them on each run.<% }
%></p>

<% if (canManage) { %>

<% var _addOpen = !!(locals.query && locals.query.new); %>
<div class="card card-p" id="newprompt" style="margin-top:22px"<%= _addOpen ? '' : ' hidden' %>>
  <div class="card-h" style="padding:0 0 12px"><h3>Add prompts</h3><span class="rr-end"><a class="more js-panel-cancel" data-panel="#newprompt" href="/prompt-explorer">Cancel</a></span></div>

  <form class="addform js-ajax-form" id="addpromptform" method="POST" action="/api/prompts"
        data-refresh="#tracked-prompts-card" data-hide-after="#newprompt" data-clear-after="#prompt-new-text">
    <div class="fld" style="flex:1 1 100%"><label for="prompt-new-text">Prompts to monitor (one per line)</label><textarea id="prompt-new-text" name="prompts" rows="4" placeholder="Best GEO agency in Dubai&#10;best geo agency in Egypt&#10;who is voctos" required maxlength="6000" style="width:100%; resize:vertical; font:inherit; padding:10px 12px; border-radius:10px; border:1px solid var(--line); background:var(--surface); color:var(--ink)"></textarea></div>
    <button class="btn btn-primary btn-sm" type="submit">Add prompts</button>
    <div class="rr-meta" style="flex:1 1 100%; margin-top:6px">One prompt per line. New prompts are asked on the next run.</div>
  </form>
</div>

<% if (!engines) { %><div class="rr-meta" style="margin:-6px 0 14px"><% if (locals.showStaff) { %>Set your model API keys in <b>.env</b> (OpenAI / Anthropic / Perplexity / Gemini), then hit <b>Run all now</b> to fetch real answers.<% } else { %>No AI engine is connected yet. Your VOCTOS team is setting this up.<% } %></div><% } %>
<% } %>

<%

  var ideas = (typeof ideas !== 'undefined' && ideas) ? ideas : [];
  var FROM = {
    answers:    { chip: 'teal', label: 'raised in the answers' },
    gap:        { chip: 'neg',  label: 'question you are absent from' },
    competitor: { chip: 'warn', label: 'names a competitor' }
  };
%>

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

  <% if (_ps.length) { %>

  <div class="vdark vd-cut vd-cut-sm b8">
    <span class="vn-fillet"></span>
    <% if (canManage) { %>

      <a class="vn-cut js-panel-open" data-panel="#newprompt" href="/prompt-explorer?new=1#newprompt">Add prompt
        <svg viewBox="0 0 12 12" fill="none" width="13" height="13" aria-hidden="true"><path d="M6 2.4v7.2M2.4 6h7.2" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
      </a>
    <% } else { %>

      <a class="vn-cut" href="/citation-center">Sources cited
        <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">You appeared in</div>
    <div class="vd-row">
      <div class="vd-num tnum"><% if (_asked) { %><%= _seen %><small>/<%= _ps.length %></small><% } else { %><span class="noval">—</span><% } %></div>
    </div>
    <div class="vd-sub">
      <% if (_asked) { %>
        Of the <%= _ps.length %> question<%= _ps.length===1?'':'s' %> we track, <b><%= _seen %></b> produced an answer that named you.
        <% if (_asked < _ps.length) { %> <b><%= _ps.length - _asked %></b> <%= _ps.length - _asked === 1 ? 'is' : 'are' %> waiting for the next run.<% } %>
      <% } else { %>
        Results appear after the first run.
      <% } %>
    </div>

  </div>

  <div class="card card-p rr b4">
    <div class="row-between"><span class="rr-lbl">Best rank</span><span class="rr-end"><%- h.ihelp('Best rank',
      'The highest position you held in any answer, across every connected engine.') %></span></div>
    <div class="score-num tnum" style="margin-top:12px"><% if (_best) { %>#<%= _best %><% } else { %><span class="noval">—</span><% } %></div>
    <div class="rr-meta" style="margin-top:10px">
      <% if (_best) { %>
        <%= _ranked.length %> prompt<%= _ranked.length===1?'':'s' %> ranked you<% if (_firsts) { %>, and you were named first in <b style="color:var(--ink)"><%= _firsts %></b><% } %>.
      <% } else if (_asked) { %>
        No answer ranked you yet.
      <% } else { %>
        Nothing has been asked yet.
      <% } %>
    </div>

    <% if (canManage) { %>
      <div class="rr-actions">

        <form class="inline-form" method="POST" action="/api/ai/run" style="flex:1" id="airunform">

          <% var _el = locals.engineList || []; if (_el.length > 1) { %>
          <fieldset class="eng-pick" id="engpick">
            <legend>Engines to ask</legend>
            <% _el.forEach(function (e) { %><label class="eng-opt"><input type="checkbox" name="engines" value="<%= e.code %>" checked> <%= e.name %></label><% }) %>
          </fieldset>
          <% } %>
          <button class="btn btn-primary btn-sm" type="submit" style="width:100%" id="airunbtn">
            <svg viewBox="0 0 12 12" fill="none" width="12" height="12" aria-hidden="true" style="margin-right:6px"><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>
            <span id="airunlabel">Run all now</span>
          </button>
          <div class="eng-note" id="engnote" hidden>Only the ticked engines are asked. The visibility score updates on the next run with all engines.</div>
        </form>
      </div>
    <% } %>
  </div>

  <% var _waiting = Math.max(0, _ps.length - _asked); %>
  <div class="card shelf-c b3 sc-violet"><div class="cl">Prompts tracked</div><div class="cv tnum"><%= _asked %></div><div class="rr-meta" style="margin-top:4px">asked on the engines at least once</div></div>
  <div class="card shelf-c b3 sc-lime"><div class="cl">Waiting for a run</div><div class="cv tnum"><%= _waiting %></div><div class="rr-meta" style="margin-top:4px"><%= _waiting ? (canManage ? 'added, not asked yet. Run all now to track them' : 'added, will be asked on the next run') : 'every prompt has been asked' %></div></div>
  <div class="card shelf-c b3 sc-navy"><div class="cl">Engines asked<%- h.ihelp('Engines asked',
    'Every tracked prompt is put to: <b>' + h.esc((locals.engineNames || []).join(', ')) + '</b>.'
    + ((locals.engineOff || []).length ? '<br><br>Not connected: ' + h.esc(locals.engineOff.join(', ')) + '.' : '')) %></div><div class="cv tnum"><%= _engines %></div></div>

  <div class="card shelf-c b3 sc-sky"><div class="cl">Rival ahead on some engine<%- h.ihelp('Rival ahead on some engine',
    'Tracked prompts where at least one engine named a competitor before you, or named one and not you.') %></div><div class="cv tnum"><%= _beaten %></div></div>
  <% } %>

  <% if (canManage) { %>

  <div class="card b12" id="suggested-prompts-card">
    <div class="card-h">
      <h3>Suggested prompts</h3>
      <span class="hint">read out of the answers the engines already gave<% if(typeof lastIdeaRun!=='undefined' && lastIdeaRun){ %> · <%= h.timeAgo(lastIdeaRun) %><% } %></span>
      <form class="inline-form js-ajax-form" method="POST" action="/api/prompt-ideas/run" style="margin-left:auto" data-refresh="#suggested-prompts-card">
        <button class="btn btn-sm" type="submit">Suggest now</button>
      </form>
    </div>

    <% if (!ideas.length) { %>
      <div class="card-p rr-meta" style="text-align:center; padding:26px">
        No suggestions right now. New ones are added on the 1st of each month.
      </div>
    <% } else { %>

      <details class="fold">
        <summary class="fold-sum">
          <svg class="chev" width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M6 3.5L10.5 8L6 12.5" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/></svg>
          <span><b><%= ideas.length %></b> suggestion<%= ideas.length === 1 ? '' : 's' %> waiting</span>
          <span class="fold-hint">review and add the ones worth tracking</span>
        </summary>
      <div class="card-p rr-meta" style="padding-bottom:2px">
        <span class="ihelp-w" tabindex="0" role="button" aria-label="Where these come from">
          <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> Where these come from
          <span class="ihelp-pop" role="tooltip"><b>Where these come from</b>Each suggestion comes from a sentence an engine wrote, quoted underneath. Add the ones worth tracking.</span>
        </span>
      </div>
      <div class="card-p" style="display:flex; flex-direction:column; gap:10px; padding-top:10px">
        <% ideas.forEach(function(idea){ var meta = FROM[idea.from] || FROM.answers; var ev = (idea.evidence||[])[0] || {}; %>
          <div class="idea">
            <div class="idea-main">
              <div class="idea-q"><%= idea.text %></div>
              <div class="rr-meta" style="margin-top:3px">
                <span class="chip <%= meta.chip %>"><%= meta.label %></span>
                <% if(idea.why){ %> <%= idea.why %><% } %>
              </div>
              <% if(ev.quote){ %>
                <div class="idea-ev">
                  “<%- h.answer(ev.quote) %>”
                  <div class="rr-meta" style="margin-top:4px">
                    <%= ev.engine || 'an engine' %><% if(ev.prompt){ %>, answering “<%= h.askedQ(ev.prompt) %>”<% } %>
                  </div>
                </div>
              <% } %>
              <div class="rr-meta" style="margin-top:6px">
                suggested by <%= idea.suggestedBy || '—' %><% if(idea.basedOn){ %> after reading <%= idea.basedOn %> stored answer<%= idea.basedOn===1?'':'s' %><% } %>
              </div>
            </div>
            <div class="idea-act">

              <form class="inline-form js-ajax-form" method="POST" action="/api/prompt-ideas/<%= idea._id %>/add" data-refresh="#suggested-prompts-card #tracked-prompts-card">
                <button class="btn btn-primary btn-sm" type="submit">Track it</button>
              </form>
              <form class="inline-form js-ajax-form" method="POST" action="/api/prompt-ideas/<%= idea._id %>/dismiss" data-refresh="#suggested-prompts-card">
                <button class="btn btn-sm" type="submit">Dismiss</button>
              </form>
            </div>
          </div>
        <% }) %>
      </div>
      </details>
    <% } %>
  </div>
  <% } %>

  <div class="card b12" id="tracked-prompts-card">

    <div class="card-h"><h3>Tracked prompts</h3><span class="hint"><%= prompts.length %> shown · <%= _engines %> engine<%= _engines===1?'':'s' %></span><% if (canManage && !_ps.length) { %><span class="rr-end"><a class="more js-panel-open" data-panel="#newprompt" href="/prompt-explorer?new=1#newprompt">+ Add prompt</a></span><% } %><span class="rr-end psel-end"><% if (canManage && prompts.length) { %><button type="button" class="psel-start" title="Select prompts to re-run or delete" aria-label="Select prompts"><svg width="15" height="15" viewBox="0 0 16 16" fill="none" aria-hidden="true"><rect x="1.75" y="2.25" width="4.5" height="4.5" rx="1.2" stroke="currentColor" stroke-width="1.4"/><path d="M2.9 4.5l.9.9 1.5-1.7" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/><rect x="1.75" y="9.25" width="4.5" height="4.5" rx="1.2" stroke="currentColor" stroke-width="1.4"/><path d="M8.5 4.5h6M8.5 11.5h6" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg></button><% } %><%- h.ihelp('What a prompt run is',
      'Each tracked prompt is asked on every connected engine and the answer is saved word for word. '
      + '<b>Appeared</b> means your brand was named. <b>Best rank</b> is your highest position across the engines. '
      + 'An engine that failed shows <span class="chip warn">⚠</span>.') %></span></div>
    <% if (canManage) { %>

    <div class="psel-bar" role="toolbar" aria-label="Selected prompts" hidden>
      <button type="button" class="psel-x" data-psel="cancel" aria-label="Leave selection (Esc)" title="Leave selection (Esc)"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg></button>
      <span class="psel-count"><b class="psel-n">0</b> selected</span>
      <button type="button" class="psel-a ghost" data-psel="all">Select all</button>
      <span class="psel-hint">Shift-click picks a range</span>
      <span class="psel-push"></span>
      <button type="button" class="psel-a run" data-psel="run" title="Ask the engines ticked above these prompts again"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M2.5 8a5.5 5.5 0 105.5-5.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><path d="M2.5 3v3h3" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>Re-run</button>
      <button type="button" class="psel-a del" data-psel="delete"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8.5h5.8l.6-8.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>Delete</button>
    </div>
    <% } %>

    <div class="pe-legend">
      <span><span class="chip pos">#1</span> named, at that position</span>
      <span><span class="chip pos">✓</span> named, no position</span>
      <span><span class="chip neg">✗</span> not named</span>
      <span><span class="chip flat">–</span> no AI Overview shown</span>
      <span><span class="chip warn">⚠</span> engine failed</span>
    </div>

    <div class="tbl-frozen">
      <% if (!prompts.length) { %>

      <div class="card-p rr-meta" style="text-align:center; padding:34px">
        No prompt is being tracked yet<%= canManage ? '. Add one above, then Run all now.' : '. Your VOCTOS team chooses the questions we monitor for you.' %>
      </div>
      <% } else { %>
      <table class="tbl">

        <thead><tr><th>Per engine</th><th>Appeared</th><th>Best rank</th><th>Beat by</th><th>Sources</th><th>Confidence</th><th>Updated</th><th></th></tr></thead>
        <tbody>
          <% var _openId = replay ? String(replay._id) : ''; %>
          <% prompts.forEach(function(p, _pi){ var _isOpen = _openId && String(p._id) === _openId; %>

            <% var _alt = (_pi % 2 === 1) ? ' prow-alt' : ''; %>
            <tr class="prow-q<%= _alt %><%= _isOpen ? ' prow-on' : '' %>" id="p<%= p._id %>" data-prompt-id="<%= p._id %>">

              <td colspan="3">

            <div class="prow-qt"><% if (canManage) { %><button type="button" class="psel" data-pick="<%= p._id %>" aria-pressed="false" aria-label="Select this prompt" title="Select (Shift-click for a range)"><svg width="10" height="10" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M3.5 8.5l3 3 6-7" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></svg></button><% } %><% if (p.replay && p.replay.length) { %><a class="prow-link js-replay-toggle" data-prompt-id="<%= p._id %>" href="/prompt-explorer?p=<%= _isOpen ? '' : p._id %>#p<%= p._id %>" aria-expanded="<%= _isOpen ? 'true' : 'false' %>"><svg class="chev chev-inline<%= _isOpen ? ' chev-open' : '' %>" width="11" height="11" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M6 3.5L10.5 8L6 12.5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg><%= p.text %></a><% } else { %><%= p.text %><% } %></div>
              </td>

              <% var bb = p.beatBy || []; %>
              <td class="muted beatby-cell" rowspan="2">
                <% if (!bb.length) { %>—<% } else if (bb.length <= 2) { %><%= bb.join(', ') %><% } else { %>
                  <%= bb.slice(0, 2).join(', ') %>
                  <span class="ihelp-w" tabindex="0" role="button" aria-label="Show all <%= bb.length %> names that beat you">
                    <span class="chip flat" style="padding:1px 6px">+<%= bb.length - 2 %></span>
                    <span class="ihelp-pop" role="tooltip"><b>Beat by</b><%= bb.join(', ') %></span>
                  </span>
                <% } %>
              </td>
              <td colspan="4"></td>
            </tr>
            <tr class="prow-m<%= _alt %><%= _isOpen ? ' prow-on' : '' %>" data-prompt-id="<%= p._id %>">
              <td style="white-space:nowrap">
                <% var pe = p.perEngine || []; %>
                <% if(!pe.length){ %><span class="muted">—</span><% } %>

                <% pe.forEach(function(x){
                     var none = (x.shown === false);
                     var cls  = x.error ? 'warn' : (none ? 'flat' : (x.appeared ? 'pos' : 'neg'));
                     var mark = x.error ? '⚠' : (none ? '–' : (x.appeared ? (x.rank ? ('#' + x.rank) : '✓') : '✗'));
                     var tip  = x.error ? (x.engine + ' failed: ' + x.error)
                              : none ? (x.engine + ' (Google showed no AI Overview for this query, so no brand was mentioned)')

                              : (x.engine + (x.appeared
                                  ? (' (mentioned'
                                     + (x.rank ? ' at #' + x.rank
                                        : (x.rankKnown === false ? ', position could not be read'
                                           : (x.rankKnown === true ? ', but not as one of the listed options' : '')))
                                     + (x.sentiment?' · '+x.sentiment:'') + ')')
                                  : ' (not mentioned)')); %>
                  <span class="chip <%= cls %>" title="<%= tip %>" style="margin-right:4px; display:inline-flex; align-items:center; gap:4px"><%- include('../partials/engine-mark', { engine: x.engine, size: 'sm', bare: true }) %><%= x.engine %> <%= mark %></span>
                <% }) %>
              </td>
              <td><span class="chip <%= p.appeared?'pos':'neg' %>"><%= p.appeared?'Yes':'No' %></span></td>
              <td><span class="rank <%= p.ourRank===1?'win':(!p.ourRank?'lose':'') %>"><%= p.ourRank?'#'+p.ourRank:'—' %></span></td>

              <td class="num"><%= p.sources %></td>
              <td><% if(p.confidence){ %><span class="num" style="color:<%= p.confidence>=85?'var(--pos)':'var(--warn-ink)' %>"><%= p.confidence %>%</span><% } else { %><span class="muted">—</span><% } %></td>
              <td class="muted"><%= h.timeAgo(p.updatedAt) %></td>

              <td style="white-space:nowrap"><div class="row-acts">
                <% if(p.replay&&p.replay.length){ %><a class="icon-btn act js-replay-toggle<%= _isOpen ? ' on' : '' %>" data-prompt-id="<%= p._id %>" href="/prompt-explorer?p=<%= _isOpen ? '' : p._id %>#p<%= p._id %>" title="<%= _isOpen ? 'Hide these answers' : 'Show how each engine answered this, over time' %>" aria-label="<%= _isOpen ? 'Hide answers' : 'Show answers' %>" aria-expanded="<%= _isOpen ? 'true' : 'false' %>"><svg class="chev<%= _isOpen ? ' chev-open' : '' %>" width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M6 3.5L10.5 8L6 12.5" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg></a><% } else { %><span class="rr-meta" title="No run has stored an answer for this prompt yet">&mdash;</span><% } %>

                <% if(canManage){ %> <form class="inline-form prow-run js-run-form" method="POST" action="/api/prompts/<%= p._id %>/run"><button class="icon-btn" type="submit" title="Ask every engine this one prompt again (about half a minute). Does not change the visibility score." aria-label="Re-run this prompt"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M2.5 8a5.5 5.5 0 105.5-5.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/><path d="M2.5 3v3h3" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg></button></form><% } %>
                <% if(canManage){ %> <form class="inline-form js-delete-form" method="POST" action="/api/prompts/<%= p._id %>/delete" data-confirm="Delete prompt?" data-refresh="#tracked-prompts-card"><button class="icon-btn" title="Delete" aria-label="Delete prompt">&times;</button></form><% } %>
              </div></td>
            </tr>

            <% if (_isOpen && replay) { %>
            <tr class="prow-ans" data-prompt-id="<%= p._id %>">
              <td colspan="8">
                <div class="prow-inner">
                  <%- include('../partials/prompt-replay', { replay: replay, h: h, engineLogo: (typeof engineLogo !== 'undefined' ? engineLogo : null) }) %>
                </div>
              </td>
            </tr>
            <% } %>
          <% }) %>
        </tbody>
      </table>
      <% } %>
    </div>
  </div>

</div>

<script src="/js/promptExplorer.js" defer></script>
