import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

const API = import.meta.env.VITE_API_URL;

const DIAMONDS = [
  { left: '5%',  top: '12%', size: 10, dur: '9s',  delay: '0s'   },
  { left: '18%', top: '58%', size: 8,  dur: '13s', delay: '2s'   },
  { left: '30%', top: '22%', size: 14, dur: '11s', delay: '0.5s' },
  { left: '48%', top: '72%', size: 7,  dur: '10s', delay: '1.5s' },
  { left: '58%', top: '20%', size: 16, dur: '12s', delay: '0.8s' },
  { left: '70%', top: '65%', size: 10, dur: '8s',  delay: '3s'   },
  { left: '82%', top: '30%', size: 13, dur: '14s', delay: '1s'   },
  { left: '90%', top: '75%', size: 9,  dur: '9s',  delay: '4s'   },
  { left: '38%', top: '45%', size: 6,  dur: '15s', delay: '2.5s' },
  { left: '62%', top: '88%', size: 11, dur: '11s', delay: '0.3s' },
  { left: '12%', top: '82%', size: 8,  dur: '13s', delay: '1.8s' },
  { left: '76%', top: '10%', size: 12, dur: '10s', delay: '3.5s' },
];

const RINGS = [
  { left: '10%', top: '35%', size: 60, dur: '7s',  delay: '0s'   },
  { left: '78%', top: '18%', size: 44, dur: '9s',  delay: '2.5s' },
  { left: '45%', top: '62%', size: 80, dur: '11s', delay: '1s'   },
  { left: '88%', top: '55%', size: 36, dur: '8s',  delay: '3.5s' },
];

const SCANLINES = [
  { top: '28%', width: '160px', left: '5%',  dur: '8s',  delay: '0s'   },
  { top: '52%', width: '120px', left: '74%', dur: '10s', delay: '3s'   },
  { top: '18%', width: '200px', left: '38%', dur: '12s', delay: '1.5s' },
  { top: '75%', width: '140px', left: '20%', dur: '9s',  delay: '2s'   },
];

const INPUT_STYLE = {
  width: '100%', padding: '12px 16px', background: 'rgba(255,255,255,0.07)',
  border: '1px solid rgba(255,255,255,0.18)', borderRadius: 10, color: '#fff',
  fontSize: 15, fontFamily: 'system-ui,sans-serif', outline: 'none', boxSizing: 'border-box',
};

const ERROR_MSGS = {
  email_taken:         'An account with this email already exists.',
  username_taken:      'That username is already taken.',
  use_google:          'This account uses Google sign-in — use the Google button above.',
  invalid_credentials: 'Incorrect email or password.',
  invalid_email:       'Please enter a valid email address.',
  password_too_short:  'Password must be at least 8 characters.',
  invalid_username:    'Username must be 3–20 characters: letters, numbers, underscores only.',
  too_many_attempts:   'Too many attempts — please wait a few minutes and try again.',
};

const RANK_COLORS = ['#f5c518', '#c0ccda', '#e0915a'];

function fmtTime(ms) {
  if (ms == null) return '—';
  const s = Math.floor(ms / 1000);
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
}

const LANDING_CSS = `
  @keyframes heroPulse {
    0%,100% { opacity:.2; transform:translate(-50%,-50%) scale(1); }
    50%      { opacity:.38; transform:translate(-50%,-50%) scale(1.12); }
  }
  @keyframes wordReveal {
    from { opacity:0; transform:translateY(28px); }
    to   { opacity:1; transform:translateY(0); }
  }
  @keyframes fadeUp {
    from { opacity:0; transform:translateY(16px); }
    to   { opacity:1; transform:translateY(0); }
  }
  @keyframes scrollBounce {
    0%,100% { transform:translateY(0); }
    50%     { transform:translateY(5px); }
  }
  .lp-hero-orb {
    position:absolute; top:50%; left:50%;
    width:1100px; height:700px;
    background:radial-gradient(ellipse at center,
      rgba(245,197,24,.07) 0%,
      rgba(37,99,235,.05) 45%,
      transparent 70%);
    border-radius:50%;
    pointer-events:none;
    animation:heroPulse 10s ease-in-out infinite;
  }
  .lp-word { display:block; animation:wordReveal .7s cubic-bezier(.16,1,.3,1) both; }
  .lp-word-1 { animation-delay:.15s; }
  .lp-word-2 { animation-delay:.3s; }
  .lp-word-3 { animation-delay:.45s; }
  .lp-nav {
    position:fixed; top:0; left:0; right:0; z-index:100;
    height:64px; display:flex; align-items:center;
    justify-content:space-between; padding:0 40px;
    background:rgba(7,8,15,.85);
    backdrop-filter:blur(20px); -webkit-backdrop-filter:blur(20px);
    border-bottom:1px solid rgba(255,255,255,.07);
  }
  .lp-nav__logo {
    font-family:'Russo One',sans-serif; font-size:19px;
    letter-spacing:.04em; text-transform:uppercase;
    color:#eceef8; background:none; border:none; cursor:pointer; padding:0;
  }
  .lp-nav__logo span { color:#f5c518; }
  .lp-nav__links { display:flex; align-items:center; gap:28px; }
  .lp-nav-link {
    font-family:'Barlow Condensed',sans-serif; font-size:13px;
    font-weight:600; letter-spacing:.1em; text-transform:uppercase;
    color:#7a85a8; text-decoration:none; cursor:pointer;
    background:none; border:none; padding:0; transition:color .2s;
  }
  .lp-nav-link:hover { color:#eceef8; }
  .lp-nav-signin {
    padding:8px 18px;
    background:rgba(245,197,24,.08); border:1px solid rgba(245,197,24,.35);
    border-radius:6px; font-family:'Barlow Condensed',sans-serif;
    font-size:13px; font-weight:700; letter-spacing:.1em; text-transform:uppercase;
    color:#f5c518; cursor:pointer; transition:background .2s, border-color .2s;
  }
  .lp-nav-signin:hover { background:rgba(245,197,24,.16); border-color:rgba(245,197,24,.6); }
  .lp-container { width:100%; max-width:1100px; margin:0 auto; padding:0 24px; }
  .lp-eyebrow {
    font-family:'Barlow Condensed',sans-serif; font-size:11px;
    font-weight:700; letter-spacing:.3em; text-transform:uppercase;
    color:#f5c518; display:flex; align-items:center; justify-content:center;
    gap:12px; margin-bottom:14px;
  }
  .lp-eyebrow::before,.lp-eyebrow::after {
    content:''; display:block; width:36px; height:1px;
    background:rgba(245,197,24,.4);
  }
  .lp-section-title {
    font-family:'Russo One',sans-serif;
    font-size:clamp(30px,5vw,48px); text-transform:uppercase;
    letter-spacing:.02em; color:#eceef8;
    text-align:center; margin-bottom:56px;
  }
  .lp-step-card {
    background:#111426; border:1px solid rgba(255,255,255,.07);
    border-radius:16px; padding:36px 28px;
    position:relative; overflow:hidden; flex:1; min-width:260px;
    transition:border-color .25s, transform .25s;
  }
  .lp-step-card::before {
    content:''; position:absolute; top:0; left:0; right:0; height:2px;
    background:linear-gradient(to right,transparent,rgba(245,197,24,.65),transparent);
  }
  .lp-step-card:hover { border-color:rgba(245,197,24,.22); transform:translateY(-4px); }
  .lp-feature-card {
    background:#111426; border:1px solid rgba(255,255,255,.07);
    border-radius:12px; padding:28px 24px;
    transition:border-color .25s, transform .25s;
  }
  .lp-feature-card:hover { border-color:rgba(245,197,24,.2); transform:translateY(-3px); }
  .lp-lb-card {
    background:#111426; border:1px solid rgba(255,255,255,.07);
    border-radius:16px; overflow:hidden; max-width:580px; margin:0 auto;
  }
  .lp-lb-row {
    display:flex; align-items:center; gap:14px; padding:13px 20px;
    border-bottom:1px solid rgba(255,255,255,.06); transition:background .15s;
  }
  .lp-lb-row:last-child { border-bottom:none; }
  .lp-lb-row:hover { background:rgba(255,255,255,.02); }
  .lp-signin-card {
    background:rgba(17,20,38,.96); border:1px solid rgba(255,255,255,.1);
    border-radius:20px; padding:40px 36px; max-width:440px; margin:0 auto;
    backdrop-filter:blur(16px); -webkit-backdrop-filter:blur(16px);
  }
  @media (max-width:768px) {
    .lp-nav { padding:0 20px; }
    .lp-nav-link.hide-mobile { display:none; }
    .lp-signin-card { padding:28px 20px; }
    .lp-step-card { min-width:100%; }
  }
  @media (max-width:500px) {
    .lp-nav__links { gap:12px; }
  }
`;

export default function Login() {
  const navigate = useNavigate();
  const authError = new URLSearchParams(window.location.search).get('error') === 'auth_failed';

  const [authMode,   setAuthMode]   = useState('login');
  const [email,      setEmail]      = useState('');
  const [password,   setPassword]   = useState('');
  const [username,   setUsername]   = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [formError,  setFormError]  = useState('');

  const [lbGrade,   setLbGrade]   = useState('G3');
  const [lbEntries, setLbEntries] = useState([]);
  const [lbLoading, setLbLoading] = useState(true);

  function resetForm() { setEmail(''); setPassword(''); setUsername(''); setFormError(''); }

  async function handleEmailAuth(e) {
    e.preventDefault();
    setFormError('');
    setSubmitting(true);
    try {
      const isRegister = authMode === 'register';
      const body = isRegister
        ? { email, password, ...(username.trim() ? { username: username.trim() } : {}) }
        : { email, password };
      const res = await fetch(`${API}/auth/${isRegister ? 'register' : 'login'}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) { setFormError(ERROR_MSGS[data.error] ?? 'Something went wrong. Please try again.'); return; }
      sessionStorage.setItem('ranked_token', data.token);
      navigate('/dashboard', { replace: true });
    } catch {
      setFormError('Something went wrong. Check your connection.');
    } finally {
      setSubmitting(false);
    }
  }

  useEffect(() => {
    setLbLoading(true);
    fetch(`${API}/leaderboard?grade=${lbGrade}&type=time`)
      .then(r => r.json())
      .then(d => setLbEntries(Array.isArray(d) ? d.slice(0, 5) : []))
      .catch(() => setLbEntries([]))
      .finally(() => setLbLoading(false));
  }, [lbGrade]);

  useEffect(() => {
    if (authError) setTimeout(() => scrollTo('signin'), 400);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  function scrollTo(id) {
    document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' });
  }

  return (
    <>
      <style>{LANDING_CSS}</style>

      {/* Fixed animated background */}
      <div className="arena-bg">
        <div className="arena-grain" />
        <div className="arena-shapes">
          {DIAMONDS.map((d, i) => (
            <div key={i} className="shape shape--diamond" style={{ left: d.left, top: d.top, width: d.size, height: d.size, animationDuration: d.dur, animationDelay: d.delay }} />
          ))}
          {RINGS.map((r, i) => (
            <div key={i} className="shape shape--ring" style={{ left: r.left, top: r.top, width: r.size, height: r.size, animationDuration: r.dur, animationDelay: r.delay }} />
          ))}
          {SCANLINES.map((s, i) => (
            <div key={i} className="shape shape--line" style={{ top: s.top, left: s.left, width: s.width, animationDuration: s.dur, animationDelay: s.delay }} />
          ))}
        </div>
      </div>

      {/* ── Sticky Nav ─────────────────────────────────────── */}
      <nav className="lp-nav">
        <button className="lp-nav__logo" onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
          RANKED<span>EQAO</span>
        </button>
        <div className="lp-nav__links">
          <a href="#how-it-works" className="lp-nav-link hide-mobile">How It Works</a>
          <a href="#leaderboard"  className="lp-nav-link hide-mobile">Leaderboard</a>
          <a href="/about"        className="lp-nav-link hide-mobile">About</a>
          <a href="/faq"          className="lp-nav-link hide-mobile">FAQ</a>
          <button className="lp-nav-signin" onClick={() => scrollTo('signin')}>Sign In</button>
        </div>
      </nav>

      {/* ── Page ───────────────────────────────────────────── */}
      <div style={{ position: 'relative', zIndex: 1 }}>

        {/* ── HERO ─────────────────────────────────────────── */}
        <section style={{
          minHeight: '100vh', display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center',
          padding: '100px 0 80px', textAlign: 'center',
          position: 'relative', overflow: 'hidden',
        }}>
          <div className="lp-hero-orb" />

          <div className="lp-container" style={{ position: 'relative', zIndex: 1 }}>
            <p style={{
              fontFamily: "'Barlow Condensed',sans-serif", fontSize: 11, fontWeight: 700,
              letterSpacing: '0.3em', textTransform: 'uppercase', color: '#f5c518',
              marginBottom: 28, opacity: 0, animation: 'fadeUp .6s .05s ease both',
            }}>
              Ontario Standardized Tests
            </p>

            <h1 style={{
              fontFamily: "'Russo One',sans-serif",
              fontSize: 'clamp(68px,14vw,148px)',
              lineHeight: 0.9, letterSpacing: '-0.01em',
              textTransform: 'uppercase', marginBottom: 36,
            }}>
              <span className="lp-word lp-word-1" style={{ color: '#eceef8' }}>COMPETE.</span>
              <span className="lp-word lp-word-2" style={{ color: '#eceef8' }}>PRACTICE.</span>
              <span className="lp-word lp-word-3" style={{ color: '#f5c518', textShadow: '0 0 60px rgba(245,197,24,.4)' }}>DOMINATE.</span>
            </h1>

            <p style={{
              fontFamily: "'Barlow',sans-serif", fontSize: 'clamp(15px,2.4vw,19px)',
              color: '#9ba5c4', maxWidth: 560, margin: '0 auto 44px', lineHeight: 1.65,
              opacity: 0, animation: 'fadeUp .6s .6s ease both',
            }}>
              The ranked EQAO quiz platform for Ontario students. Practice Grade 3, 6, and 9 math — then go head-to-head against real opponents.
            </p>

            <div style={{
              display: 'flex', gap: 14, justifyContent: 'center', flexWrap: 'wrap',
              marginBottom: 56, opacity: 0, animation: 'fadeUp .6s .75s ease both',
            }}>
              <button
                onClick={() => scrollTo('signin')}
                style={{
                  padding: '15px 38px', background: '#f5c518', color: '#07080f',
                  border: 'none', borderRadius: 10,
                  fontFamily: "'Russo One',sans-serif", fontSize: 17,
                  letterSpacing: '0.04em', textTransform: 'uppercase', cursor: 'pointer',
                  boxShadow: '0 0 32px rgba(245,197,24,.35), 0 4px 16px rgba(0,0,0,.4)',
                  transition: 'transform .15s, box-shadow .2s',
                }}
                onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 0 52px rgba(245,197,24,.5), 0 8px 24px rgba(0,0,0,.5)'; }}
                onMouseLeave={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = '0 0 32px rgba(245,197,24,.35), 0 4px 16px rgba(0,0,0,.4)'; }}
              >
                Start Playing
              </button>
              <a
                href="#how-it-works"
                style={{
                  padding: '15px 38px', background: 'transparent', color: '#eceef8',
                  border: '1.5px solid rgba(255,255,255,.22)', borderRadius: 10,
                  fontFamily: "'Russo One',sans-serif", fontSize: 17,
                  letterSpacing: '0.04em', textTransform: 'uppercase',
                  textDecoration: 'none', display: 'inline-flex', alignItems: 'center',
                  transition: 'border-color .2s, color .2s',
                }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = 'rgba(255,255,255,.5)'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = 'rgba(255,255,255,.22)'; }}
              >
                How It Works
              </a>
            </div>

            {/* Grade badges */}
            <div style={{
              display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap',
              opacity: 0, animation: 'fadeUp .6s .9s ease both',
            }}>
              {[{ id: 'G3', label: 'Grade 3' }, { id: 'G6', label: 'Grade 6' }, { id: 'G9', label: 'Grade 9' }].map(({ id, label }) => (
                <div key={id} className="grade-badge">
                  <span className="grade-badge__rank">{id}</span>
                  <span className="grade-badge__label">{label}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Scroll hint */}
          <div style={{
            position: 'absolute', bottom: 32, left: '50%', transform: 'translateX(-50%)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
            opacity: 0, animation: 'fadeUp .6s 1.2s ease both',
          }}>
            <span style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: '#7a85a8' }}>Scroll</span>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="rgba(122,133,168,.55)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ animation: 'scrollBounce 2s ease-in-out infinite' }}>
              <polyline points="6 9 12 15 18 9" />
            </svg>
          </div>
        </section>

        {/* ── HOW IT WORKS ─────────────────────────────────── */}
        <section id="how-it-works" style={{
          padding: '100px 0',
          background: 'rgba(13,15,28,.78)',
          backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)',
        }}>
          <div className="lp-container">
            <p className="lp-eyebrow">Get Started</p>
            <h2 className="lp-section-title">How It Works</h2>

            <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}>
              {[
                {
                  num: '01',
                  icon: (
                    <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#f5c518" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" />
                      <circle cx="12" cy="7" r="4" />
                    </svg>
                  ),
                  title: 'Sign In',
                  desc: "Create a free account with Google or email. Pick your grade — G3, G6, or G9 — and you're ready to start.",
                },
                {
                  num: '02',
                  icon: (
                    <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#f5c518" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M12 20h9" />
                      <path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
                    </svg>
                  ),
                  title: 'Practice',
                  desc: 'Answer 22 EQAO-style math questions across two stages. Every question must be correct to advance — no partial credit, no shortcuts.',
                },
                {
                  num: '03',
                  icon: (
                    <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#f5c518" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" />
                      <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18" />
                      <path d="M4 22h16" />
                      <path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22" />
                      <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22" />
                      <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z" />
                    </svg>
                  ),
                  title: 'Compete',
                  desc: 'Join the ranked queue and race against a real opponent. Your ELO rises or falls on the result. Climb from Bronze all the way to Diamond.',
                },
              ].map((step, i) => (
                <div key={i} className="lp-step-card">
                  <span style={{
                    fontFamily: "'Russo One',sans-serif", fontSize: 64, lineHeight: 1,
                    color: 'rgba(245,197,24,.1)', position: 'absolute', top: 16, right: 22,
                    pointerEvents: 'none',
                  }}>
                    {step.num}
                  </span>
                  <div style={{
                    width: 52, height: 52,
                    background: 'rgba(245,197,24,.07)', border: '1px solid rgba(245,197,24,.2)',
                    borderRadius: 12, display: 'flex', alignItems: 'center', justifyContent: 'center',
                    marginBottom: 20,
                  }}>
                    {step.icon}
                  </div>
                  <h3 style={{
                    fontFamily: "'Barlow Condensed',sans-serif", fontSize: 22, fontWeight: 700,
                    letterSpacing: '0.06em', textTransform: 'uppercase', color: '#eceef8', marginBottom: 10,
                  }}>
                    {step.title}
                  </h3>
                  <p style={{ fontFamily: "'Barlow',sans-serif", fontSize: 15, color: '#7a85a8', lineHeight: 1.65 }}>
                    {step.desc}
                  </p>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* ── FEATURES ─────────────────────────────────────── */}
        <section id="features" style={{ padding: '100px 0' }}>
          <div className="lp-container">
            <p className="lp-eyebrow">The Platform</p>
            <h2 className="lp-section-title">Why Ranked EQAO?</h2>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(290px,1fr))', gap: 16 }}>
              {[
                {
                  icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#f5c518" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="2" width="14" height="20" rx="2"/><path d="M9 7h6M9 11h6M9 15h4"/></svg>,
                  title: 'Real EQAO-Style Questions',
                  desc: 'Randomized values on every attempt — same problem structure, different numbers. You can\'t just memorize answers.',
                },
                {
                  icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#f5c518" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>,
                  title: 'Live 1v1 Matchmaking',
                  desc: 'Race against real students in real time. First to correctly complete all questions wins the match and earns ELO.',
                },
                {
                  icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#f5c518" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/></svg>,
                  title: 'ELO Ranking System',
                  desc: 'Climb from Bronze through Silver, Gold, Platinum, and Diamond. Your rating reflects actual performance against real opponents.',
                },
                {
                  icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#f5c518" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
                  title: 'Best Time Leaderboard',
                  desc: 'Every second counts. Your fastest completion time is tracked separately on the global leaderboard.',
                },
                {
                  icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#f5c518" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
                  title: 'Grade-Specific Content',
                  desc: 'Separate queues, leaderboards, and ELO ratings for Grade 3, 6, and 9. Difficulty scales with each grade level.',
                },
                {
                  icon: <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#f5c518" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><polyline points="9 12 11 14 15 10"/></svg>,
                  title: '100% Free',
                  desc: 'No ads, no paywalls, no subscriptions. Ranked EQAO is completely free for every Ontario student.',
                },
              ].map((f, i) => (
                <div key={i} className="lp-feature-card">
                  <div style={{
                    width: 44, height: 44,
                    background: 'rgba(245,197,24,.07)', border: '1px solid rgba(245,197,24,.18)',
                    borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center',
                    marginBottom: 16,
                  }}>
                    {f.icon}
                  </div>
                  <h3 style={{
                    fontFamily: "'Barlow Condensed',sans-serif", fontSize: 18, fontWeight: 700,
                    letterSpacing: '0.05em', textTransform: 'uppercase', color: '#eceef8', marginBottom: 8,
                  }}>
                    {f.title}
                  </h3>
                  <p style={{ fontFamily: "'Barlow',sans-serif", fontSize: 14, color: '#7a85a8', lineHeight: 1.65 }}>
                    {f.desc}
                  </p>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* ── LEADERBOARD PREVIEW ───────────────────────────── */}
        <section id="leaderboard" style={{
          padding: '100px 0',
          background: 'rgba(13,15,28,.78)',
          backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)',
        }}>
          <div className="lp-container">
            <p className="lp-eyebrow">Rankings</p>
            <h2 className="lp-section-title">Top Players</h2>

            {/* Grade tabs */}
            <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginBottom: 28 }}>
              {['G3', 'G6', 'G9'].map(g => (
                <button
                  key={g}
                  onClick={() => setLbGrade(g)}
                  style={{
                    padding: '7px 24px',
                    background: lbGrade === g ? 'rgba(245,197,24,.12)' : 'rgba(17,20,38,.8)',
                    border: `1px solid ${lbGrade === g ? 'rgba(245,197,24,.5)' : 'rgba(255,255,255,.1)'}`,
                    borderRadius: 8,
                    fontFamily: "'Barlow Condensed',sans-serif", fontSize: 13, fontWeight: 700,
                    letterSpacing: '0.1em', textTransform: 'uppercase',
                    color: lbGrade === g ? '#f5c518' : '#7a85a8',
                    cursor: 'pointer', transition: 'all .15s',
                  }}
                >
                  {g}
                </button>
              ))}
            </div>

            <div className="lp-lb-card">
              {/* Table header */}
              <div style={{ display: 'flex', gap: 14, padding: '10px 20px', borderBottom: '1px solid rgba(255,255,255,.07)' }}>
                {['#', 'Player', 'Best Time'].map((h, i) => (
                  <span key={h} style={{
                    fontFamily: "'Barlow Condensed',sans-serif", fontSize: 10, fontWeight: 700,
                    letterSpacing: '0.16em', textTransform: 'uppercase', color: '#7a85a8',
                    minWidth: i === 0 ? 36 : undefined, textAlign: i === 0 ? 'center' : undefined,
                    flex: i === 1 ? 1 : undefined,
                  }}>{h}</span>
                ))}
              </div>

              {lbLoading ? (
                <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {[0, 1, 2, 3, 4].map(i => (
                    <div key={i} className="skel-pill" style={{ height: 44, animationDelay: `${i * 0.06}s` }} />
                  ))}
                </div>
              ) : lbEntries.length === 0 ? (
                <div style={{ padding: '48px 24px', textAlign: 'center' }}>
                  <div style={{ fontSize: 28, marginBottom: 12, opacity: 0.4 }}>🏆</div>
                  <p style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 15, color: '#7a85a8' }}>No scores yet — be the first!</p>
                </div>
              ) : (
                lbEntries.map((entry, i) => {
                  const rc = i < 3 ? RANK_COLORS[i] : '#7a85a8';
                  const playerLabel = entry.username ? `@${entry.username}` : (entry.displayName ?? 'Player');
                  const initial = playerLabel[0]?.toUpperCase() ?? '?';
                  return (
                    <div
                      key={i}
                      className="lp-lb-row"
                      style={i === 0 ? { borderLeft: '2px solid #f5c518', paddingLeft: 18 } : {}}
                    >
                      <span style={{
                        fontFamily: "'Russo One',sans-serif", fontSize: 15, color: rc,
                        textShadow: i < 3 ? `0 0 12px ${rc}60` : 'none',
                        minWidth: 36, textAlign: 'center',
                      }}>
                        {i + 1}
                      </span>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 1, minWidth: 0 }}>
                        {entry.avatarUrl
                          ? <img src={entry.avatarUrl} alt={playerLabel} referrerPolicy="no-referrer" style={{ width: 28, height: 28, borderRadius: '50%', objectFit: 'cover', flexShrink: 0, border: i < 3 ? `1.5px solid ${rc}55` : '1px solid rgba(255,255,255,.1)' }} />
                          : <div style={{ width: 28, height: 28, borderRadius: '50%', background: '#181c32', border: '1px solid rgba(255,255,255,.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: "'Russo One',sans-serif", fontSize: 11, color: '#9ba5c4', flexShrink: 0 }}>{initial}</div>
                        }
                        <span style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 15, fontWeight: 600, color: '#eceef8', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                          {playerLabel}
                        </span>
                      </div>
                      <span style={{
                        fontFamily: "'Barlow Condensed',sans-serif", fontSize: 16, fontWeight: 700,
                        letterSpacing: '0.05em', color: i === 0 ? '#f5c518' : '#eceef8',
                      }}>
                        {fmtTime(entry.bestTime)}
                      </span>
                    </div>
                  );
                })
              )}
            </div>

            <div style={{ textAlign: 'center', marginTop: 32 }}>
              <p style={{ fontFamily: "'Barlow',sans-serif", fontSize: 15, color: '#7a85a8', marginBottom: 16 }}>
                Think you can crack the top 5?
              </p>
              <button
                onClick={() => scrollTo('signin')}
                style={{
                  padding: '12px 32px',
                  background: 'rgba(245,197,24,.08)', border: '1px solid rgba(245,197,24,.35)',
                  borderRadius: 8, fontFamily: "'Barlow Condensed',sans-serif",
                  fontSize: 14, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase',
                  color: '#f5c518', cursor: 'pointer', transition: 'background .2s, border-color .2s',
                }}
                onMouseEnter={e => { e.currentTarget.style.background = 'rgba(245,197,24,.17)'; e.currentTarget.style.borderColor = 'rgba(245,197,24,.6)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'rgba(245,197,24,.08)'; e.currentTarget.style.borderColor = 'rgba(245,197,24,.35)'; }}
              >
                Sign In to Compete
              </button>
            </div>
          </div>
        </section>

        {/* ── SIGN IN ───────────────────────────────────────── */}
        <section id="signin" style={{ padding: '100px 24px 120px' }}>
          <div style={{ textAlign: 'center', marginBottom: 44 }}>
            <p className="lp-eyebrow">Join the Arena</p>
            <h2 style={{
              fontFamily: "'Russo One',sans-serif",
              fontSize: 'clamp(30px,5vw,48px)',
              textTransform: 'uppercase', letterSpacing: '0.02em', color: '#eceef8',
            }}>
              Ready to Play?
            </h2>
          </div>

          <div className="lp-signin-card">
            <div className="login__cta" style={{ marginTop: 0 }}>

              {authError && <p className="login__error">Sign-in failed — please try again.</p>}

              {/* Google button */}
              <a href={`${API}/auth/google`} className="btn-google" style={{ width: '100%', justifyContent: 'center', boxSizing: 'border-box' }}>
                <GoogleIcon />Sign in with Google
              </a>

              {/* Divider */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%' }}>
                <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,.12)' }} />
                <span style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 13, color: 'rgba(255,255,255,.35)', letterSpacing: '0.05em' }}>— or —</span>
                <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,.12)' }} />
              </div>

              {/* Mode toggle */}
              <div style={{ display: 'flex', width: '100%', background: 'rgba(255,255,255,.05)', borderRadius: 10, padding: 3, gap: 3, boxSizing: 'border-box' }}>
                {['login', 'register'].map(mode => (
                  <button
                    key={mode}
                    type="button"
                    onClick={() => { resetForm(); setAuthMode(mode); }}
                    style={{
                      flex: 1, padding: '9px 0', border: 'none', borderRadius: 8,
                      fontSize: 14, fontWeight: 600,
                      fontFamily: "'Barlow Condensed',sans-serif", letterSpacing: '0.06em',
                      cursor: 'pointer', transition: 'all .15s',
                      background: authMode === mode ? 'rgba(255,255,255,.11)' : 'transparent',
                      color: authMode === mode ? '#fff' : 'rgba(255,255,255,.4)',
                    }}
                  >
                    {mode === 'login' ? 'Sign in' : 'Create account'}
                  </button>
                ))}
              </div>

              {/* Email form */}
              <form onSubmit={handleEmailAuth} style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10 }}>
                <input type="email" required placeholder="Email address" value={email} onChange={e => setEmail(e.target.value)} style={INPUT_STYLE} autoComplete="email" />
                <input type="password" required placeholder="Password" value={password} onChange={e => setPassword(e.target.value)} style={INPUT_STYLE} autoComplete={authMode === 'login' ? 'current-password' : 'new-password'} />
                {authMode === 'register' && (
                  <input
                    type="text"
                    placeholder="Username (3–20 chars, letters/numbers/_)"
                    value={username}
                    onChange={e => setUsername(e.target.value)}
                    pattern="^[a-zA-Z0-9_]{3,20}$"
                    title="3–20 characters: letters, numbers, underscores only"
                    style={INPUT_STYLE}
                    autoComplete="username"
                  />
                )}
                <button
                  type="submit"
                  disabled={submitting}
                  style={{
                    width: '100%', padding: '13px',
                    background: '#1a73e8', color: '#fff',
                    border: 'none', borderRadius: 10, fontSize: 15, fontWeight: 700,
                    fontFamily: "'Barlow Condensed',sans-serif", letterSpacing: '0.06em',
                    cursor: submitting ? 'not-allowed' : 'pointer',
                    opacity: submitting ? 0.7 : 1, transition: 'opacity .2s',
                  }}
                >
                  {submitting ? 'Please wait…' : authMode === 'login' ? 'Sign in' : 'Create account'}
                </button>
                {formError && <p className="login__error" style={{ margin: 0 }}>{formError}</p>}
              </form>

              <p style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 12, letterSpacing: '0.05em', color: 'rgba(255,255,255,.3)', textAlign: 'center' }}>
                Free · No credit card required
              </p>
            </div>
          </div>
        </section>

        {/* ── FOOTER ───────────────────────────────────────── */}
        <footer style={{
          background: 'rgba(7,8,15,.95)',
          borderTop: '1px solid rgba(255,255,255,.07)',
          padding: '40px 24px',
        }}>
          <div className="lp-container" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18 }}>
            <span style={{ fontFamily: "'Russo One',sans-serif", fontSize: 16, letterSpacing: '0.04em', color: '#eceef8' }}>
              RANKED<span style={{ color: '#f5c518' }}>EQAO</span>
            </span>
            <div style={{ display: 'flex', gap: 28, flexWrap: 'wrap', justifyContent: 'center' }}>
              {[
                { label: 'How It Works', href: '#how-it-works' },
                { label: 'About',        href: '/about' },
                { label: 'FAQ',          href: '/faq' },
                { label: 'Sign In', href: null, onClick: () => scrollTo('signin') },
              ].map(({ label, href, onClick }) =>
                href ? (
                  <a
                    key={label} href={href}
                    style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 12, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a85a8', textDecoration: 'none', transition: 'color .2s' }}
                    onMouseEnter={e => e.currentTarget.style.color = '#eceef8'}
                    onMouseLeave={e => e.currentTarget.style.color = '#7a85a8'}
                  >
                    {label}
                  </a>
                ) : (
                  <button
                    key={label} onClick={onClick}
                    style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 12, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7a85a8', background: 'none', border: 'none', cursor: 'pointer', padding: 0, transition: 'color .2s' }}
                    onMouseEnter={e => e.currentTarget.style.color = '#eceef8'}
                    onMouseLeave={e => e.currentTarget.style.color = '#7a85a8'}
                  >
                    {label}
                  </button>
                )
              )}
            </div>
            <p style={{ fontFamily: "'Barlow',sans-serif", fontSize: 11, color: 'rgba(122,133,168,.45)', letterSpacing: '0.04em', textAlign: 'center' }}>
              Ranked EQAO — Built for Ontario students &nbsp;·&nbsp; Not affiliated with EQAO or the Ontario government.
            </p>
          </div>
        </footer>

      </div>
    </>
  );
}

function GoogleIcon() {
  return (
    <svg className="btn-google__icon" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4" />
      <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
      <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05" />
      <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
    </svg>
  );
}
