<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <meta name="theme-color" content="#0EA5E9" />
  <title>Find on this case · takedowns</title>
  <link rel="stylesheet" href="/public/css/glass.css?v=2-light" />
  <style>
    .search-row { display: flex; align-items: center; gap: .5rem; padding: .75rem 1rem; border-bottom: 1px solid var(--line); background: var(--bg-2, #11141c); }
    .search-row input { flex: 1; padding: .5rem .75rem; background: var(--bg-3); color: inherit; border: 1px solid var(--line); border-radius: 4px; }
    .result-row { display: flex; align-items: flex-start; gap: 1rem; padding: .75rem 1rem; border-bottom: 1px solid var(--line); }
    .result-row .pill { font-size: .7rem; padding: .1rem .5rem; border-radius: 999px; border: 1px solid var(--line); margin-left: .35rem; }
    .result-row .pill.video { background: rgba(150, 90, 220, .12); border-color: rgba(150, 90, 220, .5); }
    .result-row .pill.image { background: rgba(220, 100, 150, .12); border-color: rgba(220, 100, 150, .5); }
    .result-row .pill.other { background: rgba(120, 130, 200, .12); border-color: rgba(120, 130, 200, .5); }
    .result-row .pill.name  { background: rgba(120, 160, 200, .12); border-color: rgba(120, 160, 200, .5); }
    .result-row .pill.unknown { background: rgba(160, 160, 160, .12); border-color: rgba(160, 160, 160, .5); }
    .result-row .pill.ok    { background: rgba(80, 200, 120, .12); border-color: rgba(80, 200, 120, .5); }
    .result-row mark { background: rgba(255, 220, 60, .35); color: inherit; padding: 0 .15em; border-radius: 2px; }
    .result-row .meta { font-size: .8rem; opacity: .7; margin-top: .15rem; }
    .result-row .actions { flex: 0; }
    .result-row .actions a { display: inline-block; margin-left: .35rem; padding: .25rem .55rem; font-size: .8rem; border: 1px solid var(--line); border-radius: 4px; text-decoration: none; color: inherit; }
    .result-row .actions a:hover { background: var(--bg-3); }
  </style>
</head>
<body>
  <div class="search-row">
    <a id="back" href="#" class="pill">← back to case</a>
    <input type="search" id="q" placeholder="Search across all findings on this case…" autofocus />
    <span class="muted" id="count" style="opacity:.65"></span>
  </div>
  <div id="results"></div>

  <script>
    const params = new URLSearchParams(location.search);
    const CASE_ID = parseInt(params.get('case_id') || '0', 10);
    const csrf = (() => { const m = document.cookie.match(/(?:^|;\s*)ncsrf=([^;]+)/); return m ? m[1] : ''; })();

    const el = (id) => document.getElementById(id);
    el('back').href = '/cases/?id=' + CASE_ID;
    el('q').value = params.get('q') || '';
    document.title = `Find: ${el('q').value || '…'} · case #${CASE_ID}`;

    const pillForCategory = (c) => {
      if (!c) return null;
      const map = {
        unauthorized_video: ['video', 'unauthorized video'],
        unauthorized_image: ['image', 'unauthorized image'],
        unauthorized_other: ['other', 'unauthorized (other)'],
        name_only:          ['name',  'name only'],
        not_ncii:           ['ok',    'not NCII'],
        unknown:            ['unknown', 'unknown'],
      };
      return map[c] ? `<span class="pill ${map[c][0]}">${map[c][1]}</span>` : '';
    };

    function highlight(text, q) {
      if (!q || !text) return text || '';
      const idx = text.toLowerCase().indexOf(q.toLowerCase());
      if (idx < 0) return text.slice(0, 200);
      const start = Math.max(0, idx - 60);
      const end   = Math.min(text.length, idx + q.length + 80);
      return (start > 0 ? '…' : '') + text.slice(start, end).replace(new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi'), '<mark>$1</mark>') + (end < text.length ? '…' : '');
    }

    async function run() {
      const q = el('q').value.trim();
      if (q.length < 2) { el('results').innerHTML = '<div style="padding:1rem;opacity:.65">Type at least 2 characters to search.</div>'; return; }
      const r = await fetch('/findings/search?case_id=' + CASE_ID + '&q=' + encodeURIComponent(q), {
        credentials: 'same-origin',
        headers: { 'x-csrf-token': csrf },
      });
      if (r.status === 403) {
        const d = await r.json();
        el('results').innerHTML = `<div style="padding:1rem"><h2>Plan required</h2><p>${esc(d.message || '')}</p><a class="button" href="/billing/">See plans →</a></div>`;
        return;
      }
      const data = await r.json();
      el('count').textContent = `${data.count} hit${data.count === 1 ? '' : 's'}`;
      if (!data.results.length) {
        el('results').innerHTML = '<div style="padding:1rem;opacity:.65">No matches in title, snippet, URL, or classification evidence.</div>';
        return;
      }
      el('results').innerHTML = data.results.map(row => {
        const catPill = pillForCategory(row.category);
        const conf = row.confidence != null ? Math.round(row.confidence * 100) + '%' : '';
        const viewer = `/findings/${row.finding_id}/view?case_id=${row.case_id}`;
        const mhtml  = `/findings/${row.finding_id}/save.mhtml`;
        return `
          <div class="result-row">
            <div style="flex:1; min-width:0">
              <div><a href="${row.url}" target="_blank" rel="noopener">${row.url}</a></div>
              <div class="meta">
                T${row.tier} · status: ${row.status}
                ${catPill}${conf ? ` (${conf})` : ''}
              </div>
              ${row.page_title   ? `<div class="meta">title: ${highlight(row.page_title, q)}</div>` : ''}
              ${row.page_snippet ? `<div class="meta">snippet: ${highlight(row.page_snippet, q)}</div>` : ''}
              ${row.evidence     ? `<div class="meta">evidence: ${highlight(row.evidence, q)}</div>` : ''}
              ${row.summary      ? `<div class="meta">summary: ${highlight(row.summary, q)}</div>` : ''}
            </div>
            <div class="actions">
              <a href="${viewer}" target="_blank" rel="noopener">Open viewer →</a>
              <a href="${mhtml}"  target="_blank" rel="noopener">Save .mhtml</a>
            </div>
          </div>`;
      }).join('');
    }

    el('q').onkeydown = (e) => {
      if (e.key === 'Enter') {
        const u = new URL(location.href);
        u.searchParams.set('q', el('q').value);
        history.replaceState(null, '', u.toString());
        run();
      }
    };
    run();

    function esc(s){return String(s==null?'':s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));}


  </script>
</body>
</html>
