---
import Base from '../../layouts/Base.astro';
---

<Base title="Registrati — BincioWiki" public={true}>
  <div class="max-w-sm mx-auto mt-16">
    <h1 class="text-2xl font-bold mb-2 text-center" style="color: var(--text-primary)">
      Bincio<span style="color: var(--accent)">Wiki</span>
    </h1>
    <p class="text-sm text-center mb-8" style="color: var(--text-4)">Crea il tuo account</p>

    <div id="invalid-msg" class="hidden text-sm px-3 py-2 rounded bg-red-900/40 text-red-300 border border-red-800 mb-4">
      Codice invito non valido o già utilizzato.
    </div>

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

      <div class="flex flex-col gap-1">
        <label class="text-sm" style="color: var(--text-4)">Handle</label>
        <input
          id="handle"
          type="text"
          autocomplete="username"
          autocapitalize="none"
          placeholder="es. mario"
          required
          class="px-3 py-2 rounded border text-sm bg-zinc-900 border-zinc-700 focus:outline-none focus:border-zinc-500"
          style="color: var(--text-primary)"
        />
        <span class="text-xs" style="color: var(--text-5)">2-20 caratteri: lettere minuscole, numeri, _ o -</span>
      </div>

      <div class="flex flex-col gap-1">
        <label class="text-sm" style="color: var(--text-4)">Nome visualizzato <span style="color:var(--text-5)">(opzionale)</span></label>
        <input
          id="display-name"
          type="text"
          autocomplete="name"
          placeholder="es. Mario Rossi"
          class="px-3 py-2 rounded border text-sm bg-zinc-900 border-zinc-700 focus:outline-none focus:border-zinc-500"
          style="color: var(--text-primary)"
        />
      </div>

      <div class="flex flex-col gap-1">
        <label class="text-sm" style="color: var(--text-4)">Password</label>
        <input
          id="password"
          type="password"
          autocomplete="new-password"
          required
          class="px-3 py-2 rounded border text-sm bg-zinc-900 border-zinc-700 focus:outline-none focus:border-zinc-500"
          style="color: var(--text-primary)"
        />
        <span class="text-xs" style="color: var(--text-5)">Minimo 8 caratteri</span>
      </div>

      <div class="flex flex-col gap-1">
        <label class="text-sm" style="color: var(--text-4)">Conferma password</label>
        <input
          id="confirm-password"
          type="password"
          autocomplete="new-password"
          required
          class="px-3 py-2 rounded border text-sm bg-zinc-900 border-zinc-700 focus:outline-none focus:border-zinc-500"
          style="color: var(--text-primary)"
        />
      </div>

      <button
        type="submit"
        id="submit-btn"
        class="mt-2 px-4 py-2 rounded text-sm font-medium transition-colors"
        style="background: var(--accent); color: #000"
      >
        Registrati
      </button>
    </form>
  </div>
</Base>

<script>
  const params      = new URLSearchParams(window.location.search);
  const code        = params.get('code') || '';
  const form        = document.getElementById('register-form') as HTMLFormElement;
  const errorEl     = document.getElementById('error-msg') as HTMLDivElement;
  const invalidEl   = document.getElementById('invalid-msg') as HTMLDivElement;
  const submitBtn   = document.getElementById('submit-btn') as HTMLButtonElement;

  if (!code) {
    form.classList.add('hidden');
    invalidEl.classList.remove('hidden');
  }

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    errorEl.classList.add('hidden');

    const handle      = (document.getElementById('handle') as HTMLInputElement).value.trim();
    const displayName = (document.getElementById('display-name') as HTMLInputElement).value.trim();
    const password    = (document.getElementById('password') as HTMLInputElement).value;
    const confirm     = (document.getElementById('confirm-password') as HTMLInputElement).value;

    if (password !== confirm) {
      errorEl.textContent = 'Le password non coincidono';
      errorEl.classList.remove('hidden');
      return;
    }

    submitBtn.disabled = true;
    submitBtn.textContent = 'Registrazione…';

    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code, handle, display_name: displayName, password }),
      });

      if (res.ok) {
        window.location.replace('/');
      } else {
        const data = await res.json().catch(() => ({}));
        errorEl.textContent = data.detail || 'Errore durante la registrazione';
        errorEl.classList.remove('hidden');
      }
    } catch {
      errorEl.textContent = 'Errore di rete. Riprova.';
      errorEl.classList.remove('hidden');
    } finally {
      submitBtn.disabled = false;
      submitBtn.textContent = 'Registrati';
    }
  });
</script>
