<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Log In | PaceHelper</title>
  <meta name="theme-color" content="#001b38" />
  <link rel="stylesheet" href="style.css" />
  <script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
  <style>
    body { display: flex; flex-direction: column; min-height: 100vh; }
    .container.login-wrapper { flex: 1; display: flex; align-items: center; justify-content: center; padding-top: 80px; }
    .login-card { background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 16px; padding: 40px; width: 100%; max-width: 400px; box-shadow: 0 20px 40px rgba(0,0,0,0.4); text-align: center; backdrop-filter: blur(10px); }
    .login-card h1 { margin-top: 0; font-size: 1.8rem; margin-bottom: 10px; color: white; }
    .login-desc { color: #cce7ff; margin-bottom: 30px; line-height: 1.5; }
    .input-group { margin-bottom: 20px; text-align: left; }
    .input-group label { display: block; margin-bottom: 8px; font-size: 0.9rem; font-weight: bold; color: #cce7ff; }
    input.ts-input { width: 100%; padding: 12px; border-radius: 10px; border: 1px solid #4da3ff; background: #ffffff20; color: white; font-size: 1rem; box-sizing: border-box; margin-bottom: 0; }
    input.ts-input:focus { outline: none; box-shadow: 0 0 0 3px rgba(77, 163, 255, 0.35); }
    .action-btn { width: 100%; padding: 14px; border-radius: 12px; border: none; font-weight: bold; font-size: 1rem; cursor: pointer; background: #4da3ff; color: #001b38; transition: transform 0.2s, filter 0.2s; margin-top: 10px; }
    .action-btn:hover { background: #73baff; transform: translateY(-2px); }
    .action-btn:active { transform: scale(0.98); }
    .action-btn:disabled { background: #555; cursor: not-allowed; color: #aaa; transform: none; }
    .status-msg { margin-top: 20px; padding: 12px; border-radius: 8px; font-size: 0.9rem; display: none; }
    .status-success { background: rgba(77, 255, 148, 0.15); border: 1px solid rgba(77, 255, 148, 0.4); color: #8cffb4; }
    .status-error { background: rgba(255, 100, 100, 0.15); border: 1px solid rgba(255, 100, 100, 0.4); color: #ffcccc; }
    #loggedInView { display: none; }
    .user-email-display { font-size: 1.2rem; color: #4daaff; margin: 10px 0 30px; word-break: break-all; font-weight: bold; }
  </style>
</head>
<body>
  <nav class="navbar" aria-label="Primary">
    <a href="login.html" class="active" style="color: #ff6666 !important; border-bottom-color: #ff6666;">Log In</a>
    <a href="index.html">Pace Calculator</a>
    <a href="race_predictor.html">Race Predictor</a>
    <a href="running_plan.html">Plan Builder</a>
    <a href="quotes.html">Motivational Quotes</a>
    <a href="best_gear.html">Best Gear</a>
    <a href="myth_of_day.html">Myth of the Day</a>
    <a href="racing.html">Racing</a>
    <a href="negative_split.html">Negative Split</a>
    <a href="track_snake.html" style="color: #4daaff !important; font-weight: 800; border: 1px solid rgba(77, 170, 255, 0.4); padding: 4px 10px; border-radius: 6px;">Track Snake 🐍</a>
  </nav>

  <div class="container login-wrapper">
    <div class="login-card">
      <div id="loggedOutView">
        <h1>Welcome Back</h1>
        <p class="login-desc">Sign in to save your <b>Track Snake</b> high scores and sync your running plans.</p>
        <form id="loginForm">
          <div class="input-group">
            <label for="email">Email Address</label>
            <input type="email" id="email" class="ts-input" placeholder="runner@example.com" required />
          </div>
          <button type="submit" id="submitBtn" class="action-btn">Send Magic Link</button>
        </form>
      </div>

      <div id="loggedInView">
        <h1>You are logged in!</h1>
        <p class="login-desc">Current session active for:</p>
        <div class="user-email-display" id="displayEmail">...</div>
        <button id="btnGoHome" class="action-btn" style="margin-bottom: 10px;">Go to Track Snake</button>
        <button id="btnSignOut" class="action-btn" style="background: rgba(255,255,255,0.1); color: white; border: 1px solid rgba(255,255,255,0.2);">Sign Out</button>
      </div>
      <div id="statusArea" class="status-msg"></div>
    </div>
  </div>

  <script>
    const SUPABASE_URL = "https://rkgwvecretdnpqqxtrle.supabase.co";
    const SUPABASE_ANON_KEY = "sb_publishable_qM1ggUQ6-Is9RynJag9aZA_GMRaPPdc";
    let sb = null;
    if (typeof supabase !== 'undefined') sb = supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

    const loggedOutView = document.getElementById('loggedOutView');
    const loggedInView = document.getElementById('loggedInView');
    const loginForm = document.getElementById('loginForm');
    const emailInput = document.getElementById('email');
    const submitBtn = document.getElementById('submitBtn');
    const statusArea = document.getElementById('statusArea');
    const displayEmail = document.getElementById('displayEmail');
    const btnSignOut = document.getElementById('btnSignOut');
    const btnGoHome = document.getElementById('btnGoHome');

    function showLoggedIn(email) {
      loggedOutView.style.display = 'none';
      loggedInView.style.display = 'block';
      displayEmail.textContent = email;
      statusArea.style.display = 'none';
    }
    function showLoggedOut() {
      loggedInView.style.display = 'none';
      loggedOutView.style.display = 'block';
    }
    function setStatus(msg, type) {
      statusArea.textContent = msg;
      statusArea.className = `status-msg status-${type}`;
      statusArea.style.display = 'block';
    }

    async function checkUser() {
      if (!sb) return;
      
      // 1. FAST CHECK: Local Storage first
      try {
        const key = `sb-${new URL(SUPABASE_URL).hostname.split('.')[0]}-auth-token`;
        const stored = localStorage.getItem(key);
        if (stored) {
            const parsed = JSON.parse(stored);
            if (parsed.user) showLoggedIn(parsed.user.email);
        }
      } catch (e) {}

      // 2. BACKGROUND SYNC
      try {
        const { data: { session } } = await sb.auth.getSession();
        if (session) showLoggedIn(session.user.email);
        else showLoggedOut();
      } catch(e) {
        // If network fails, stick with what we found in local storage
      }
    }

    loginForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const email = emailInput.value.trim();
      if (!email) return;
      if (!sb) { setStatus("Supabase not configured correctly.", "error"); return; }

      submitBtn.disabled = true;
      submitBtn.textContent = "Sending...";
      statusArea.style.display = 'none';

      // ✅ FIX: Redirect specifically to the game page
      const { error } = await sb.auth.signInWithOtp({
        email: email,
        options: { emailRedirectTo: window.location.origin + '/track_snake.html' }
      });

      submitBtn.disabled = false;
      submitBtn.textContent = "Send Magic Link";

      if (error) {
        setStatus(error.message, "error");
      } else {
        setStatus("Check your email! We sent you a magic login link.", "success");
        emailInput.value = "";
      }
    });

    btnSignOut.addEventListener('click', async () => {
      if (!sb) return;
      await sb.auth.signOut();
      showLoggedOut();
      setStatus("You have been signed out.", "success");
    });

    btnGoHome.addEventListener('click', () => { window.location.href = 'track_snake.html'; });

    checkUser();
  </script>
</body>
</html>