<!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>Scan — takedowns</title>
  <link rel="stylesheet" href="/public/css/glass.css?v=2-light" />
</head>
<body>
  <div class="app">
    <aside>
      <a href="/" class="brand" aria-label="takedowns home"><img src="/public/og/logo-mark.png" alt="" width="28" height="28" /><span class="brand-wordmark">takedowns<small>by vesamuni</small></span></a>
      <nav>
        <a href="/dashboard/">Dashboard</a>
        <a href="/cases/">Cases</a>
        <a href="/scan/" class="active">Scan</a>
        <a href="/takedown/">Takedowns</a>
        <a href="/billing/">Billing</a>
        <a href="/admin/" data-admin-only class="hidden">Admin</a>
        <a href="#" id="logout">Sign out</a>
      </nav>
    </aside>
    <main>
      <header class="topbar">
        <h1>Run a scan</h1>
        <div class="user-pill">
          <span id="siteHealthDot" class="site-health-dot unknown" title="checking…"></span>
        </div>
      </header>
      <div id="flash"></div>

      <section class="panel">
        <h2>1. Pick a case</h2>
        <div class="row">
          <select id="caseSel" class="field"><option value="">— select a case —</option></select>
          <a href="/cases/" class="button secondary">+ New</a>
        </div>
        <small class="muted">Tip: open a case and add a reference URL first to anchor the search.</small>
      </section>

      <section class="panel" id="googlePanel">
        <h2>2. Google search (3-tier detect)</h2>
        <form id="gForm">
          <label>Extra search terms (optional)</label>
          <input name="q" placeholder="e.g. leaked, onlyfans, snap" />
          <button type="submit" class="mt-1">Run scan</button>
        </form>
      </section>

      <section class="panel">
        <h2>3. Or upload evidence</h2>
        <div class="row">
          <div class="field">
            <label>Image (JPG/PNG/WEBP, max 10 MB)</label>
            <input type="file" id="imgFile" accept="image/*" />
            <button class="mt-1" id="imgBtn">Hash &amp; match</button>
          </div>
          <div class="field">
            <label>Video (frames extracted client-side)</label>
            <input type="file" id="vidFile" accept="video/*" />
            <button class="mt-1" id="vidBtn">Extract 5 frames &amp; scan</button>
            <small class="muted" id="vidProgress"></small>
          </div>
        </div>
      </section>

      <section class="panel" id="resultsPanel" style="display:none">
        <h2>Findings</h2>
        <table class="tight">
          <thead><tr><th>ID</th><th>URL</th><th>Tier</th><th>Confidence</th><th>Status</th><th>Action</th></tr></thead>
          <tbody id="resultsRows"></tbody>
        </table>
      </section>
    </main>
  </div>

  <script src="/public/js/video-frames.js"></script>
  <script src="/public/js/siteHealth.js" defer></script>
  <script>
    function csrf(){const m=document.cookie.match(/(?:^|; )ncsrf=([^;]+)/);return m?m[1]:'';}
    async function api(p,o={}){const r=await fetch(p,{...o,headers:{'content-type':'application/json','x-csrf-token':csrf(),...(o.headers||{})}});if(r.status===401){location.href='/login?next='+encodeURIComponent(location.pathname);return null;}return r.json().catch(()=>({}));}
    function escape(s){return String(s||'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
    function esc(s){return String(s==null?'':s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));}
    function flash(t,m){document.getElementById('flash').innerHTML=`<div class="flash ${esc(t)}">${esc(m)}</div>`;setTimeout(()=>document.getElementById('flash').innerHTML='',6000);}

    function caseId() { return document.getElementById('caseSel').value; }

    async function loadCases() {
      const d = await api('/cases/');
      if (!d) return;
      const sel = document.getElementById('caseSel');
      d.cases.forEach(c => {
        const o = document.createElement('option');
        o.value = c.id; o.textContent = `#${c.id} — ${c.victim_name} (${c.status})`;
        sel.appendChild(o);
      });
      // pre-select from query string
      const params = new URLSearchParams(location.search);
      const wanted = params.get('case_id');
      if (wanted) sel.value = wanted;
    }

    document.getElementById('gForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      if (!caseId()) return flash('err', 'Pick a case first.');
      const q = (new FormData(e.target)).get('q') || '';
      flash('info', 'Scanning… this may take up to a minute.');
      const r = await fetch(`/scan/run?case_id=${encodeURIComponent(caseId())}&q=${encodeURIComponent(q)}`, {
        headers: { 'x-csrf-token': csrf() },
      });
      const data = await r.json();
      if (!r.ok) return flash('err', data.message || data.error || 'Scan failed');
      flash('ok', `Scanned ${data.scanned} result(s); ${data.confirmed} confirmed.`);
      renderFindings(data.findings);
    });

    document.getElementById('imgBtn').onclick = async () => {
      if (!caseId()) return flash('err', 'Pick a case first.');
      const f = document.getElementById('imgFile').files[0];
      if (!f) return flash('err', 'Pick an image.');
      if (f.size > 10*1024*1024) return flash('err', 'File too big.');
      const fd = new FormData();
      fd.append('image', f);
      fd.append('case_id', caseId());
      flash('info', 'Hashing…');
      const r = await fetch('/scan/image', { method: 'POST', body: fd, headers: { 'x-csrf-token': csrf() } });
      const data = await r.json();
      if (!r.ok) return flash('err', data.message || data.error);
      flash('ok', `Found ${data.hash_matches} hash match(es).`);
      renderFindings([data.finding]);
    };

    document.getElementById('vidBtn').onclick = async () => {
      if (!caseId()) return flash('err', 'Pick a case first.');
      const f = document.getElementById('vidFile').files[0];
      if (!f) return flash('err', 'Pick a video.');
      const prog = document.getElementById('vidProgress');
      prog.textContent = 'Extracting frames…';
      const frames = await window.extractVideoFrames(f, 5, (i, n) => prog.textContent = `Extracting frame ${i+1}/${n}…`);
      prog.textContent = `Extracted ${frames.length} frames. Hashing…`;
      const r = await fetch('/scan/video', { method: 'POST', headers: { 'content-type': 'application/json', 'x-csrf-token': csrf() }, body: JSON.stringify({ case_id: caseId(), frames }) });
      const data = await r.json();
      prog.textContent = '';
      if (!r.ok) return flash('err', data.message || data.error);
      flash('ok', `Hashed ${data.frames_hashed} frame(s).`);
      renderFindings([data.finding]);
    };

    function renderFindings(findings) {
      const panel = document.getElementById('resultsPanel');
      panel.style.display = '';
      const rows = findings.map(f => `
        <tr>
          <td>${f.id}</td>
          <td><a href="${escape(f.url)}" target="_blank" rel="noopener">${escape(f.url).slice(0,60)}…</a></td>
          <td><span class="pill info">T${f.tier}</span></td>
          <td class="mono">${(f.confidence*100).toFixed(0)}%</td>
          <td><span class="pill ${f.is_ncii?'danger':'ok'}">${f.status}</span></td>
          <td>${f.is_ncii ? `<a href="/takedown/?case_id=${f.case_id}&finding_id=${f.id}&url=${encodeURIComponent(f.url)}">Takedown →</a>` : '<span class="muted">—</span>'}</td>
        </tr>`).join('');
      document.getElementById('resultsRows').innerHTML = rows;
    }

    document.getElementById('logout').onclick = async (e) => { e.preventDefault(); await api('/auth/logout', { method: 'POST' }); location.href = '/'; };
    loadCases();
  </script>
</body>
</html>
