/**
 * CoinRush Auth Modal - React Component
 * Shared authentication modal for login/register across all pages
 */

const { useState, useEffect } = React;

// ============================================
// AUTH MODAL COMPONENT
// ============================================
function AuthModal({ isOpen, onClose, initialMode = 'login', onSuccess }) {
  const [mode, setMode] = useState(initialMode);
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  
  // Age verification
  const [dateOfBirth, setDateOfBirth] = useState('');
  const [country, setCountry] = useState('');
  const [termsAccepted, setTermsAccepted] = useState(false);
  const [countries, setCountries] = useState([]);
  const [showAgePopup, setShowAgePopup] = useState(false);
  
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState('');
  const [oauthProviders, setOauthProviders] = useState({ discord: true, google: true, twitter: true });
  
  const isLogin = mode === 'login';
  const ageVerified = dateOfBirth && country && termsAccepted;
  
  // Fetch countries list on mount
  useEffect(() => {
    fetch('/auth/countries')
      .then(res => res.json())
      .then(data => {
        if (data.countries) {
          setCountries(data.countries);
        }
      })
      .catch(() => {});
  }, []);
  
  // Fetch OAuth provider availability on mount
  useEffect(() => {
    fetch('/auth/oauth/providers/status')
      .then(res => res.json())
      .then(data => {
        if (data.providers) {
          setOauthProviders(data.providers);
        }
      })
      .catch(() => {});
  }, []);
  
  // Reset form when mode or open state changes
  useEffect(() => {
    if (isOpen) {
      setMode(initialMode);
      setUsername('');
      setEmail('');
      setPassword('');
      setDateOfBirth('');
      setCountry('');
      setTermsAccepted(false);
      setShowAgePopup(false);
      setError('');
      setSuccess('');
      setShowPassword(false);
    }
  }, [isOpen, initialMode]);
  
  if (!isOpen) return null;
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSuccess('');
    setLoading(true);
    
    try {
      if (isLogin) {
        const res = await fetch('/auth/login-json', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({ 
            username_or_email: username, 
            password: password 
          })
        });
        
        if (!res.ok) {
          const data = await res.json().catch(() => ({ detail: 'Login failed' }));
          throw new Error(data.detail || 'Login failed');
        }
        
        onSuccess?.();
        onClose();
        window.location.reload();
      } else {
        // Validate all required fields before submitting
        if (!dateOfBirth) {
          throw new Error('Please enter your date of birth');
        }
        if (!country) {
          throw new Error('Please select your country');
        }
        if (!termsAccepted) {
          throw new Error('You must accept the Terms of Service');
        }
        
        const res = await fetch('/auth/register', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ 
            username: username, 
            email: email, 
            password: password,
            date_of_birth: dateOfBirth,
            country: country,
            terms_accepted: termsAccepted
          })
        });
        
        if (!res.ok) {
          const data = await res.json().catch(() => ({ detail: 'Registration failed' }));
          throw new Error(data.detail || 'Registration failed');
        }
        
        const data = await res.json();
        setSuccess(data.message || 'Account created! Check your email.');
        
        setTimeout(() => {
          setMode('login');
          setSuccess('');
          setEmail('');
          setPassword('');
        }, 2500);
      }
    } catch (err) {
      setError(err.message || 'An error occurred');
    } finally {
      setLoading(false);
    }
  };
  
  const switchMode = () => {
    setMode(isLogin ? 'register' : 'login');
    setError('');
    setSuccess('');
  };
  
  return (
    <div className="auth-overlay" onClick={onClose}>
      <div className="auth-modal" onClick={(e) => e.stopPropagation()}>
        {/* Decorative Elements */}
        <div className="auth-glow auth-glow-1" />
        <div className="auth-glow auth-glow-2" />
        <div className="auth-border-glow" />
        
        {/* Close Button */}
        <button className="auth-close" onClick={onClose} type="button">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <line x1="18" y1="6" x2="6" y2="18"/>
            <line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
        
        {/* Logo/Brand */}
        <div className="auth-brand">
          <div className="auth-logo">
            <div className="auth-logo-icon">
              <span>CR</span>
            </div>
            <div className="auth-logo-text-group">
              <span className="auth-logo-title">COINRUSH</span>
              <span className="auth-logo-subtitle">CRYPTO CASINO</span>
            </div>
          </div>
        </div>
        
        {/* Mode Tabs */}
        <div className="auth-tabs">
          <button 
            type="button"
            className={`auth-tab ${isLogin ? 'active' : ''}`}
            onClick={() => { setMode('login'); setError(''); setSuccess(''); }}
          >
            Log In
          </button>
          <button 
            type="button"
            className={`auth-tab ${!isLogin ? 'active' : ''}`}
            onClick={() => { setMode('register'); setError(''); setSuccess(''); }}
          >
            Sign Up
          </button>
          <div className={`auth-tab-indicator ${!isLogin ? 'right' : ''}`} />
        </div>
        
        {/* Form */}
        <form className="auth-form" onSubmit={handleSubmit}>
          {/* Messages */}
          {error && (
            <div className="auth-message auth-message-error">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="12" cy="12" r="10"/>
                <line x1="15" y1="9" x2="9" y2="15"/>
                <line x1="9" y1="9" x2="15" y2="15"/>
              </svg>
              <span>{error}</span>
            </div>
          )}
          
          {success && (
            <div className="auth-message auth-message-success">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                <polyline points="22 4 12 14.01 9 11.01"/>
              </svg>
              <span>{success}</span>
            </div>
          )}
          
          {/* Username */}
          <div className="auth-field">
            <label className="auth-label">
              {isLogin ? 'Username or Email' : 'Username'}
            </label>
            <div className="auth-input-box">
              <input
                type="text"
                className="auth-input"
                placeholder={isLogin ? 'Enter username or email' : 'Choose a username'}
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                required
                autoComplete="username"
              />
            </div>
          </div>
          
          {/* Email (Register only) */}
          {!isLogin && (
            <div className="auth-field">
              <label className="auth-label">Email</label>
              <div className="auth-input-box">
                <input
                  type="email"
                  className="auth-input"
                  placeholder="your@email.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  autoComplete="email"
                />
              </div>
            </div>
          )}
          
          {/* Password */}
          <div className="auth-field">
            <label className="auth-label">Password</label>
            <div className="auth-input-box">
              <input
                type={showPassword ? 'text' : 'password'}
                className="auth-input"
                placeholder={isLogin ? 'Enter password' : 'Create a password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                autoComplete={isLogin ? 'current-password' : 'new-password'}
              />
              <button
                type="button"
                className="auth-eye"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/>
                    <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/>
                    <line x1="1" y1="1" x2="23" y2="23"/>
                  </svg>
                ) : (
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                    <circle cx="12" cy="12" r="3"/>
                  </svg>
                )}
              </button>
            </div>
          </div>
          
          {/* Forgot Password (Login only) */}
          {isLogin && (
            <div className="auth-forgot">
              <button type="button" className="auth-forgot-link">
                Forgot password?
              </button>
            </div>
          )}
          
          {/* Age Verification Button (Register only) */}
          {!isLogin && (
            <button
              type="button"
              className={`auth-age-btn ${ageVerified ? 'verified' : ''}`}
              onClick={() => setShowAgePopup(true)}
            >
              {ageVerified ? (
                <>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
                    <polyline points="22 4 12 14.01 9 11.01"/>
                  </svg>
                  <span>Age verified · {country}</span>
                </>
              ) : (
                <>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                  </svg>
                  <span>Verify age (18+) & accept terms</span>
                </>
              )}
            </button>
          )}
          
          {/* Submit Button */}
          <button
            type="submit"
            className="auth-submit"
            disabled={loading || (!isLogin && !ageVerified)}
          >
            {loading ? (
              <div className="auth-spinner" />
            ) : (
              <>
                <span>{isLogin ? 'Log In' : 'Create Account'}</span>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                  <line x1="5" y1="12" x2="19" y2="12"/>
                  <polyline points="12 5 19 12 12 19"/>
                </svg>
              </>
            )}
          </button>
          
          {/* Divider */}
          <div className="auth-divider">
            <span>or continue with</span>
          </div>
          
          {/* Social Login Buttons - Full Width Branded Buttons */}
          <div className="auth-oauth-buttons">
            <button 
              type="button" 
              className={`auth-oauth-btn auth-oauth-discord ${!oauthProviders.discord ? 'disabled' : ''}`}
              onClick={() => oauthProviders.discord && (window.location.href = '/auth/oauth/discord')}
              disabled={!oauthProviders.discord}
            >
              <div className="auth-oauth-icon">
                <svg viewBox="0 0 24 24" fill="currentColor">
                  <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/>
                </svg>
              </div>
              <span className="auth-oauth-text">Continue with Discord</span>
              <svg className="auth-oauth-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polyline points="9 18 15 12 9 6"/>
              </svg>
            </button>
            
            <button 
              type="button" 
              className={`auth-oauth-btn auth-oauth-google ${!oauthProviders.google ? 'disabled' : ''}`}
              onClick={() => oauthProviders.google && (window.location.href = '/auth/oauth/google')}
              disabled={!oauthProviders.google}
            >
              <div className="auth-oauth-icon">
                <svg viewBox="0 0 24 24">
                  <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>
              </div>
              <span className="auth-oauth-text">Continue with Google</span>
              <svg className="auth-oauth-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polyline points="9 18 15 12 9 6"/>
              </svg>
            </button>
            
            <button 
              type="button" 
              className={`auth-oauth-btn auth-oauth-twitter ${!oauthProviders.twitter ? 'disabled' : ''}`}
              onClick={() => oauthProviders.twitter && (window.location.href = '/auth/oauth/twitter')}
              disabled={!oauthProviders.twitter}
            >
              <div className="auth-oauth-icon">
                <svg viewBox="0 0 24 24" fill="currentColor">
                  <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
                </svg>
              </div>
              <span className="auth-oauth-text">Continue with X</span>
              <svg className="auth-oauth-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <polyline points="9 18 15 12 9 6"/>
              </svg>
            </button>
          </div>
        </form>
        
        {/* Footer */}
        <div className="auth-footer">
          <p>
            {isLogin ? "Don't have an account? " : "Already have an account? "}
            <button type="button" className="auth-switch" onClick={switchMode}>
              {isLogin ? 'Sign up' : 'Log in'}
            </button>
          </p>
        </div>
        
        {/* Age Verification Popup */}
        {showAgePopup && (
          <div className="age-popup-overlay" onClick={() => setShowAgePopup(false)}>
            <div className="age-popup" onClick={(e) => e.stopPropagation()}>
              <div className="age-popup-header">
                <h3>Age Verification</h3>
                <button className="age-popup-close" onClick={() => setShowAgePopup(false)}>
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <line x1="18" y1="6" x2="6" y2="18"/>
                    <line x1="6" y1="6" x2="18" y2="18"/>
                  </svg>
                </button>
              </div>
              
              <div className="age-popup-body">
                <div className="age-popup-field">
                  <label>Date of Birth</label>
                  <input
                    type="date"
                    value={dateOfBirth}
                    onChange={(e) => setDateOfBirth(e.target.value)}
                    max={`${new Date().getFullYear() - 18}-${String(new Date().getMonth() + 1).padStart(2, '0')}-${String(new Date().getDate()).padStart(2, '0')}`}
                  />
                </div>
                
                <div className="age-popup-field">
                  <label>Country</label>
                  <select value={country} onChange={(e) => setCountry(e.target.value)}>
                    <option value="">Select...</option>
                    {countries.map(c => (
                      <option key={c.code} value={c.code}>{c.name}</option>
                    ))}
                  </select>
                </div>
                
                <label className="age-popup-terms">
                  <input
                    type="checkbox"
                    checked={termsAccepted}
                    onChange={(e) => setTermsAccepted(e.target.checked)}
                  />
                  <span>I confirm I am 18+ and agree to <a href="/terms" target="_blank">Terms</a> & <a href="/privacy" target="_blank">Privacy</a></span>
                </label>
              </div>
              
              <button
                className="age-popup-confirm"
                disabled={!dateOfBirth || !country || !termsAccepted}
                onClick={() => setShowAgePopup(false)}
              >
                Confirm
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// Export for use across pages
window.AuthModal = AuthModal;
