<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login — Dealspace</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    * { font-family: 'Inter', sans-serif; }
    body { background: #0a1628; }
    .code-input { letter-spacing: 0.5em; text-align: center; font-size: 1.5rem; font-weight: 600; }
  </style>
</head>
<body class="min-h-screen flex items-center justify-center">
  <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>

    <!-- Step 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 to receive a login code.</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>

      <form id="emailForm" 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">
        </div>
        <button type="submit" id="emailBtn"
          class="w-full py-2.5 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg transition disabled:opacity-50">
          Send login code
        </button>
      </form>
    </div>

    <!-- Step 2: OTP Code -->
    <div id="step-code" class="hidden bg-[#0d1f3c] border border-white/[0.08] rounded-xl p-8">
      <h2 class="text-xl font-semibold text-white mb-2">Enter your code</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>

      <form id="codeForm" 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" required 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">
        </div>
        <button type="submit" id="codeBtn"
          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>
      </form>

      <div class="mt-4 flex items-center justify-between">
        <button id="backBtn" class="text-[#b0bec5] text-sm hover:text-white transition">
          &larr; Use a different email
        </button>
        <button id="resendBtn" 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>

  <script>
    // If already logged in, redirect
    if (localStorage.getItem('ds_token')) {
      window.location.href = '/app/tasks';
    }

    let currentEmail = '';

    // Step 1: Send challenge
    document.getElementById('emailForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      const btn = document.getElementById('emailBtn');
      const errorEl = document.getElementById('error-email');
      btn.disabled = true;
      btn.textContent = 'Sending code...';
      errorEl.classList.add('hidden');

      currentEmail = document.getElementById('email').value.trim().toLowerCase();

      try {
        const res = await fetch('/api/auth/challenge', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email: currentEmail }),
        });

        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Failed to send code');

        // Show code step
        document.getElementById('sent-email').textContent = currentEmail;
        document.getElementById('step-email').classList.add('hidden');
        document.getElementById('step-code').classList.remove('hidden');
        document.getElementById('code').focus();
      } catch (err) {
        errorEl.textContent = err.message;
        errorEl.classList.remove('hidden');
      } finally {
        btn.disabled = false;
        btn.textContent = 'Send login code';
      }
    });

    // Step 2: Verify code
    document.getElementById('codeForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      const btn = document.getElementById('codeBtn');
      const errorEl = document.getElementById('error-code');
      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: document.getElementById('code').value.trim(),
          }),
        });

        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));

        // Everyone lands on /app/tasks — admin panel accessible from nav
        window.location.href = '/app/tasks';
      } catch (err) {
        errorEl.textContent = err.message;
        errorEl.classList.remove('hidden');
        btn.disabled = false;
        btn.textContent = 'Verify & sign in';
      }
    });

    // Back button
    document.getElementById('backBtn').addEventListener('click', () => {
      document.getElementById('step-code').classList.add('hidden');
      document.getElementById('step-email').classList.remove('hidden');
      document.getElementById('code').value = '';
      document.getElementById('error-code').classList.add('hidden');
      document.getElementById('email').focus();
    });

    // Resend button
    document.getElementById('resendBtn').addEventListener('click', async () => {
      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) {
        document.getElementById('codeForm').dispatchEvent(new Event('submit'));
      }
    });
  </script>
</body>
</html>
