/**
 * LoginApp.jsx — CrowdCue login + sign up (single page)
 */

const { useState, useEffect, useRef } = React;

const C = {
  bg:        "#0D0B1F",
  surf2:     "#1A1735",
  border:    "#252245",
  purple:    "#7B61FF",
  white:     "#FFFFFF",
  muted:     "#7A779A",
  muted2:    "#4A4870",
  red:       "#EF4444",
  redBg:     "#200808",
  redBorder: "#6B1A1A",
  green:     "#22C55E",
};

const inputStyle = {
  width: "100%", background: C.surf2, border: `1.5px solid ${C.border}`,
  borderRadius: 14, padding: 14, fontSize: 15, color: C.white,
  outline: "none", marginBottom: 10, display: "block",
};

function PasswordStrength({ password }) {
  if (!password) return null;
  const len    = password.length >= 8;
  const hasNum = /\d/.test(password);
  const hasMix = /[a-z]/.test(password) && /[A-Z]/.test(password);
  const score  = [len, hasNum, hasMix].filter(Boolean).length;
  const labels = ['', 'Weak', 'Fair', 'Strong'];
  const colors = ['', C.red, '#F59E0B', C.green];
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: -4, marginBottom: 8 }}>
      {[1, 2, 3].map(i => (
        <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i <= score ? colors[score] : C.muted2, transition: "background 0.2s" }} />
      ))}
      <span style={{ fontSize: 11, color: colors[score] || C.muted2, minWidth: 36 }}>{labels[score]}</span>
    </div>
  );
}

function LoginApp() {
  const [mode, setMode]           = useState('login'); // 'login' | 'signup'
  // Shared
  const [email, setEmail]         = useState('');
  const [password, setPassword]   = useState('');
  const [error, setError]         = useState(null);
  const [loading, setLoading]     = useState(false);
  // Sign-up only
  const [name, setName]           = useState('');
  const [referralCode, setReferralCode] = useState(null);
  const [referrerName, setReferrerName] = useState(null);

  const firstRef = useRef(null);

  useEffect(() => {
    if (sessionStorage.getItem('crowdcue_token')) {
      window.location.href = '/dashboard';
    }
    // Capture ?ref= and pre-select sign-up mode
    const params = new URLSearchParams(window.location.search);
    const ref    = params.get('ref');
    if (ref) {
      setReferralCode(ref);
      setMode('signup');
      fetch(`/api/v1/performers/${encodeURIComponent(ref)}`)
        .then(r => r.ok ? r.json() : null)
        .then(data => { if (data?.performer?.display_name) setReferrerName(data.performer.display_name); })
        .catch(() => {});
    }
  }, []);

  // Focus first field whenever mode changes
  useEffect(() => {
    setTimeout(() => firstRef.current?.focus(), 50);
    setError(null);
  }, [mode]);

  function switchMode(m) {
    setMode(m);
    setError(null);
    setEmail('');
    setPassword('');
    setName('');
  }

  async function handleLogin(e) {
    e.preventDefault();
    if (!email.trim() || !password || loading) return;
    setLoading(true); setError(null);
    try {
      const res  = await fetch('/api/v1/auth/login', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim(), password }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.message || 'Login failed'); setLoading(false); return; }
      sessionStorage.setItem('crowdcue_token', data.access_token);
      const next = new URLSearchParams(window.location.search).get('next');
      window.location.href = next || '/dashboard';
    } catch {
      setError('Could not reach the server. Try again.');
      setLoading(false);
    }
  }

  async function handleSignup(e) {
    e.preventDefault();
    if (!name.trim() || !email.trim() || password.length < 8 || loading) return;
    setLoading(true); setError(null);
    try {
      const res  = await fetch('/api/v1/auth/register', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.trim(), email: email.trim(), password,
          referral_code: referralCode || undefined,
        }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.message || 'Sign up failed'); setLoading(false); return; }
      sessionStorage.setItem('crowdcue_token', data.access_token);
      const next = new URLSearchParams(window.location.search).get('next');
      window.location.href = next || '/dashboard';
    } catch {
      setError('Could not reach the server. Try again.');
      setLoading(false);
    }
  }

  const loginReady  = email.trim() && password.length >= 1;
  const signupReady = name.trim() && email.trim() && password.length >= 8;

  return (
    <div style={{
      background: C.bg, minHeight: "100vh",
      display: "flex", alignItems: "center", justifyContent: "center",
      fontFamily: "'Inter', -apple-system, sans-serif", color: C.white,
    }}>
      <style>{`* { margin:0; padding:0; box-sizing:border-box; } input::placeholder { color: #4A4870; } input { color-scheme: dark; }`}</style>

      <div style={{ width: "100%", maxWidth: 380, padding: "0 24px" }}>

        {/* Logo */}
        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <div style={{ fontSize: 28, fontWeight: 800, marginBottom: 6 }}>
            Crowd<span style={{ color: C.purple }}>Cue</span>
          </div>
          <div style={{ fontSize: 13, color: C.muted }}>Performer Dashboard</div>
        </div>

        {/* Tab toggle */}
        <div style={{ display: "flex", background: C.surf2, border: `1px solid ${C.border}`, borderRadius: 14, padding: 4, marginBottom: 24 }}>
          {['login', 'signup'].map(m => (
            <button key={m} onClick={() => switchMode(m)} style={{
              flex: 1, padding: "10px", border: "none", borderRadius: 11,
              background: mode === m ? C.purple : "none",
              color: mode === m ? C.white : C.muted,
              fontSize: 13, fontWeight: mode === m ? 700 : 500,
              cursor: "pointer", transition: "background 0.15s, color 0.15s",
            }}>
              {m === 'login' ? 'Log In' : 'Sign Up'}
            </button>
          ))}
        </div>

        {/* Referral banner (sign-up mode only) */}
        {mode === 'signup' && referralCode && (
          <div style={{
            textAlign: "center", marginBottom: 16,
            background: "rgba(34,197,94,0.1)", border: `1px solid rgba(34,197,94,0.3)`,
            borderRadius: 10, padding: "10px 14px", fontSize: 12, color: C.green,
          }}>
            🎸 {referrerName ? `${referrerName} invited you` : "You were referred"} — enjoy a <strong>45-day free trial</strong>
          </div>
        )}

        {/* Trial badge (sign-up, no referral) */}
        {mode === 'signup' && !referralCode && (
          <div style={{
            textAlign: "center", marginBottom: 16,
            background: "rgba(123,97,255,0.12)", border: `1px solid rgba(123,97,255,0.3)`,
            borderRadius: 10, padding: "8px 14px", fontSize: 12, color: C.purple,
          }}>
            ✦ 30-day free trial — no credit card required
          </div>
        )}

        {/* ── Login form ── */}
        {mode === 'login' && (
          <form onSubmit={handleLogin}>
            <input
              ref={firstRef}
              type="email" value={email} onChange={e => setEmail(e.target.value)}
              placeholder="Email address" autoComplete="email"
              style={inputStyle}
            />
            <input
              type="password" value={password} onChange={e => setPassword(e.target.value)}
              placeholder="Password" autoComplete="current-password"
              style={inputStyle}
            />
            {error && <div style={{ background: C.redBg, border: `1px solid ${C.redBorder}`, borderRadius: 12, padding: "10px 14px", marginBottom: 10, fontSize: 13, color: C.red }}>{error}</div>}
            <button type="submit" disabled={!loginReady || loading} style={{
              width: "100%", padding: 15, border: "none", borderRadius: 14,
              fontSize: 15, fontWeight: 700,
              background: loginReady ? C.purple : C.surf2,
              color: loginReady ? C.white : C.muted,
              cursor: loginReady ? "pointer" : "not-allowed",
            }}>
              {loading ? "Logging in…" : "Log In"}
            </button>
          </form>
        )}

        {/* ── Sign-up form ── */}
        {mode === 'signup' && (
          <form onSubmit={handleSignup}>
            <input
              ref={firstRef}
              type="text" value={name} onChange={e => setName(e.target.value)}
              placeholder="Your name" autoComplete="name"
              style={inputStyle}
            />
            <input
              type="email" value={email} onChange={e => setEmail(e.target.value)}
              placeholder="Email address" autoComplete="email"
              style={inputStyle}
            />
            <input
              type="password" value={password} onChange={e => setPassword(e.target.value)}
              placeholder="Password (8+ characters)" autoComplete="new-password"
              style={{ ...inputStyle, marginBottom: 2 }}
            />
            <PasswordStrength password={password} />
            {error && <div style={{ background: C.redBg, border: `1px solid ${C.redBorder}`, borderRadius: 12, padding: "10px 14px", marginBottom: 10, fontSize: 13, color: C.red }}>{error}</div>}
            <button type="submit" disabled={!signupReady || loading} style={{
              width: "100%", padding: 15, border: "none", borderRadius: 14,
              fontSize: 15, fontWeight: 700,
              background: signupReady ? C.purple : C.surf2,
              color: signupReady ? C.white : C.muted,
              cursor: signupReady ? "pointer" : "not-allowed",
            }}>
              {loading ? "Creating account…" : "Create Account"}
            </button>
          </form>
        )}

        <div style={{ textAlign: "center", marginTop: 24, fontSize: 11, color: C.muted2 }}>
          Powered by CrowdCue
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<LoginApp />);
