---
import Base from '../../layouts/Base.astro';
import { SITE_TITLE } from '../../consts';
---

<Base title={`Inviti — ${SITE_TITLE}`} description="Invita qualcuno al wiki">
  <div class="max-w-2xl mx-auto">
    <div class="flex items-center justify-between mb-8">
      <h1 class="text-3xl font-bold" style="color: var(--text-primary)">Inviti</h1>
      <button
        id="btn-new"
        class="text-sm px-4 py-2 rounded border transition-colors"
        style="color: var(--accent); border-color: var(--accent)"
      >+ Genera invito</button>
    </div>

    <div id="error-msg" class="hidden mb-4 text-sm px-3 py-2 rounded bg-red-900/40 text-red-300 border border-red-800"></div>

    <div id="invite-list" class="space-y-2">
      <p class="text-sm" style="color: var(--text-4)">Caricamento…</p>
    </div>
  </div>
</Base>

<script>
  const listEl   = document.getElementById('invite-list')!;
  const errorEl  = document.getElementById('error-msg')!;
  const btnNew   = document.getElementById('btn-new')!;

  function showError(msg: string) {
    errorEl.textContent = msg;
    errorEl.classList.remove('hidden');
  }

  function formatDate(ts: number): string {
    if (!ts) return '';
    const d = new Date(ts * 1000);
    return d.toLocaleDateString('it-IT', { day: 'numeric', month: 'short', year: 'numeric' });
  }

  function inviteUrl(code: string): string {
    return `${window.location.origin}/join/?code=${code}`;
  }

  async function loadInvites() {
    try {
      const r = await fetch('/api/invites', { credentials: 'include' });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      const { invites } = await r.json();

      if (!invites.length) {
        listEl.innerHTML = '<p class="text-sm" style="color:var(--text-4)">Nessun invito ancora. Generane uno!</p>';
        return;
      }

      listEl.innerHTML = invites.map((inv: any) => `
        <div class="flex items-center gap-3 px-3 py-2 rounded-lg text-sm" style="background:var(--bg-card)">
          ${inv.used_by
            ? `<span class="flex-1 font-mono text-xs truncate" style="color:var(--text-5)">${inviteUrl(inv.code)}</span>
               <span class="shrink-0 text-xs" style="color:var(--text-5)">usato da <span style="color:var(--accent)">@${inv.used_by}</span></span>`
            : `<span class="flex-1 font-mono text-xs truncate" style="color:var(--text-2)">${inviteUrl(inv.code)}</span>
               <button
                 class="btn-copy shrink-0 text-xs px-2 py-0.5 rounded border transition-colors"
                 style="color:var(--accent);border-color:var(--accent)"
                 data-code="${inv.code}"
               >Copia</button>
               <button
                 class="btn-revoke shrink-0 text-xs text-zinc-500 hover:text-red-400 transition-colors px-2 py-0.5 rounded border border-zinc-700 hover:border-red-800"
                 data-code="${inv.code}"
               >Revoca</button>`
          }
          <span class="shrink-0 text-xs" style="color:var(--text-5)">${formatDate(inv.created_at)}</span>
        </div>
      `).join('');

      listEl.querySelectorAll('.btn-copy').forEach(btn => {
        btn.addEventListener('click', () => {
          const url = inviteUrl((btn as HTMLElement).dataset.code!);
          navigator.clipboard.writeText(url).then(() => {
            btn.textContent = 'Copiato!';
            setTimeout(() => { btn.textContent = 'Copia'; }, 2000);
          });
        });
      });

      listEl.querySelectorAll('.btn-revoke').forEach(btn => {
        btn.addEventListener('click', async () => {
          const code = (btn as HTMLElement).dataset.code!;
          if (!confirm('Revocare questo invito?')) return;
          const r = await fetch(`/api/invites/${code}`, { method: 'DELETE', credentials: 'include' });
          if (r.ok) loadInvites();
          else { const d = await r.json().catch(() => ({})); showError(d.detail || 'Errore'); }
        });
      });
    } catch (e) {
      listEl.innerHTML = '<p class="text-sm" style="color:#f87171">Errore nel caricamento.</p>';
    }
  }

  btnNew.addEventListener('click', async () => {
    errorEl.classList.add('hidden');
    btnNew.setAttribute('disabled', '');
    try {
      const r = await fetch('/api/invites', { method: 'POST', credentials: 'include' });
      if (!r.ok) { const d = await r.json().catch(() => ({})); showError(d.detail || 'Errore'); return; }
      await loadInvites();
    } finally {
      btnNew.removeAttribute('disabled');
    }
  });

  loadInvites();
</script>
