<%

  var st = !!locals.showStaff;
  var TYPE = { invented: 'Made up', stale: 'Out of date', merged: 'Mixed up', omission: 'Recommends others', accurate: 'Real point', unknown: 'Not sorted' };
  var TYPE_SAY = {
    invented: 'No source found.',
    stale: 'Outdated.',
    merged: 'Probably about a different company with a similar name.',
    omission: 'Recommends a competitor.',
    accurate: 'Backed by a source.',
    unknown: ''
  };
  var RET_SAY = { memory: 'Repeats with web search off (model memory).', search: 'Only appears with web search on.', both: '', unknown: '' };
  var STATUS = { open: 'Open', waiting: 'Waiting for a new model', fixed: 'Fixed', dismissed: 'Not a problem' };
  var path = function (u) { try { var x = new URL(u); return x.hostname.replace(/^www\./, '') + (x.pathname.length > 1 ? decodeURIComponent(x.pathname).slice(0, 50) : ''); } catch (e) { return u || ''; } };
  var OV = 'Google AI Overview';

  var cur = locals.cur || null;
  var isNow = function (e, q) { return !cur || cur.prompt(e, q); };
  var ovAll = answers.filter(function (a) { return a.engine === OV && a.text; });
  var ovAnswers = ovAll.filter(function (a) { return isNow(OV, a.prompt); });
  var ovNow = ovAnswers.length;
  ovAnswers = ovAnswers.concat(ovAll.filter(function (a) { return !isNow(OV, a.prompt); }));
  engines = engines.filter(function (e) { return e !== OV; });
  var questions = (entity.aiQuestions || []).filter(function (q) { return q.active !== false; }).map(function (q) { return q.text; });
  var qNow = questions.length;
  answers.forEach(function (a) { if (a.engine !== OV && questions.indexOf(a.prompt) < 0) questions.push(a.prompt); });
  var qGone = questions.length - qNow, ovGone = ovAnswers.length - ovNow;
  var gone = function (e, q) { return !isNow(e, q); };
  var ans = {}; answers.forEach(function (a) { ans[a.engine + '|' + a.prompt] = a; });
  var cellClaims = function (e, q) { var a = ans[e + '|' + q]; return claims.filter(function (c) { return c.engine === e && c.prompt === q && (!a || !a.at || +new Date(c.lastSeen) >= +new Date(a.at) - 2000); }); };
  var oldClaims = function (e, q) { var a = ans[e + '|' + q]; return a && a.at ? claims.filter(function (c) { return c.engine === e && c.prompt === q && +new Date(c.lastSeen) < +new Date(a.at) - 2000 && c.status !== 'dismissed'; }) : []; };
  var asked = answers.filter(function (a) { return a.text && isNow(a.engine, a.prompt); });
  var flagged = asked.filter(function (a) { return cellClaims(a.engine, a.prompt).some(function (c) { return c.status !== 'dismissed'; }); });
  var lastAt = asked.reduce(function (m, a) { return !m || a.at > m ? a.at : m; }, null);

  var cells = [];
  questions.forEach(function (q, qi) { engines.forEach(function (e, ei) { cells.push({ id: qi + '-' + ei, e: e, q: q }); }); });
  ovAnswers.forEach(function (a, i) { cells.push({ id: 'o-' + i, e: OV, q: a.prompt }); });
  var first = null;
  cells.forEach(function (c) { if (first == null && !gone(c.e, c.q) && cellClaims(c.e, c.q).some(function (x) { return x.status !== 'dismissed'; })) first = c.id; });
  if (first == null) first = '0-0';
  var plural = function (n, one, many) { return n === 1 ? one : many; };
  var rmLabel = function (n, one, many) { return 'Show ' + n + ' archived ' + plural(n, one, many); };
  var RM_TIP = 'Removed from Settings, so it is no longer checked. This is its last answer.';
  var short = function (q) { return q.replace(new RegExp('\\s*\\(' + (entity.ownedDomains && entity.ownedDomains[0] ? entity.ownedDomains[0].replace(/\./g, '\\.') : 'zzz') + '\\)', 'g'), ''); };
%>
<%- include('../partials/rep-shell') %>

<% if (!asked.length) { %>
  <p class="claim-lede"><%= claims.length ? 'No saved answers yet.' : 'No AI check yet for ' + entity.name + '.' %></p>
  <p class="claim-sub"><%= st ? 'Press Run now.' : 'Checked monthly.' %></p>
<% } else { %>
  <p class="claim-lede"><% if (flagged.length) { %><em><%= flagged.length %> of <%= asked.length %> AI answers</em> flag an issue.<% } else { %><em>All <%= asked.length %> AI answers</em> are clean.<% } %></p>
  <p class="claim-sub"><%= engines.join(', ') %><%= ovNow ? ', Google AI Overview' : '' %> · <%= qNow %> question<%= qNow === 1 ? '' : 's' %><%= lastAt ? ' · ' + h.date(lastAt) : '' %></p>
<% } %>

<div class="bento" style="margin-top:18px">
  <section class="card b12 rp-sec">
    <div class="ai-grid" style="--n:<%= engines.length %>">
      <div class="ai-gh ai-gq">Question</div>
      <% engines.forEach(function (e) { %><div class="ai-gh"><%- include('../partials/engine-mark', { engine: e, size: 'sm' }) %><span><%= e %></span></div><% }) %>
      <% questions.forEach(function (q, qi) { var rm = qi >= qNow; %>
        <div class="ai-q<%= rm ? ' ai-rm' : '' %>" <%- h.dirAttr(q) %><%= rm ? ' hidden' : '' %>><span class="ai-qn"><%= rm ? '–' : qi + 1 %></span><span><%= short(q) %><% if (rm) { %> <span class="ai-rmtag" title="<%= RM_TIP %>">Archived</span><% } %></span></div>
        <% engines.forEach(function (e, ei) { var a = ans[e + '|' + q]; var cc = cellClaims(e, q).filter(function (c) { return c.status !== 'dismissed'; }); var id = qi + '-' + ei;
           var cls = !a ? 'none' : a.error && !a.text ? 'err' : cc.length ? 'bad' : 'ok'; %>
          <button type="button" class="ai-cell <%= cls %> <%= id === first ? 'on' : '' %><%= rm ? ' ai-rm' : '' %>" data-cell="<%= id %>" <%= cls === 'none' ? 'disabled' : '' %><%= rm ? ' hidden' : '' %> aria-label="<%= e %>, <%= rm ? 'removed question' : 'question ' + (qi + 1) %>">
            <% if (cls === 'none') { %>Not asked yet<% } else if (cls === 'err') { %>Didn't answer<% } else if (cls === 'ok') { %><i>✓</i> Clean<% } else { %><b><%= cc.length %></b> issue<%= cc.length === 1 ? '' : 's' %><% } %>
          </button>
        <% }) %>
      <% }) %>
    </div>
    <% if (qGone) { %>
      <div class="ai-rmbar"><button type="button" class="ai-rmbtn js-rm-toggle" aria-pressed="false" data-show="<%= rmLabel(qGone, 'question', 'questions') %>" data-hide="Hide archived questions" title="<%= RM_TIP %>"><svg viewBox="0 0 16 16" width="14" height="14" fill="none" aria-hidden="true"><rect x="2" y="3" width="12" height="3" rx="1" stroke="currentColor" stroke-width="1.3"/><path d="M3 6v6.5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V6M6.5 9h3" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg><span><%= rmLabel(qGone, 'question', 'questions') %></span></button><span class="ai-rmnote">Removed from Settings and no longer checked. Only your team sees these.</span></div>
    <% } %>
  </section>

  <% if (ovAnswers.length) { %>
  <section class="card b12 rp-sec">
    <div class="rp-sh"><div><div class="rp-kick" style="display:flex; gap:6px; align-items:center"><%- include('../partials/engine-mark', { engine: OV, size: 'sm' }) %>On Google search results</div><h3>Google AI Overview</h3></div><div class="rp-sm"><% if (ovNow) { %><span><%= ovNow %> search<%= ovNow === 1 ? '' : 'es' %></span><% } %></div></div>
    <div class="ai-ov">
      <% ovAnswers.forEach(function (a, i) { var cc = cellClaims(OV, a.prompt).filter(function (c) { return c.status !== 'dismissed'; }); var id = 'o-' + i; var rm = i >= ovNow; %>
        <div class="ai-q<%= rm ? ' ai-rm' : '' %>" <%- h.dirAttr(a.prompt) %><%= rm ? ' hidden' : '' %>><span class="srp-ovq"><%= a.prompt %></span><% if (rm) { %> <span class="ai-rmtag" title="<%= RM_TIP %>">Archived</span><% } %></div>
        <button type="button" class="ai-cell <%= cc.length ? 'bad' : 'ok' %> <%= id === first ? 'on' : '' %><%= rm ? ' ai-rm' : '' %>" data-cell="<%= id %>"<%= rm ? ' hidden' : '' %>><% if (cc.length) { %><b><%= cc.length %></b> issue<%= cc.length === 1 ? '' : 's' %><% } else { %><i>✓</i> Clean<% } %></button>
      <% }) %>
    </div>
    <% if (!ovNow) { %><div class="rp-empty" style="padding:14px 22px">Google showed no AI Overview for the searches being checked now.</div><% } %>
    <% if (ovGone) { %>
      <div class="ai-rmbar"><button type="button" class="ai-rmbtn js-rm-toggle" aria-pressed="false" data-show="<%= rmLabel(ovGone, 'search', 'searches') %>" data-hide="Hide archived searches" title="<%= RM_TIP %>"><svg viewBox="0 0 16 16" width="14" height="14" fill="none" aria-hidden="true"><rect x="2" y="3" width="12" height="3" rx="1" stroke="currentColor" stroke-width="1.3"/><path d="M3 6v6.5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V6M6.5 9h3" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg><span><%= rmLabel(ovGone, 'search', 'searches') %></span></button><span class="ai-rmnote">Removed from Settings and no longer checked. Only your team sees these.</span></div>
    <% } %>
  </section>
  <% } %>

  <% cells.forEach(function (cl) { var e = cl.e, q = cl.q, id = cl.id; var a = ans[e + '|' + q]; var cc = cellClaims(e, q); var old = oldClaims(e, q);
     if (!a && !cc.length) return;
     var caseIds = []; cc.forEach(function (c) { if (c.case && caseIds.indexOf(String(c.case)) < 0) caseIds.push(String(c.case)); }); %>
  <section class="card b12 rp-sec ai-detail" data-detail="<%= id %>"<%= id === first ? '' : ' hidden' %>>
    <div class="rp-sh">
      <div><div class="rp-kick" style="display:flex; gap:6px; align-items:center"><%- include('../partials/engine-mark', { engine: e, size: 'sm' }) %><%= e %><%= a && a.at ? ', ' + h.date(a.at) : '' %><% if (gone(e, q)) { %> <span class="ai-rmtag" title="<%= RM_TIP %>">Archived, no longer checked</span><% } %></div><h3 <%- h.dirAttr(q) %>><%= short(q) %></h3></div>
      <div class="rp-sm"><% caseIds.forEach(function (cid) { var cs = cases.get(cid); if (!cs) return; %><a href="/reputation/cases?status=all&open=<%= cid %>#c-<%= cid %>">Case →</a><% }) %></div>
    </div>
    <% if (a && a.error && !a.text) { %><div class="rp-empty"><b><%= e %> didn't answer</b><%= st ? a.error : 'Retried on the next check.' %></div><% } %>
    <% if (!cc.length && a && a.text) { %><div class="ai-clean"><i>✓</i><div><b>No issues in this answer.</b><span>Full text below.</span></div></div><% } %>
    <% if (cc.length) { %>
    <ul class="rp-list">
      <% cc.forEach(function (c) { %>
        <li class="ai-pt tc-<%= c.type %> <%= ['fixed', 'dismissed'].indexOf(c.status) > -1 ? 'is-done' : '' %>">
          <div>
            <% if (!st) { %><span class="rp-lab tc-<%= c.type %>" style="font-size:11px"><%= TYPE[c.type] %></span><% } %>
            <p class="rp-q" <%- h.dirAttr(c.text) %>><%= c.text %></p>
            <div class="rp-why"><%= TYPE_SAY[c.type] %> <%= RET_SAY[c.retrieval] || '' %><% if (c.sourceUrl) { %> Source: <a href="<%= c.sourceUrl %>" target="_blank" rel="noopener nofollow"><%= path(c.sourceUrl) %></a>.<% } %><%= c.seenCount > 1 ? ' Seen ' + c.seenCount + '×.' : '' %></div>
          </div>
          <div class="rp-side">
            <% if (st) { %>
              <form class="rp-ctl" method="POST" action="/api/reputation/claims/<%= c._id %>">
                <select class="rp-sel tc-<%= c.type %>" name="type" data-auto aria-label="What kind of claim"><% Object.keys(TYPE).forEach(function (k) { %><option value="<%= k %>" <%= c.type === k ? 'selected' : '' %>><%= TYPE[k] %></option><% }) %></select>
                <select class="rp-sel sc-<%= c.status %>" name="status" data-auto="reload" aria-label="Status"><% Object.keys(STATUS).forEach(function (k) { %><option value="<%= k %>" <%= c.status === k ? 'selected' : '' %>><%= STATUS[k] %></option><% }) %></select>
              </form>
            <% } else { %><span class="rp-lab sc-<%= c.status %>"><%= STATUS[c.status] %></span><% } %>
          </div>
        </li>
      <% }) %>
    </ul>
    <% } %>
    <% if (old.length) { %>
      <details class="rp-det" style="padding:0 22px 6px"><summary><%= old.length %> earlier issue<%= old.length === 1 ? '' : 's' %>, no longer repeated</summary>
        <ul class="ai-old"><% old.forEach(function (c) { %><li <%- h.dirAttr(c.text) %>><%= c.text %> <span class="rp-sm" style="display:inline">(last seen <%= h.date(c.lastSeen) %>)</span></li><% }) %></ul>
      </details>
    <% } %>
    <% if (a && a.text) { %>
      <details class="rp-det" style="padding:0 22px 16px"><summary>Full answer</summary><div class="rp-box" <%- h.dirAttr(a.text) %>><%= a.text %></div>
        <% if ((a.citations || []).length) { %><div class="rep-feat" style="margin-top:8px"><% a.citations.slice(0, 10).forEach(function (u) { %><a href="<%= u %>" target="_blank" rel="noopener nofollow"><span><%= path(u) %></span></a><% }) %></div><% } %>
      </details>
    <% } %>
  </section>
  <% }) %>

  <section class="card b12 rp-sec">
    <div class="rp-note" style="border-top:0">AI engines don't remove claims on request. Fix or answer the pages they cite; memory-based points change with new model versions. Individuals can ask OpenAI to remove personal data (see Removals).<% if (st) { %> <a href="/reputation/settings#e-<%= entity._id %>">Edit questions</a><% } %></div>
  </section>
</div>
<style>
  .ai-grid{display:grid; grid-template-columns:minmax(220px, 1.4fr) repeat(var(--n), minmax(130px, 1fr)); overflow-x:auto}
  .ai-gh{display:flex; gap:8px; align-items:center; padding:14px 16px; font-size:13px; font-weight:700; color:var(--ink); border-bottom:1px solid var(--line-2); background:var(--surface-2)}
  .ai-gq{font-size:11px; letter-spacing:.07em; text-transform:uppercase; color:var(--muted); font-weight:600}
  .ai-q{display:flex; gap:10px; align-items:flex-start; padding:12px 16px; font-size:13px; line-height:1.45; color:var(--ink-2); border-bottom:1px solid var(--line-2)}
  .ai-qn{flex:none; width:20px; height:20px; border-radius:6px; background:var(--surface-2); color:var(--muted); font-size:11px; font-weight:700; display:inline-flex; align-items:center; justify-content:center}
  .ai-cell{margin:6px; padding:10px; border-radius:12px; border:1px solid var(--line-2); background:var(--surface); font:inherit; font-size:12.5px; color:var(--ink-2); cursor:pointer; text-align:left; display:flex; align-items:center; gap:6px; transition:border-color .15s, box-shadow .15s}
  .ai-cell:hover:not([disabled]){border-color:var(--muted-2)}
  .ai-cell.ok{background:color-mix(in srgb, var(--pos) 7%, var(--surface))} .ai-cell.ok i{color:var(--pos); font-style:normal; font-weight:700}
  .ai-cell.bad{background:color-mix(in srgb, var(--neg) 8%, var(--surface)); color:var(--ink)} .ai-cell.bad b{color:var(--neg); font-size:15px}
  .ai-cell.err{background:var(--warn-tint); color:var(--warn-ink)}
  .ai-cell.none{background:transparent; border-style:dashed; color:var(--muted); cursor:default}
  .ai-cell.on{border-color:var(--accent-strong); box-shadow:0 0 0 2px color-mix(in srgb, var(--accent-strong) 25%, transparent)}
  .ai-detail[hidden]{display:none !important}
  .ai-rmbar{display:flex; align-items:center; gap:12px; flex-wrap:wrap; padding:12px 16px; border-top:1px solid var(--line-2)}
  .ai-rmbtn{display:inline-flex; align-items:center; gap:7px; padding:7px 12px; border:1px dashed var(--line); border-radius:99px; background:transparent; color:var(--ink-2); font:inherit; font-size:12.5px; font-weight:600; cursor:pointer}
  .ai-rmbtn:hover{border-color:var(--muted-2); color:var(--ink)} .ai-rmbtn[aria-pressed="true"]{border-style:solid; background:var(--surface-2)}
  .ai-rmnote{font-size:12px; color:var(--muted)}
  .ai-rmtag{display:inline-block; margin-left:6px; padding:1px 7px; border-radius:99px; background:var(--surface-2); color:var(--muted); font-size:10.5px; font-weight:600; letter-spacing:.02em; vertical-align:1px; text-transform:none}
  .ai-q.ai-rm{color:var(--muted)} .ai-cell.ai-rm{opacity:.75}
  .ai-clean{display:flex; gap:12px; align-items:center; padding:18px 22px} .ai-clean i{flex:none; width:30px; height:30px; border-radius:50%; background:var(--pos-tint); color:var(--pos); font-style:normal; font-weight:700; display:flex; align-items:center; justify-content:center}
  .ai-clean b{display:block; color:var(--ink); font-size:14px} .ai-clean span{font-size:12.5px; color:var(--muted)}
  .ai-ov{display:grid; grid-template-columns:minmax(0, 1fr) 180px} .srp-ovq{font-family:ui-monospace, SFMono-Regular, Menlo, monospace; font-size:12.5px; color:var(--ink)}
  .ai-pt{display:grid; grid-template-columns:minmax(0, 1fr) auto; gap:8px 18px; align-items:start; padding:14px 22px; border-top:1px solid var(--line-2)} .ai-pt:first-child{border-top:0}
  .ai-pt.is-done{opacity:.6} .ai-pt .rp-q{margin-top:6px}
  .ai-old{margin:8px 0 0; padding-left:18px; font-size:13px; color:var(--muted); display:flex; flex-direction:column; gap:4px}
  @media (max-width:700px){ .ai-grid{grid-template-columns:minmax(180px, 1fr) repeat(var(--n), 120px)} .ai-pt{grid-template-columns:1fr; padding:14px 16px} }
</style>
<script>
(function () {

  function setArchived(open) {
    window.__repArchivedOpen = open;
    document.querySelectorAll('.ai-rm').forEach(function (el) { el.hidden = !open; });
    document.querySelectorAll('.js-rm-toggle').forEach(function (x) { var l = x.querySelector('span'); if (l) l.textContent = open ? x.dataset.hide : x.dataset.show; x.setAttribute('aria-pressed', open ? 'true' : 'false'); });

    if (!open) { var on = document.querySelector('.ai-cell.on.ai-rm'); if (on) { on.classList.remove('on'); var d = document.querySelector('.ai-detail[data-detail="' + on.dataset.cell + '"]'); if (d) d.hidden = true; } }
  }
  document.querySelectorAll('.js-rm-toggle').forEach(function (t) {
    t.addEventListener('click', function () { setArchived(!window.__repArchivedOpen); });
  });
  if (window.__repArchivedOpen) setArchived(true);
  document.querySelectorAll('.ai-cell[data-cell]').forEach(function (b) {
    b.addEventListener('click', function () {
      var id = b.dataset.cell;
      document.querySelectorAll('.ai-cell').forEach(function (x) { x.classList.toggle('on', x === b); });
      document.querySelectorAll('.ai-detail').forEach(function (d) { d.hidden = d.dataset.detail !== id; });
      var d = document.querySelector('.ai-detail[data-detail="' + id + '"]');
      if (d && d.getBoundingClientRect().top > window.innerHeight - 120) d.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  });
})();
</script>
<%- include('../partials/rep-foot') %>
