---
import Base from '../../layouts/Base.astro';
const editUrl   = import.meta.env.PUBLIC_EDIT_URL  ?? '';
const wikiUrl   = import.meta.env.PUBLIC_WIKI_URL  ?? '';
---
<Base title="Login — BincioActivity" public={true}>
  <div class="max-w-sm mx-auto mt-16 px-4">
    <p class="text-center text-zinc-600 text-sm italic mb-8 leading-relaxed">
      mangia<br/>bevi<br/>stai calmo<br/>non strappare
    </p>
    <h1 class="text-2xl font-bold text-white mb-6 text-center">Sign in</h1>

    <form id="login-form" data-wiki-url={wikiUrl} class="space-y-4">
      <div>
        <label class="block text-sm text-zinc-400 mb-1" for="handle">Handle</label>
        <input id="handle" name="handle" type="text" autocomplete="username"
          class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
          placeholder="your handle" required />
      </div>
      <div>
        <label class="block text-sm text-zinc-400 mb-1" for="password">Password</label>
        <input id="password" name="password" type="password" autocomplete="current-password"
          class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white focus:outline-none focus:border-[--accent]"
          required />
      </div>
      <p id="login-error" class="text-red-400 text-sm hidden"></p>
      <button type="submit"
        class="w-full py-2 rounded-lg bg-[--accent] hover:opacity-90 text-white font-medium transition-opacity">
        Sign in
      </button>
    </form>

    {editUrl && (
      <p class="text-center text-zinc-500 text-sm mt-6">
        Have an invite? <a href="/register/" class="text-[--accent] hover:underline">Create account</a>
      </p>
      <p class="text-center text-zinc-600 text-sm mt-2">
        <a href="/reset-password/" class="hover:text-zinc-400 transition-colors">Forgot password?</a>
      </p>
    )}
  </div>
</Base>

<script>
  const form   = document.getElementById('login-form') as HTMLFormElement;
  const errEl  = document.getElementById('login-error') as HTMLElement;
  const wikiUrl = form?.dataset.wikiUrl ?? '';

  form?.addEventListener('submit', async (e) => {
    e.preventDefault();
    const handle   = (form.querySelector('#handle')   as HTMLInputElement).value.trim();
    const password = (form.querySelector('#password') as HTMLInputElement).value;
    errEl.classList.add('hidden');

    try {
      const r = await fetch('/api/auth/login', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ handle, password }),
      });
      if (!r.ok) {
        const d = await r.json().catch(() => ({}));
        errEl.textContent = d.detail ?? 'Invalid credentials';
        errEl.classList.remove('hidden');
        return;
      }
      const data = await r.json();
      // Wiki-only users have no activity access — send them straight to the wiki.
      if (!data.activity_access && data.wiki_access && wikiUrl) {
        window.location.href = wikiUrl;
        return;
      }
      const next = new URLSearchParams(window.location.search).get('next') ?? '/';
      window.location.href = next;
    } catch {
      errEl.textContent = 'Could not reach server';
      errEl.classList.remove('hidden');
    }
  });
</script>
