const input = document.querySelector('#filter');
const cards = [...document.querySelectorAll('.identity-card')];
const empty = document.querySelector('#empty');
const filterStatus = document.querySelector('#filter-status');
const copyStatus = document.querySelector('#copy-status');

input?.addEventListener('input', () => {
  const query = input.value.trim().toLowerCase();
  let visible = 0;
  cards.forEach((card) => {
    const show = !query || card.dataset.filter.includes(query);
    card.hidden = !show;
    if (show) visible += 1;
  });
  if (empty) empty.hidden = visible !== 0;
  if (filterStatus) filterStatus.textContent = `${visible} ${visible === 1 ? 'identity' : 'identities'} shown`;
});

function fallbackCopy(text) {
  const area = document.createElement('textarea');
  area.value = text;
  area.setAttribute('readonly', '');
  area.style.position = 'fixed';
  area.style.opacity = '0';
  document.body.append(area);
  area.select();
  const ok = document.execCommand('copy');
  area.remove();
  if (!ok) throw new Error('copy failed');
}

async function copyText(text) {
  if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(text);
  else fallbackCopy(text);
}

document.querySelectorAll('[data-copy-hash]').forEach((button) => button.addEventListener('click', async () => {
  const original = button.textContent;
  try {
    await copyText(button.dataset.copyHash);
    button.textContent = 'Copied checksum';
    if (copyStatus) copyStatus.textContent = 'SHA-256 checksum copied';
  } catch {
    button.textContent = 'Copy failed';
    if (copyStatus) copyStatus.textContent = 'Could not copy the SHA-256 checksum';
  }
  setTimeout(() => { button.textContent = original; }, 1600);
}));

const lensRoot = document.querySelector('#atlas-lens');
const lensIdentity = document.querySelector('#lens-identity');
const lensOperation = document.querySelector('#lens-operation');
const lensMedium = document.querySelector('#lens-medium');
const lensResult = document.querySelector('#lens-result');
let lensRegistry = null;

function renderLens(result) {
  if (!lensResult) return;
  const decision = result?.decision === 'ALLOWED' ? 'ALLOWED' : 'BLOCKED';
  lensResult.dataset.decision = decision.toLowerCase();
  lensResult.querySelector('.lens-signal b').textContent = decision;
  lensResult.querySelector(':scope > p').textContent = result?.reason || 'The registry could not produce a verified decision.';
  lensResult.querySelector(':scope > code').textContent = result?.rule || 'fail closed / no governing rule';
  const resourceWrap = lensResult.querySelector('.lens-resource');
  const resourceLink = lensResult.querySelector('#lens-resource');
  const hash = lensResult.querySelector('#lens-hash');
  if (decision === 'ALLOWED' && result.resource) {
    resourceWrap.hidden = false;
    resourceLink.href = result.resource.immutable_url;
    resourceLink.textContent = `${result.resource.role} / immutable object ↗`;
    hash.textContent = `sha256 ${result.resource.sha256}`;
  } else {
    resourceWrap.hidden = true;
    resourceLink.removeAttribute('href');
    hash.textContent = '';
  }
}

function testLens() {
  if (!lensRegistry || !globalThis.AtlasLens) {
    renderLens({ decision: 'BLOCKED', rule: 'registry and evaluator must load', reason: 'The Atlas Lens failed closed.' });
    return;
  }
  renderLens(globalThis.AtlasLens.evaluate(lensRegistry, lensIdentity.value, lensOperation.value, lensMedium.value));
}

async function initLens() {
  if (!lensRoot) return;
  try {
    const response = await fetch('/registry/identities.json', { headers: { Accept: 'application/json' } });
    if (!response.ok) throw new Error(`registry HTTP ${response.status}`);
    lensRegistry = await response.json();
    testLens();
  } catch (error) {
    renderLens({ decision: 'BLOCKED', rule: 'registry fetch must succeed', reason: `The Atlas Lens failed closed: ${error.message}` });
  }
}

[lensIdentity, lensOperation, lensMedium].forEach((control) => control?.addEventListener('change', testLens));
initLens();
