/**
 * timmy-id.js — Timmy's identity card.
 *
 * Fetches Timmy's Nostr npub from GET /api/identity/timmy and populates
 * the #timmy-id-card widget. Npub is displayed shortened and is copyable.
 * Zap count refreshes every 60 seconds.
 */

const REFRESH_INTERVAL_MS = 60_000;

function shortenNpub(npub) {
  if (!npub || npub.length < 16) return npub;
  return npub.slice(0, 10) + '…' + npub.slice(-6);
}

async function fetchTimmyIdentity() {
  try {
    const res = await fetch('/api/identity/timmy');
    if (!res.ok) return;
    return await res.json();
  } catch {
    return null;
  }
}

function renderCard(data) {
  if (!data) return;

  const $npub    = document.getElementById('timmy-npub');
  const $zapCount = document.getElementById('timmy-zap-count');

  if ($npub && data.npub) {
    $npub.textContent = shortenNpub(data.npub);
    $npub.title = data.npub + '\n(click to copy)';

    if (!$npub._clickBound) {
      $npub._clickBound = true;
      $npub.addEventListener('click', () => {
        navigator.clipboard.writeText(data.npub).then(() => {
          const orig = $npub.textContent;
          $npub.textContent = 'copied!';
          setTimeout(() => { $npub.textContent = orig; }, 1500);
        }).catch(() => {});
      });
    }
  }

  if ($zapCount) {
    const n = typeof data.zapCount === 'number' ? data.zapCount : 0;
    $zapCount.textContent = `⚡ ${n} zap${n === 1 ? '' : 's'} sent`;
  }
}

export async function initTimmyId() {
  const data = await fetchTimmyIdentity();
  renderCard(data);

  setInterval(async () => {
    const refreshed = await fetchTimmyIdentity();
    renderCard(refreshed);
  }, REFRESH_INTERVAL_MS);
}
