// ImposterShield popup (v0.3): verdict, split proven/likely findings,
// on-device detector status.

var HEADLINES = {
  red: 'A lot of AI on this page.',
  yellow: 'Some AI on this page.',
  green: 'No AI found on this page.',
  gray: 'Checking this page...'
};

function hostOf(url) {
  try { return new URL(url).hostname; } catch (e) { return url.slice(0, 60); }
}

function modelLineText(state, pct, error) {
  if (state === 'loading') return 'Detector model downloading: ' + (pct || 0) + '%. One time only; likely-AI checks start when it finishes.';
  if (state === 'failed') return 'The on-device detector failed to load' + (error ? ' [' + error + ']' : '') + '. Marker-based checks still work.';
  return null;
}

function render(res) {
  var dot = document.getElementById('dot');
  var headline = document.getElementById('headline');
  var detail = document.getElementById('detail');
  var findings = document.getElementById('findings');
  var modelline = document.getElementById('modelline');

  if (!res) {
    dot.className = 'dot';
    headline.textContent = 'Nothing to check here.';
    detail.textContent = 'This kind of page (browser settings, web store, new tab) cannot be scanned.';
    return;
  }

  var ml = modelLineText(res.detector, res.detectorPct, res.detectorError);
  modelline.hidden = !ml;
  if (ml) modelline.textContent = ml;

  if (res.onlyModel) {
    dot.className = 'dot';
    headline.textContent = 'Checking this page...';
    detail.textContent = '';
    return;
  }

  dot.className = 'dot ' + res.verdict;
  headline.textContent = HEADLINES[res.verdict] || HEADLINES.gray;

  var bits;
  if (res.checked === 0) {
    bits = ['No images on this page were big enough to judge. Small icons, logos, and emoji are skipped on purpose: nothing that tiny can be called real or fake honestly.'];
  } else {
    bits = ['Checked ' + res.checked + ' image' + (res.checked === 1 ? '' : 's') + '.'];
  }
  if (res.aiCount > 0) bits.push(res.aiCount + ' carried proof of AI generation.');
  if (res.likelyCount > 0) bits.push(res.likelyCount + ' rated likely AI by our detector.');
  if (res.signedCount > 0) bits.push(res.signedCount + ' carried a creator signature (a good sign).');
  if (res.pageDeclared) bits.push('The page itself says it was made with an AI tool.');
  if (res.classified > 0 && res.likelyCount === 0 && typeof res.topScore === 'number') {
    bits.push('Detector checked ' + res.classified + ': highest AI-likeness ' + Math.round(res.topScore * 100) + '%, below the flag line.');
  }
  detail.textContent = bits.join(' ');

  if (res.findings && res.findings.length > 0) {
    findings.hidden = false;
    findings.innerHTML = '';
    res.findings.forEach(function (f) {
      var div = document.createElement('div');
      div.className = 'f' + (f.kind === 'likely' ? ' likely' : '');
      var why = document.createElement('div');
      why.className = 'why';
      why.textContent = (f.kind === 'likely' ? 'Likely AI: ' : '') + f.why;
      var host = document.createElement('div');
      host.className = 'host';
      host.textContent = hostOf(f.url);
      var wrong = document.createElement('a');
      wrong.href = '#';
      wrong.className = 'wrong';
      wrong.textContent = 'This flag is wrong';
      wrong.addEventListener('click', function (e) {
        e.preventDefault();
        wrong.textContent = 'Sending...';
        fetch('https://impostershield.com/api/feedback', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            kind: 'wrong_flag',
            imageUrl: f.url,
            pageHost: hostOf(res.url || ''),
            verdict: f.kind,
            score: f.score,
            version: chrome.runtime.getManifest().version
          })
        }).then(function () {
          wrong.textContent = 'Thanks, that helps train the detector';
          wrong.style.pointerEvents = 'none';
        }).catch(function () {
          wrong.textContent = 'Could not send, try later';
        });
      });
      div.appendChild(why);
      div.appendChild(host);
      div.appendChild(wrong);
      findings.appendChild(div);
    });
  } else {
    findings.hidden = true;
  }
}

function refresh(tabId) {
  chrome.runtime.sendMessage({ type: 'IS_GET', tabId: tabId }, render);
}

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  var tab = tabs[0];
  if (!tab || !tab.url || tab.url.indexOf('http') !== 0) {
    render(null);
    return;
  }
  chrome.runtime.sendMessage({ type: 'IS_WARM' });
  refresh(tab.id);
  // Live-update while the model downloads or a scan lands.
  var poll = setInterval(function () { refresh(tab.id); }, 1500);
  window.addEventListener('unload', function () { clearInterval(poll); });

  document.getElementById('rescan').addEventListener('click', function () {
    chrome.runtime.sendMessage({ type: 'IS_RESCAN', tabId: tab.id });
    document.getElementById('headline').textContent = 'Checking this page...';
    document.getElementById('dot').className = 'dot';
  });
});

document.getElementById('site').addEventListener('click', function () {
  chrome.tabs.create({ url: 'https://impostershield.com' });
});
