/*
 * Mysterion Verify — browser-action popup.
 * Fetches the active tab's PDF verdict from background.js and renders the
 * Tier-2 localization (changes[]) as a readable list. Mirrors the desktop
 * app's PdfChange.describe() surfacing. Non-text (Tier-1-only) changes are
 * shown as a single "location not available" line — Tier-2 object
 * localization is not built yet.
 */
(function () {
  'use strict';

  var api = (typeof browser !== 'undefined') ? browser : chrome;

  // patch5b: scan-mode dropdown persistence (mysterionScanMode).
  var _MYST_MODES = ['disable', 'click', 'hover', 'all'];
  function _initScanMode() {
    var sel = document.getElementById('scan-mode');
    if (!sel) return;
    try {
      api.storage.local.get('mysterionScanMode', function (r) {
        var m = r && r.mysterionScanMode;
        sel.value = (_MYST_MODES.indexOf(m) >= 0) ? m : 'click';
      });
    } catch (e) { sel.value = 'click'; }
    sel.addEventListener('change', function () {
      var m = _MYST_MODES.indexOf(sel.value) >= 0 ? sel.value : 'hover';
      try { api.storage.local.set({ mysterionScanMode: m }); } catch (e) {}
    });
  }
  document.addEventListener('DOMContentLoaded', _initScanMode);

  function q(id) { return document.getElementById(id); }

  // Mirror of background.js _describePdfChange, plus an explicit non-text branch.
  function describeChange(c) {
    if (!c || typeof c !== 'object') return String(c);
    if (c.kind === 'nontext') {
      return c.detail || 'Non-text change — content added or modified after signing';
    }
    var page = (c.page != null) ? c.page : '?';
    if (c.paragraphCountChanged) {
      var at = c.divergesAtParagraph;
      return (at != null)
        ? 'Page ' + page + ' altered starting at paragraph ' + at
        : 'Page ' + page + ' altered (sections added or removed)';
    }
    var paras = c.paragraphs || [];
    if (!paras.length) return 'Page ' + page + ' altered';
    if (paras.length === 1) return 'Page ' + page + ', section ' + paras[0] + ' changed';
    return 'Page ' + page + ', sections ' + paras.join(', ') + ' changed';
  }

  function render(verdict) {
    var dot = q('dot');
    var statusText = q('status-text');
    var creatorEl = q('creator');
    var locSection = q('pdf-localization');
    var list = q('changes');

    if (!verdict) {
      dot.className = 'dot unk';
      statusText.textContent = 'No PDF verified on this tab';
      creatorEl.hidden = true;
      locSection.hidden = true;
      return;
    }

    // Header state.
    if (!verdict.signed) {
      dot.className = 'dot unk';
      statusText.textContent = 'No Mysterion signature found';
    } else if (verdict.altered) {
      dot.className = 'dot alt';
      statusText.textContent = 'Altered after signing';
    } else {
      dot.className = 'dot ok';
      statusText.textContent = 'Verified — content intact';
    }

    if (verdict.creator) {
      creatorEl.textContent = 'By ' + verdict.creator;
      creatorEl.hidden = false;
    } else {
      creatorEl.hidden = true;
    }

    // Localization list.
    var changes = Array.isArray(verdict.changes) ? verdict.changes : null;
    while (list.firstChild) list.removeChild(list.firstChild);

    if (verdict.altered && changes && changes.length) {
      changes.forEach(function (c) {
        var li = document.createElement('li');
        if (c && c.kind === 'nontext') li.className = 'nontext';
        li.textContent = describeChange(c);
        list.appendChild(li);
      });
      locSection.hidden = false;
    } else if (verdict.altered) {
      // Altered but no structured changes (localization unavailable).
      var li = document.createElement('li');
      li.className = 'nontext';
      li.textContent = 'Content altered — location not available';
      list.appendChild(li);
      locSection.hidden = false;
    } else {
      locSection.hidden = true;
    }
  }

  function requestVerdict() {
    api.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      var tabId = (tabs && tabs[0]) ? tabs[0].id : null;
      try {
        api.runtime.sendMessage({ type: 'GET_PDF_VERDICT', tabId: tabId }, function (resp) {
          if (api.runtime.lastError) { render(null); return; }
          render(resp ? resp.verdict : null);
        });
      } catch (e) {
        render(null);
      }
    });
  }

  // patch10: live-update — re-render as soon as a verdict is broadcast, so
  // it doesn't matter whether the popup was opened before or after verifying.
  try {
    api.runtime.onMessage.addListener(function (msg) {
      if (msg && msg.type === 'mysterion-pdf-verdict' && msg.verdict) {
        render(msg.verdict);
      }
    });
  } catch (e) {}

  document.addEventListener('DOMContentLoaded', requestVerdict);
})();
