{{define "content"}}
  <div class="w-full max-w-md px-6">
    <!-- Logo -->
    <div class="text-center mb-10">
      <h1 class="text-3xl font-bold text-white tracking-tight">
        <span class="text-[#c9a84c]">Deal</span>space
      </h1>
      <p class="text-[#b0bec5] mt-2 text-sm">Secure M&A deal management</p>
    </div>

    <!-- Screen 1: Email -->
    <div id="step-email" class="bg-[#0d1f3c] border border-white/[0.08] rounded-xl p-8">
      <h2 class="text-xl font-semibold text-white mb-2">Sign in</h2>
      <p class="text-[#b0bec5] text-sm mb-6">Enter your email address to continue.</p>

      <div id="error-email" class="hidden mb-4 p-3 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 text-sm"></div>

      <div class="space-y-5">
        <div>
          <label for="email" class="block text-sm font-medium text-[#b0bec5] mb-1.5">Email</label>
          <input type="email" id="email" name="email" required autocomplete="email" autofocus
            placeholder="you@company.com"
            class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white placeholder-[#8899a6] focus:outline-none focus:border-[#c9a84c] focus:ring-1 focus:ring-[#c9a84c] transition"
            onkeydown="if(event.key==='Enter'){event.preventDefault();submitEmail();}">
        </div>
        <button type="button" id="emailBtn" onclick="submitEmail()"
          class="w-full py-2.5 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg transition disabled:opacity-50">
          Login
        </button>
      </div>
    </div>

    <!-- Screen 2: Code -->
    <div id="step-code" style="display:none" class="bg-[#0d1f3c] border border-white/[0.08] rounded-xl p-8">
      <h2 class="text-xl font-semibold text-white mb-2">Check your email</h2>
      <p class="text-[#b0bec5] text-sm mb-6">
        We sent a 6-digit code to <span id="sent-email" class="text-white font-medium"></span>
      </p>

      <div id="error-code" class="hidden mb-4 p-3 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 text-sm"></div>

      <div class="space-y-5">
        <div>
          <label for="code" class="block text-sm font-medium text-[#b0bec5] mb-1.5">Login code</label>
          <input type="text" id="code" name="code" autocomplete="one-time-code"
            maxlength="6" inputmode="numeric" pattern="[0-9]*"
            placeholder="000000"
            class="code-input w-full px-4 py-3 bg-[#0a1628] border border-white/[0.08] rounded-lg text-[#c9a84c] placeholder-[#8899a6] focus:outline-none focus:border-[#c9a84c] focus:ring-1 focus:ring-[#c9a84c] transition"
            onkeydown="if(event.key==='Enter'){event.preventDefault();verifyCode();}">
        </div>
        <button type="button" id="codeBtn" onclick="verifyCode()"
          class="w-full py-2.5 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg transition disabled:opacity-50">
          Verify & sign in
        </button>
      </div>

      <div class="mt-4 flex items-center justify-between">
        <button onclick="backToEmail()" class="text-[#b0bec5] text-sm hover:text-white transition">
          &larr; Different email
        </button>
        <button id="resendBtn" onclick="resendCode()" class="text-[#c9a84c] text-sm hover:text-[#b8973f] transition">
          Resend code
        </button>
      </div>
    </div>

    <p class="text-center text-[#8899a6] text-xs mt-6">
      Don&rsquo;t have an account? Dealspace is invite-only.<br>
      <a href="/#demo" class="text-[#c9a84c] hover:underline">Request access on muskepo.com</a>
    </p>
    <p class="text-center text-[#8899a6] text-xs mt-3">&copy; 2026 Muskepo B.V. — Amsterdam</p>
  </div>
{{end}}

{{define "scripts"}}
  <script>
    const params = new URLSearchParams(window.location.search);
    const nextURL = params.get('next') || '/app/projects';

    if (localStorage.getItem('ds_token')) {
      document.cookie = 'ds_token=' + localStorage.getItem('ds_token') + '; path=/; SameSite=Lax; max-age=31536000';
      window.location.href = nextURL;
    }

    let currentEmail = '';

    function submitEmail() {
      const errorEl = document.getElementById('error-email');
      currentEmail = document.getElementById('email').value.trim().toLowerCase();
      if (!currentEmail) return;
      errorEl.classList.add('hidden');

      // Show code screen immediately
      document.getElementById('sent-email').textContent = currentEmail;
      document.getElementById('step-email').style.display = 'none';
      document.getElementById('step-code').style.display = 'block';
      document.getElementById('code').value = '';
      document.getElementById('code').focus();

      // Send challenge in parallel (fire and forget)
      fetch('/api/auth/challenge', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: currentEmail }),
      }).catch(() => {});
    }

    async function verifyCode() {
      const btn = document.getElementById('codeBtn');
      const errorEl = document.getElementById('error-code');
      const codeVal = document.getElementById('code').value.trim();
      if (!codeVal || !currentEmail) return;

      btn.disabled = true;
      btn.textContent = 'Verifying...';
      errorEl.classList.add('hidden');

      try {
        const res = await fetch('/api/auth/verify', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email: currentEmail, code: codeVal }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Invalid or expired code');

        localStorage.setItem('ds_token', data.token);
        localStorage.setItem('ds_user', JSON.stringify(data.user));
        document.cookie = 'ds_token=' + data.token + '; path=/; SameSite=Lax; max-age=31536000';
        window.location.href = nextURL;
      } catch (err) {
        errorEl.textContent = err.message;
        errorEl.classList.remove('hidden');
        btn.disabled = false;
        btn.textContent = 'Verify & sign in';
      }
    }

    function backToEmail() {
      document.getElementById('step-code').style.display = 'none';
      document.getElementById('step-email').style.display = 'block';
      document.getElementById('error-code').classList.add('hidden');
      document.getElementById('email').focus();
    }

    async function resendCode() {
      const btn = document.getElementById('resendBtn');
      btn.disabled = true;
      btn.textContent = 'Sending...';
      try {
        await fetch('/api/auth/challenge', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email: currentEmail }),
        });
        btn.textContent = 'Code sent!';
        setTimeout(() => { btn.textContent = 'Resend code'; btn.disabled = false; }, 3000);
      } catch {
        btn.textContent = 'Resend code';
        btn.disabled = false;
      }
    }

    // Auto-submit when 6 digits entered
    document.getElementById('code').addEventListener('input', (e) => {
      e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
      if (e.target.value.length === 6) verifyCode();
    });
  </script>
{{end}}
