/* ============================================================
   ARCHIVE — interaction layer
   ============================================================ */

(() => {

  /* ---------- Clock ---------- */
  const clock = document.getElementById('clock');
  if (clock) {
    const tick = () => {
      const d = new Date();
      const pad = n => String(n).padStart(2, '0');
      clock.textContent = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    };
    tick(); setInterval(tick, 1000);
  }

  /* ---------- Custom cursor ---------- */
  const cursor = document.getElementById('cursor');
  const cursorLabel = cursor?.querySelector('.cursor-label');
  let cx = 0, cy = 0, tx = 0, ty = 0;

  if (cursor) {
    window.addEventListener('mousemove', e => { tx = e.clientX; ty = e.clientY; });
    const animate = () => {
      cx += (tx - cx) * 0.2;
      cy += (ty - cy) * 0.2;
      cursor.style.transform = `translate(${cx}px, ${cy}px) translate(-50%, -50%)`;
      requestAnimationFrame(animate);
    };
    animate();

    document.querySelectorAll('[data-cursor], a, button').forEach(el => {
      el.addEventListener('mouseenter', () => {
        cursor.classList.add('is-hover');
        if (cursorLabel) cursorLabel.textContent = el.dataset.cursor || '';
      });
      el.addEventListener('mouseleave', () => {
        cursor.classList.remove('is-hover');
        if (cursorLabel) cursorLabel.textContent = '';
      });
    });
  }

  /* ---------- Hover preview (index view) ---------- */
  const preview = document.getElementById('hoverPreview');
  if (preview) {
    const img = preview.querySelector('img');
    let px = 0, py = 0, ptx = 0, pty = 0;

    document.querySelectorAll('.album-row[data-cover]').forEach(row => {
      row.addEventListener('mouseenter', () => {
        img.src = row.dataset.cover;
        preview.classList.add('is-active');
      });
      row.addEventListener('mouseleave', () => {
        preview.classList.remove('is-active');
      });
    });

    window.addEventListener('mousemove', e => { ptx = e.clientX + 200; pty = e.clientY; });
    const animPrev = () => {
      px += (ptx - px) * 0.1;
      py += (pty - py) * 0.1;
      preview.style.left = px + 'px';
      preview.style.top = py + 'px';
      requestAnimationFrame(animPrev);
    };
    animPrev();
  }

  /* ---------- Lightbox ---------- */
  const lightbox = document.getElementById('lightbox');
  if (lightbox) {
    const lbImg = document.getElementById('lbImg');
    const lbIdx = document.getElementById('lbIdx');
    const lbTotal = document.getElementById('lbTotal');
    const lbExif = document.getElementById('lbExif');
    const lbDownload = document.getElementById('lbDownload');
    const lbClose = document.getElementById('lbClose');
    const lbPrev = document.getElementById('lbPrev');
    const lbNext = document.getElementById('lbNext');
    const tiles = Array.from(document.querySelectorAll('.tile'));
    let active = 0;

    const fmtShutter = s => {
      if (!s) return '—';
      if (typeof s === 'string' && s.includes('/')) return s + 's';
      const f = parseFloat(s);
      return f >= 1 ? f + 's' : '1/' + Math.round(1/f) + 's';
    };
    const fmtDate = d => {
      if (!d) return '—';
      const m = String(d).match(/(\d{4}):(\d{2}):(\d{2})/);
      return m ? `${m[1]}.${m[2]}.${m[3]}` : d;
    };

    const open = idx => {
      active = idx;
      const tile = tiles[idx];
      if (!tile) return;
      const img = tile.querySelector('img');
      const meta = JSON.parse(img.dataset.meta);
      const exif = JSON.parse(img.dataset.exif);

      lbImg.src = img.dataset.full;
      lbIdx.textContent = String(idx + 1).padStart(3, '0');
      lbTotal.textContent = String(tiles.length).padStart(3, '0');
      lbDownload.href = img.dataset.orig;

      const rows = [
        ['File',     meta.file],
        ['Frame',    `${meta.w} × ${meta.h}`],
        ['Size',     meta.size],
        ['Camera',   exif.camera || '—'],
        ['Lens',     exif.lens || '—'],
        ['ISO',      exif.iso || '—'],
        ['Shutter',  fmtShutter(exif.shutter)],
        ['Aperture', exif.aperture ? 'ƒ/' + exif.aperture : '—'],
        ['Focal',    exif.focal ? exif.focal + ' mm' : '—'],
        ['Captured', fmtDate(exif.date)],
      ];
      lbExif.innerHTML = rows.map(([k, v]) => `<dt>${k}</dt><dd>${v}</dd>`).join('');

      lightbox.hidden = false;
      document.body.style.overflow = 'hidden';
    };

    const close = () => {
      lightbox.hidden = true;
      document.body.style.overflow = '';
    };

    const step = dir => open((active + dir + tiles.length) % tiles.length);

    tiles.forEach((t, i) => t.addEventListener('click', () => open(i)));
    lbClose.addEventListener('click', close);
    lbPrev.addEventListener('click', e => { e.stopPropagation(); step(-1); });
    lbNext.addEventListener('click', e => { e.stopPropagation(); step(1); });
    lightbox.addEventListener('click', e => { if (e.target === lightbox || e.target.classList.contains('lightbox__stage')) close(); });

    document.addEventListener('keydown', e => {
      if (lightbox.hidden) return;
      if (e.key === 'Escape') close();
      if (e.key === 'ArrowRight') step(1);
      if (e.key === 'ArrowLeft') step(-1);
    });
  }

})();
