(function() {
  const M = window.MANIFEST;
  if (!M) { document.body.innerHTML = '<div class="empty">manifest missing</div>'; return; }

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

  const total = (M.counts && M.counts.total) || 0;
  const genIso = M.generated_at || '';
  let genLocal = genIso;
  if (genIso) {
    const d = new Date(genIso);
    if (!isNaN(d)) {
      // Locale-aware date+time, e.g. "5/15/2026, 2:01:05 PM" — uses the viewer's timezone.
      genLocal = d.toLocaleString(undefined, {
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit',
      });
    }
  }
  const cell = (k, v) =>
    `<span class="meta-cell"><span class="k">${esc(k)}</span><span class="v">${esc(v)}</span></span>`;
  const sep = '<span class="meta-sep"></span>';
  document.getElementById('meta').innerHTML =
    cell('ASSETS', String(total)) + sep +
    cell('PATH',   M.path_filter || '—') + sep +
    cell('GENERATED', genLocal);

  const classSet = new Set();
  for (const a of M.assets) { classSet.add(a.class); }
  const classes = Array.from(classSet).sort();
  const enabled = new Set(classes);

  const chipsEl = document.getElementById('chips');
  for (const c of classes) {
    const el = document.createElement('span');
    el.className = 'chip on'; el.textContent = c; el.dataset.cls = c;
    el.onclick = () => {
      if (enabled.has(c)) { enabled.delete(c); el.classList.remove('on'); }
      else { enabled.add(c); el.classList.add('on'); }
      render();
    };
    chipsEl.appendChild(el);
  }

  const searchEl = document.getElementById('search');
  searchEl.addEventListener('input', render);

  const gridEl = document.getElementById('grid');

  function render() {
    const q = searchEl.value.trim().toLowerCase();
    const items = M.assets.filter(a =>
      enabled.has(a.class) && (q === '' || a.asset_path.toLowerCase().includes(q))
    );
    if (items.length === 0) {
      gridEl.innerHTML = '<div class="empty">No assets matched.</div>';
      return;
    }
    gridEl.innerHTML = items.map(a => {
      const path = esc(a.asset_path);
      const cls = esc(a.class);
      const tier = esc(a.tier);
      // UE convention: /Game/Foo/Bar.Bar  → name = "Bar"
      // Fallback for paths without the dotted suffix: take the last path segment.
      const rawName = a.asset_path.includes('.')
        ? a.asset_path.substring(a.asset_path.lastIndexOf('.') + 1)
        : a.asset_path.substring(a.asset_path.lastIndexOf('/') + 1);
      const name = esc(rawName);
      const img = a.png
        ? `<img loading="lazy" src="${esc(a.png)}" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'miss',textContent:'missing'}))">`
        : `<div class="miss">${cls}</div>`;
      return `<div class="card">
        ${img}
        <div class="meta-row">
          <code class="path" title="${path}">${path}</code>
          <div class="name" title="${name}">${name}</div>
          <div class="row2">
            <span class="badge tier-${tier}">${tier}</span>
            <button class="copy" data-p="${path}">copy</button>
          </div>
        </div>
      </div>`;
    }).join('');
    gridEl.querySelectorAll('button.copy').forEach(b => {
      b.onclick = () => { navigator.clipboard.writeText(b.dataset.p); b.textContent = 'copied'; setTimeout(() => b.textContent = 'copy', 1200); };
    });
  }
  render();
})();
