import React, { useState } from 'react'
import { LoginBox } from './LoginBox'
import { ResetPasswordBox } from './ResetPasswordBox'
import {
  validatePassword,
  createPasswordValidator,
  getPasswordStrength,
  DEFAULT_PASSWORD_CONFIG
} from './validations'
import { ExampleTemplate } from '../../html/ExampleTemplate'

export default {
  title: 'Widgets/Login',
}

/**
 * LoginBox Básico
 */
export const LoginBoxBasic = () => {
  const [state, setState] = useState({ loading: false, message: '', success: false })

  const handleLogin = (user, password) => {
    setState({ loading: true, message: '', success: false })

    setTimeout(() => {
      if (user === 'admin' && password === 'admin') {
        setState({ loading: false, message: '', success: true })
      } else {
        setState({ loading: false, message: 'Usuario o contraseña incorrectos', success: false })
      }
    }, 1500)
  }

  const reset = () => setState({ loading: false, message: '', success: false })

  return (
    <div style={{ padding: '20px' }}>
      <h2 style={{ marginBottom: '2rem' }}>🔐 LoginBox</h2>

      <ExampleTemplate
        title="LoginBox Básico"
        description="Componente de login con campos de usuario y contraseña. Soporta estados de carga y mensajes de error. Usa 'admin/admin' para probar login exitoso."
        code={`const [state, setState] = useState({ loading: false, message: '' })

const handleLogin = (user, password) => {
  setState({ loading: true, message: '' })

  // Simular autenticación
  setTimeout(() => {
    if (user === 'admin' && password === 'admin') {
      setState({ loading: false, message: '' })
      // Redirigir o mostrar contenido
    } else {
      setState({ loading: false, message: 'Usuario o contraseña incorrectos' })
    }
  }, 1500)
}

<LoginBox
  userLabel="Usuario"
  passwordLabel="Contraseña"
  loginLabel="Iniciar Sesión"
  onOK={handleLogin}
  loading={state.loading}
  message={state.message}
/>`}
      >
        <div style={{ maxWidth: '400px' }}>
          {state.success ? (
            <div style={{ padding: '2rem', background: '#e8f5e9', borderRadius: '8px', textAlign: 'center' }}>
              <span style={{ fontSize: '3rem' }}>✅</span>
              <h3>¡Login Exitoso!</h3>
              <p>Bienvenido, admin</p>
              <button onClick={reset} style={{ marginTop: '1rem', padding: '0.5rem 1rem', cursor: 'pointer' }}>
                Reiniciar
              </button>
            </div>
          ) : (
            <LoginBox
              userLabel="Usuario"
              passwordLabel="Contraseña"
              loginLabel="Iniciar Sesión"
              onOK={handleLogin}
              loading={state.loading}
              message={state.message}
            />
          )}
        </div>
      </ExampleTemplate>
    </div>
  )
}

/**
 * LoginBox con valores predefinidos
 */
export const LoginBoxPrefilled = () => (
  <div style={{ padding: '20px' }}>
    <h2 style={{ marginBottom: '2rem' }}>📝 LoginBox con Valores</h2>

    <ExampleTemplate
      title="Campos Pre-rellenados"
      description="LoginBox puede inicializarse con valores usando 'userValue' y 'passwordValue'. Útil para desarrollo o 'recordar usuario'."
      code={`<LoginBox
  userLabel="Email"
  userValue="usuario@ejemplo.com"
  passwordLabel="Password"
  passwordValue="password123"
  loginLabel="Sign In"
  onOK={(user, pass) => console.log({ user, pass })}
/>`}
    >
      <div style={{ maxWidth: '400px' }}>
        <LoginBox
          userLabel="Email"
          userValue="usuario@ejemplo.com"
          passwordLabel="Password"
          passwordValue="password123"
          loginLabel="Sign In"
          onOK={(user, pass) => alert(`Login: ${user}`)}
        />
      </div>
    </ExampleTemplate>
  </div>
)

/**
 * LoginBox con children
 */
export const LoginBoxWithChildren = () => (
  <div style={{ padding: '20px' }}>
    <h2 style={{ marginBottom: '2rem' }}>🔗 LoginBox con Acciones Extra</h2>

    <ExampleTemplate
      title="Children para Enlaces Adicionales"
      description="El LoginBox acepta children que se renderizan después del botón de login. Ideal para 'Olvidé mi contraseña' o 'Registrarse'."
      code={`<LoginBox
  userLabel="Usuario"
  passwordLabel="Contraseña"
  loginLabel="Entrar"
  onOK={handleLogin}
>
  <button className="forgot-button" onClick={() => alert('Recuperar')}>
    ¿Olvidaste tu contraseña?
  </button>
  <p>¿No tienes cuenta? <a href="#">Regístrate</a></p>
</LoginBox>`}
    >
      <div style={{ maxWidth: '400px' }}>
        <LoginBox
          userLabel="Usuario"
          passwordLabel="Contraseña"
          loginLabel="Entrar"
          onOK={(u, p) => alert(`Login: ${u}`)}
        >
          <button
            className="forgot-button"
            style={{
              background: 'none', border: 'none', color: 'var(--primary-color, #2196f3)',
              cursor: 'pointer', padding: '0.5rem 0', fontSize: '0.875rem'
            }}
            onClick={() => alert('Abrir diálogo de recuperación')}
          >
            ¿Olvidaste tu contraseña?
          </button>
        </LoginBox>
      </div>
    </ExampleTemplate>
  </div>
)

/**
 * Estados de LoginBox
 */
export const LoginBoxStates = () => (
  <div style={{ padding: '20px' }}>
    <h2 style={{ marginBottom: '2rem' }}>⚡ Estados del LoginBox</h2>

    <ExampleTemplate
      title="Estado Normal"
      description="Estado inicial del LoginBox sin carga ni mensajes de error."
      code={`<LoginBox
  userLabel="User"
  passwordLabel="Password"
  loginLabel="Log In"
  onOK={handleLogin}
  loading={false}
  message=""
/>`}
    >
      <div style={{ maxWidth: '400px' }}>
        <LoginBox
          userLabel="User"
          passwordLabel="Password"
          loginLabel="Log In"
          onOK={() => {}}
          loading={false}
        />
      </div>
    </ExampleTemplate>

    <ExampleTemplate
      title="Estado de Carga"
      description="Durante la autenticación, el botón se reemplaza por un spinner animado. El usuario no puede interactuar."
      code={`<LoginBox
  userLabel="User"
  passwordLabel="Password"
  loginLabel="Log In"
  onOK={handleLogin}
  loading={true}  // ← Activa el spinner
/>`}
    >
      <div style={{ maxWidth: '400px' }}>
        <LoginBox
          userLabel="User"
          passwordLabel="Password"
          loginLabel="Log In"
          onOK={() => {}}
          loading={true}
        />
      </div>
    </ExampleTemplate>

    <ExampleTemplate
      title="Estado de Error"
      description="Cuando la autenticación falla, se muestra un mensaje de error debajo del formulario."
      code={`<LoginBox
  userLabel="User"
  passwordLabel="Password"
  loginLabel="Log In"
  onOK={handleLogin}
  loading={false}
  message="Usuario o contraseña incorrectos"  // ← Mensaje de error
/>`}
    >
      <div style={{ maxWidth: '400px' }}>
        <LoginBox
          userLabel="User"
          passwordLabel="Password"
          loginLabel="Log In"
          onOK={() => {}}
          loading={false}
          message="Usuario o contraseña incorrectos"
        />
      </div>
    </ExampleTemplate>
  </div>
)

/**
 * ResetPasswordBox
 */
export const ResetPassword = () => {
  const [result, setResult] = useState(null)

  const handleReset = (form) => {
    console.log('Reset password form:', form)
    setResult(form)
  }

  return (
    <div style={{ padding: '20px' }}>
      <h2 style={{ marginBottom: '2rem' }}>🔑 ResetPasswordBox</h2>

      <ExampleTemplate
        title="Formulario de Reset de Contraseña"
        description="Componente para cambiar contraseña con validaciones integradas: longitud mínima 15 caracteres, mayúsculas, minúsculas, números y caracteres especiales."
        code={`<ResetPasswordBox
  userRequired={false}      // No pedir usuario
  oldPwdRequired={false}    // No pedir contraseña actual
  onOK={(form) => {
    console.log(form)
    // form = { user, oldPassword, password1, password2 }
  }}
>
  {/* Contenido opcional entre los campos */}
  <div className="password-requirements">
    <p>La contraseña debe contener:</p>
    <ul>
      <li>Al menos 15 caracteres</li>
      <li>Una mayúscula y una minúscula</li>
      <li>Un número</li>
      <li>Un carácter especial</li>
    </ul>
  </div>
</ResetPasswordBox>`}
      >
        <div style={{ maxWidth: '450px' }}>
          <ResetPasswordBox
            userRequired={false}
            oldPwdRequired={false}
            onOK={handleReset}
          >
            <div style={{ padding: '0.5rem', background: '#fff3e0', borderRadius: '4px', fontSize: '0.85rem', margin: '0.5rem 0' }}>
              <strong>Requisitos:</strong> 15+ caracteres, mayúscula, minúscula, número, carácter especial
            </div>
          </ResetPasswordBox>
          {result && (
            <div style={{ marginTop: '1rem', padding: '1rem', background: '#e8f5e9', borderRadius: '4px', fontSize: '0.85rem' }}>
              <strong>✅ Resultado:</strong>
              <pre style={{ margin: '0.5rem 0 0 0' }}>{JSON.stringify(result, null, 2)}</pre>
            </div>
          )}
        </div>
      </ExampleTemplate>
    </div>
  )
}

/**
 * ResetPasswordBox con opciones
 */
export const ResetPasswordOptions = () => (
  <div style={{ padding: '20px' }}>
    <h2 style={{ marginBottom: '2rem' }}>⚙️ Opciones de ResetPasswordBox</h2>

    <ExampleTemplate
      title="Con Usuario Requerido"
      description="Cuando userRequired=true, se muestra un campo adicional para el nombre de usuario."
      code={`<ResetPasswordBox
  userRequired={true}       // ← Mostrar campo de usuario
  oldPwdRequired={false}
  onOK={handleReset}
/>`}
    >
      <div style={{ maxWidth: '450px' }}>
        <ResetPasswordBox
          userRequired={true}
          oldPwdRequired={false}
          onOK={(form) => alert(JSON.stringify(form))}
        />
      </div>
    </ExampleTemplate>

    <ExampleTemplate
      title="Con Contraseña Actual Requerida"
      description="Cuando oldPwdRequired=true, el usuario debe ingresar su contraseña actual antes de cambiarla."
      code={`<ResetPasswordBox
  userRequired={false}
  oldPwdRequired={true}     // ← Requiere contraseña actual
  onOK={handleReset}
/>`}
    >
      <div style={{ maxWidth: '450px' }}>
        <ResetPasswordBox
          userRequired={false}
          oldPwdRequired={true}
          onOK={(form) => alert(JSON.stringify(form))}
        />
      </div>
    </ExampleTemplate>

    <ExampleTemplate
      title="Formulario Completo"
      description="Ambas opciones activadas: usuario + contraseña actual + nueva contraseña + confirmación."
      code={`<ResetPasswordBox
  userRequired={true}       // ← Usuario
  oldPwdRequired={true}     // ← Contraseña actual
  onOK={handleReset}
/>`}
    >
      <div style={{ maxWidth: '450px' }}>
        <ResetPasswordBox
          userRequired={true}
          oldPwdRequired={true}
          onOK={(form) => alert(JSON.stringify(form))}
        />
      </div>
    </ExampleTemplate>
  </div>
)


/**
 * Validación de Contraseña
 */
export const PasswordValidation = () => {
  const [password, setPassword] = useState('')
  const strength = getPasswordStrength(password)

  const examples = [
    { pwd: 'abc', desc: 'Muy corta' },
    { pwd: 'abcdefghijklmno', desc: 'Sin mayúscula' },
    { pwd: 'ABCDEFGHIJKLMNO', desc: 'Sin minúscula' },
    { pwd: 'Abcdefghijklmno', desc: 'Sin número' },
    { pwd: 'Abcdefghijklmn1', desc: 'Sin carácter especial' },
    { pwd: 'Abcdefghijklmn1!', desc: '✅ Válida' },
  ]

  const strengthColors = {
    0: '#ff4444', 1: '#ff8844', 2: '#ffbb33',
    3: '#99cc00', 4: '#33b5e5', 5: '#00C851'
  }

  return (
    <div style={{ padding: '20px' }}>
      <h2 style={{ marginBottom: '2rem' }}>✔️ Validación de Contraseña</h2>

      <ExampleTemplate
        title="Función validatePassword"
        description="La función validatePassword verifica que la contraseña cumpla con los requisitos de seguridad. Ahora es configurable y exporta validaciones individuales."
        code={`import { validatePassword, createPasswordValidator, getPasswordStrength } from './validations'

// Validación con configuración por defecto (15-50 chars)
const [isValid, error] = validatePassword('Mi.Contraseña.Segura.123')

// Validación con configuración personalizada
const [isValid2, error2] = validatePassword('MyPass123!', {
  minLength: 8,
  maxLength: 100,
  requireSpecialChar: true
})

// Crear validador reutilizable
const simpleValidator = createPasswordValidator({
  minLength: 8,
  requireSpecialChar: false
})
const [valid, err] = simpleValidator('MyPassword123')

// Obtener fortaleza de contraseña
const { score, label, checks } = getPasswordStrength('MyPass')
// score: 0-5, label: "Weak", checks: { length, uppercase, ... }`}
      >
        <div style={{ display: 'flex', gap: '2rem', flexWrap: 'wrap' }}>
          <div style={{ flex: '1 1 300px' }}>
            <h4 style={{ marginTop: 0 }}>Probar Contraseña en Tiempo Real</h4>
            <input
              type="text"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Escribe una contraseña..."
              style={{ width: '100%', padding: '0.75rem', marginBottom: '0.5rem', borderRadius: '4px', border: '1px solid #ccc' }}
            />

            {/* Strength bar */}
            <div style={{ display: 'flex', gap: '4px', marginBottom: '0.5rem' }}>
              {[0, 1, 2, 3, 4, 5].map(i => (
                <div
                  key={i}
                  style={{
                    flex: 1,
                    height: '6px',
                    borderRadius: '3px',
                    background: i <= strength.score ? strengthColors[strength.score] : '#e0e0e0'
                  }}
                />
              ))}
            </div>
            <div style={{ fontSize: '0.85rem', color: strengthColors[strength.score], fontWeight: 500 }}>
              Fortaleza: {strength.label} ({strength.score}/5)
            </div>

            {/* Checks */}
            <div style={{ marginTop: '1rem', fontSize: '0.85rem' }}>
              <div style={{ color: strength.checks.length ? 'green' : '#999' }}>
                {strength.checks.length ? '✓' : '○'} Mínimo 8 caracteres
              </div>
              <div style={{ color: strength.checks.lengthStrong ? 'green' : '#999' }}>
                {strength.checks.lengthStrong ? '✓' : '○'} 15+ caracteres (recomendado)
              </div>
              <div style={{ color: strength.checks.uppercase ? 'green' : '#999' }}>
                {strength.checks.uppercase ? '✓' : '○'} Mayúscula
              </div>
              <div style={{ color: strength.checks.lowercase ? 'green' : '#999' }}>
                {strength.checks.lowercase ? '✓' : '○'} Minúscula
              </div>
              <div style={{ color: strength.checks.number ? 'green' : '#999' }}>
                {strength.checks.number ? '✓' : '○'} Número
              </div>
              <div style={{ color: strength.checks.special ? 'green' : '#999' }}>
                {strength.checks.special ? '✓' : '○'} Carácter especial
              </div>
            </div>
          </div>
          <div style={{ flex: '1 1 300px' }}>
            <h4 style={{ marginTop: 0 }}>Ejemplos con Validación Estricta</h4>
            <table style={{ width: '100%', fontSize: '0.85rem', borderCollapse: 'collapse' }}>
              <tbody>
                {examples.map((ex, i) => {
                  const [valid] = validatePassword(ex.pwd)
                  return (
                    <tr key={i} style={{ borderBottom: '1px solid #eee' }}>
                      <td style={{ padding: '0.5rem 0', fontFamily: 'monospace' }}>{ex.pwd}</td>
                      <td style={{ padding: '0.5rem', color: valid ? 'green' : '#666' }}>{ex.desc}</td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </div>
      </ExampleTemplate>
    </div>
  )
}

/**
 * Validador Personalizado
 */
export const CustomValidator = () => {
  const [password, setPassword] = useState('')

  // Validador simple: mínimo 8 caracteres, sin caracteres especiales requeridos
  const simpleValidator = createPasswordValidator({
    minLength: 8,
    maxLength: 100,
    requireSpecialChar: false
  })

  const [isValid, error] = simpleValidator(password)

  return (
    <div style={{ padding: '20px' }}>
      <h2 style={{ marginBottom: '2rem' }}>🔧 Validador Personalizado</h2>

      <ExampleTemplate
        title="createPasswordValidator"
        description="Crea validadores con configuración personalizada usando createPasswordValidator. Útil para diferentes niveles de seguridad."
        code={`import { createPasswordValidator } from './validations'

// Validador simple (para apps internas)
const simpleValidator = createPasswordValidator({
  minLength: 8,
  requireSpecialChar: false
})

// Validador estricto (para banca)
const strictValidator = createPasswordValidator({
  minLength: 20,
  requireSpecialChar: true,
  specialChars: '!@#$%^&*'
})

// Usar en ResetPasswordBox
<ResetPasswordBox
  validator={simpleValidator}
  onOK={handleReset}
/>`}
      >
        <div style={{ maxWidth: '450px' }}>
          <h4 style={{ marginTop: 0 }}>Validador Simple (mín. 8 chars, sin especiales)</h4>
          <input
            type="text"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Probar validador simple..."
            style={{ width: '100%', padding: '0.75rem', marginBottom: '0.5rem', borderRadius: '4px', border: '1px solid #ccc' }}
          />
          <div style={{
            padding: '0.75rem',
            background: !password ? '#f5f5f5' : isValid ? '#e8f5e9' : '#ffebee',
            borderRadius: '4px',
            fontSize: '0.9rem'
          }}>
            {!password ? 'Escribe una contraseña...' : isValid ? '✅ Válida' : `❌ ${error}`}
          </div>

          <div style={{ marginTop: '1rem', padding: '1rem', background: '#fff3e0', borderRadius: '4px', fontSize: '0.85rem' }}>
            <strong>Config usada:</strong>
            <pre style={{ margin: '0.5rem 0 0 0', fontSize: '0.8rem' }}>
{`{
  minLength: 8,
  maxLength: 100,
  requireSpecialChar: false
}`}
            </pre>
          </div>
        </div>
      </ExampleTemplate>
    </div>
  )
}

/**
 * Simulación de Login Realista
 * Incluye todas las casuísticas de una aplicación web moderna
 */
export const RealWorldLoginSimulation = () => {
  // Estados de la aplicación
  const [view, setView] = useState('login') // login | register | forgot | reset | verify2fa | locked | success
  const [loading, setLoading] = useState(false)
  const [message, setMessage] = useState({ type: '', text: '' })
  const [rememberMe, setRememberMe] = useState(false)
  const [loginAttempts, setLoginAttempts] = useState(0)
  const [lockoutTime, setLockoutTime] = useState(null)
  const [verificationCode, setVerificationCode] = useState('')
  const [pendingUser, setPendingUser] = useState(null)
  const [forgotEmail, setForgotEmail] = useState('')
  const [lockoutRemaining, setLockoutRemaining] = useState(0)

  // Base de datos simulada de usuarios
  const users = {
    'admin@example.com': { password: 'Admin123!secure', name: 'Administrador', requires2FA: false, locked: false },
    'user@example.com': { password: 'User1234!secure', name: 'Usuario Normal', requires2FA: false, locked: false },
    '2fa@example.com': { password: '2FA12345!secure', name: 'Usuario 2FA', requires2FA: true, locked: false },
    'locked@example.com': { password: 'Locked123!secure', name: 'Usuario Bloqueado', requires2FA: false, locked: true },
  }

  // Verificar si está bloqueado por intentos
  const isLockedOut = () => {
    if (!lockoutTime) return false
    const remaining = Math.ceil((lockoutTime - Date.now()) / 1000)
    return remaining > 0
  }

  const getLockoutRemaining = () => {
    if (!lockoutTime) return 0
    return Math.max(0, Math.ceil((lockoutTime - Date.now()) / 1000))
  }

  // Simular login
  const handleLogin = (email, password) => {
    setMessage({ type: '', text: '' })

    // Verificar bloqueo por intentos
    if (isLockedOut()) {
      setMessage({ type: 'error', text: `Cuenta bloqueada temporalmente. Intente en ${getLockoutRemaining()} segundos.` })
      return
    }

    setLoading(true)

    setTimeout(() => {
      const user = users[email.toLowerCase()]

      // Usuario no existe
      if (!user) {
        handleFailedAttempt()
        setMessage({ type: 'error', text: 'Credenciales incorrectas' })
        setLoading(false)
        return
      }

      // Contraseña incorrecta
      if (user.password !== password) {
        handleFailedAttempt()
        setMessage({ type: 'error', text: 'Credenciales incorrectas' })
        setLoading(false)
        return
      }

      // Usuario bloqueado permanentemente
      if (user.locked) {
        setMessage({ type: 'error', text: 'Esta cuenta ha sido bloqueada. Contacte con soporte.' })
        setLoading(false)
        return
      }

      // Requiere 2FA
      if (user.requires2FA) {
        setPendingUser({ email, ...user })
        setMessage({ type: 'info', text: 'Código de verificación enviado a su email' })
        setView('verify2fa')
        setLoading(false)
        return
      }

      // Login exitoso
      setLoginAttempts(0)
      setPendingUser({ email, ...user })
      setView('success')
      setLoading(false)
    }, 1500)
  }

  const handleFailedAttempt = () => {
    const attempts = loginAttempts + 1
    setLoginAttempts(attempts)

    if (attempts >= 5) {
      // Bloquear por 30 segundos
      setLockoutTime(Date.now() + 30000)
      setView('locked')
      setTimeout(() => {
        setView('login')
        setLoginAttempts(0)
        setLockoutTime(null)
      }, 30000)
    }
  }

  // Simular verificación 2FA
  const handleVerify2FA = () => {
    setLoading(true)
    setMessage({ type: '', text: '' })

    setTimeout(() => {
      if (verificationCode === '123456') {
        setView('success')
      } else {
        setMessage({ type: 'error', text: 'Código incorrecto' })
      }
      setLoading(false)
    }, 1000)
  }

  // Simular envío de email de recuperación
  const handleForgotPassword = (email) => {
    setLoading(true)
    setMessage({ type: '', text: '' })

    setTimeout(() => {
      // Siempre mostrar éxito para no revelar si el email existe
      setMessage({ type: 'success', text: 'Si el email existe, recibirá instrucciones para restablecer su contraseña.' })
      setLoading(false)
    }, 1500)
  }

  // Simular reset de contraseña
  const handleResetPassword = (form) => {
    setLoading(true)
    setMessage({ type: '', text: '' })

    setTimeout(() => {
      setMessage({ type: 'success', text: '¡Contraseña actualizada correctamente!' })
      setLoading(false)
      setTimeout(() => setView('login'), 2000)
    }, 1500)
  }

  // Simular registro
  const handleRegister = (form) => {
    setLoading(true)
    setMessage({ type: '', text: '' })

    setTimeout(() => {
      if (users[form.user?.toLowerCase()]) {
        setMessage({ type: 'error', text: 'Este email ya está registrado' })
        setLoading(false)
        return
      }
      setMessage({ type: 'success', text: '¡Registro exitoso! Revise su email para activar la cuenta.' })
      setLoading(false)
      setTimeout(() => setView('login'), 3000)
    }, 1500)
  }

  // Estilos comunes
  const containerStyle = {
    maxWidth: '420px',
    margin: '0 auto',
    padding: '2rem',
    background: 'white',
    borderRadius: '12px',
    boxShadow: '0 4px 20px rgba(0,0,0,0.1)'
  }

  const linkStyle = {
    color: '#1976d2',
    cursor: 'pointer',
    textDecoration: 'none',
    fontSize: '0.9rem'
  }

  const messageStyle = (type) => ({
    padding: '0.75rem 1rem',
    borderRadius: '6px',
    marginBottom: '1rem',
    fontSize: '0.9rem',
    background: type === 'error' ? '#ffebee' : type === 'success' ? '#e8f5e9' : '#e3f2fd',
    color: type === 'error' ? '#c62828' : type === 'success' ? '#2e7d32' : '#1565c0',
    border: `1px solid ${type === 'error' ? '#ef9a9a' : type === 'success' ? '#a5d6a7' : '#90caf9'}`
  })

  const socialButtonStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '0.5rem',
    width: '100%',
    padding: '0.75rem',
    border: '1px solid #ddd',
    borderRadius: '6px',
    background: 'white',
    cursor: 'pointer',
    fontSize: '0.9rem',
    marginBottom: '0.5rem',
    transition: 'background 0.2s'
  }

  // Vista: Login
  const renderLogin = () => (
    <div style={containerStyle}>
      <h2 style={{ textAlign: 'center', marginBottom: '0.5rem', color: '#333' }}>Bienvenido</h2>
      <p style={{ textAlign: 'center', marginBottom: '1.5rem', color: '#666', fontSize: '0.9rem' }}>
        Inicia sesión para continuar
      </p>

      {message.text && <div style={messageStyle(message.type)}>{message.text}</div>}

      {/* Login social */}
      <button
        style={socialButtonStyle}
        onClick={() => setMessage({ type: 'info', text: 'Login social simulado - use credenciales normales' })}
      >
        <span style={{ fontSize: '1.2rem' }}>G</span> Continuar con Google
      </button>
      <button
        style={socialButtonStyle}
        onClick={() => setMessage({ type: 'info', text: 'Login social simulado - use credenciales normales' })}
      >
        <span style={{ fontSize: '1.2rem' }}>🍎</span> Continuar con Apple
      </button>

      <div style={{
        display: 'flex',
        alignItems: 'center',
        margin: '1.5rem 0',
        gap: '1rem'
      }}>
        <hr style={{ flex: 1, border: 'none', borderTop: '1px solid #e0e0e0' }} />
        <span style={{ color: '#999', fontSize: '0.85rem' }}>o</span>
        <hr style={{ flex: 1, border: 'none', borderTop: '1px solid #e0e0e0' }} />
      </div>

      <LoginBox
        userLabel="Email"
        passwordLabel="Contraseña"
        loginLabel="Iniciar Sesión"
        onOK={handleLogin}
        loading={loading}
        message=""
      >
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          margin: '0.5rem 0 1rem',
          fontSize: '0.85rem'
        }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
            <input
              type="checkbox"
              checked={rememberMe}
              onChange={(e) => setRememberMe(e.target.checked)}
            />
            Recordarme
          </label>
          <span style={linkStyle} onClick={() => { setView('forgot'); setMessage({ type: '', text: '' }); }}>
            ¿Olvidaste tu contraseña?
          </span>
        </div>
      </LoginBox>

      <p style={{ textAlign: 'center', marginTop: '1.5rem', fontSize: '0.9rem', color: '#666' }}>
        ¿No tienes cuenta?{' '}
        <span style={linkStyle} onClick={() => { setView('register'); setMessage({ type: '', text: '' }); }}>
          Regístrate
        </span>
      </p>

      {loginAttempts > 0 && loginAttempts < 5 && (
        <p style={{ textAlign: 'center', fontSize: '0.8rem', color: '#ff9800', marginTop: '1rem' }}>
          ⚠️ Intentos fallidos: {loginAttempts}/5
        </p>
      )}
    </div>
  )

  // Vista: Registro
  const renderRegister = () => (
    <div style={containerStyle}>
      <h2 style={{ textAlign: 'center', marginBottom: '0.5rem', color: '#333' }}>Crear Cuenta</h2>
      <p style={{ textAlign: 'center', marginBottom: '1.5rem', color: '#666', fontSize: '0.9rem' }}>
        Regístrate para comenzar
      </p>

      {message.text && <div style={messageStyle(message.type)}>{message.text}</div>}

      <ResetPasswordBox
        userRequired={true}
        oldPwdRequired={false}
        submitLabel="Crear Cuenta"
        loading={loading}
        onOK={handleRegister}
      >
        <div style={{ fontSize: '0.8rem', color: '#666', margin: '0.5rem 0', padding: '0.5rem', background: '#f5f5f5', borderRadius: '4px' }}>
          <strong>Requisitos:</strong> 15+ caracteres, mayúscula, minúscula, número y carácter especial
        </div>
      </ResetPasswordBox>

      <p style={{ textAlign: 'center', marginTop: '1.5rem', fontSize: '0.9rem', color: '#666' }}>
        ¿Ya tienes cuenta?{' '}
        <span style={linkStyle} onClick={() => { setView('login'); setMessage({ type: '', text: '' }); }}>
          Inicia sesión
        </span>
      </p>
    </div>
  )

  // Vista: Olvidé mi contraseña
  const renderForgotPassword = () => (
    <div style={containerStyle}>
      <h2 style={{ textAlign: 'center', marginBottom: '0.5rem', color: '#333' }}>Recuperar Contraseña</h2>
      <p style={{ textAlign: 'center', marginBottom: '1.5rem', color: '#666', fontSize: '0.9rem' }}>
        Te enviaremos instrucciones por email
      </p>

      {message.text && <div style={messageStyle(message.type)}>{message.text}</div>}

      <div style={{ marginBottom: '1rem' }}>
        <input
          type="email"
          placeholder="Email"
          value={forgotEmail}
          onChange={(e) => setForgotEmail(e.target.value)}
          style={{
            width: '100%',
            padding: '0.75rem',
            border: '1px solid #ddd',
            borderRadius: '6px',
            fontSize: '1rem',
            boxSizing: 'border-box'
          }}
        />
      </div>

      <button
        onClick={() => handleForgotPassword(forgotEmail)}
        disabled={!forgotEmail || loading}
        style={{
          width: '100%',
          padding: '0.75rem',
          background: (!forgotEmail || loading) ? '#ccc' : '#1976d2',
          color: 'white',
          border: 'none',
          borderRadius: '6px',
          fontSize: '1rem',
          cursor: (!forgotEmail || loading) ? 'not-allowed' : 'pointer'
        }}
      >
        {loading ? 'Enviando...' : 'Enviar Instrucciones'}
      </button>

      <p style={{ textAlign: 'center', marginTop: '1.5rem', fontSize: '0.9rem', color: '#666' }}>
        <span style={linkStyle} onClick={() => { setView('login'); setMessage({ type: '', text: '' }); }}>
          ← Volver al login
        </span>
      </p>

      {/* Enlace de prueba para ir al reset */}
      <p style={{ textAlign: 'center', marginTop: '1rem', fontSize: '0.8rem', color: '#999' }}>
        <span style={{ ...linkStyle, color: '#999' }} onClick={() => { setView('reset'); setMessage({ type: '', text: '' }); }}>
          (Simular: Ir a restablecer contraseña)
        </span>
      </p>
    </div>
  )

  // Vista: Reset Password (desde link de email)
  const renderResetPassword = () => (
    <div style={containerStyle}>
      <h2 style={{ textAlign: 'center', marginBottom: '0.5rem', color: '#333' }}>Nueva Contraseña</h2>
      <p style={{ textAlign: 'center', marginBottom: '1.5rem', color: '#666', fontSize: '0.9rem' }}>
        Ingresa tu nueva contraseña
      </p>

      {message.text && <div style={messageStyle(message.type)}>{message.text}</div>}

      <ResetPasswordBox
        userRequired={false}
        oldPwdRequired={false}
        submitLabel="Guardar Contraseña"
        loading={loading}
        onOK={handleResetPassword}
      />
    </div>
  )

  // Vista: Verificación 2FA
  const renderVerify2FA = () => (
    <div style={containerStyle}>
      <h2 style={{ textAlign: 'center', marginBottom: '0.5rem', color: '#333' }}>Verificación</h2>
      <p style={{ textAlign: 'center', marginBottom: '1.5rem', color: '#666', fontSize: '0.9rem' }}>
        Ingresa el código de 6 dígitos enviado a tu email
      </p>

      {message.text && <div style={messageStyle(message.type)}>{message.text}</div>}

      <div style={{ marginBottom: '1rem' }}>
        <input
          type="text"
          placeholder="000000"
          value={verificationCode}
          onChange={(e) => setVerificationCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
          maxLength={6}
          style={{
            width: '100%',
            padding: '1rem',
            border: '1px solid #ddd',
            borderRadius: '6px',
            fontSize: '1.5rem',
            textAlign: 'center',
            letterSpacing: '0.5rem',
            boxSizing: 'border-box'
          }}
        />
      </div>

      <button
        onClick={handleVerify2FA}
        disabled={verificationCode.length !== 6 || loading}
        style={{
          width: '100%',
          padding: '0.75rem',
          background: (verificationCode.length !== 6 || loading) ? '#ccc' : '#1976d2',
          color: 'white',
          border: 'none',
          borderRadius: '6px',
          fontSize: '1rem',
          cursor: (verificationCode.length !== 6 || loading) ? 'not-allowed' : 'pointer'
        }}
      >
        {loading ? 'Verificando...' : 'Verificar'}
      </button>

      <p style={{ textAlign: 'center', marginTop: '1.5rem', fontSize: '0.85rem', color: '#666' }}>
        ¿No recibiste el código?{' '}
        <span style={linkStyle} onClick={() => setMessage({ type: 'success', text: 'Código reenviado' })}>
          Reenviar
        </span>
      </p>

      <p style={{ textAlign: 'center', marginTop: '0.5rem', fontSize: '0.8rem', color: '#999' }}>
        (Usa el código: 123456)
      </p>
    </div>
  )

  // Efecto para el contador de bloqueo - siempre se ejecuta al nivel del componente
  React.useEffect(() => {
    if (view !== 'locked' || !lockoutTime) return

    // Inicializar contador
    setLockoutRemaining(getLockoutRemaining())

    const timer = setInterval(() => {
      const r = getLockoutRemaining()
      setLockoutRemaining(r)
      if (r <= 0) {
        setView('login')
        setLoginAttempts(0)
        setLockoutTime(null)
      }
    }, 1000)
    return () => clearInterval(timer)
  }, [view, lockoutTime])

  // Vista: Cuenta bloqueada temporalmente
  const renderLocked = () => (
    <div style={containerStyle}>
      <div style={{ textAlign: 'center', fontSize: '4rem', marginBottom: '1rem' }}>🔒</div>
      <h2 style={{ textAlign: 'center', marginBottom: '0.5rem', color: '#c62828' }}>Cuenta Bloqueada</h2>
      <p style={{ textAlign: 'center', marginBottom: '1.5rem', color: '#666', fontSize: '0.9rem' }}>
        Demasiados intentos fallidos. Espera antes de intentar de nuevo.
      </p>

      <div style={{
        textAlign: 'center',
        fontSize: '2.5rem',
        fontWeight: 'bold',
        color: '#c62828',
        marginBottom: '1.5rem'
      }}>
        {lockoutRemaining}s
      </div>

      <div style={{
        background: '#fff3e0',
        padding: '1rem',
        borderRadius: '6px',
        fontSize: '0.85rem',
        color: '#e65100'
      }}>
        <strong>Consejo:</strong> Si olvidaste tu contraseña, usa la opción "¿Olvidaste tu contraseña?" para restablecerla.
      </div>
    </div>
  )

  // Vista: Login exitoso
  const renderSuccess = () => (
    <div style={containerStyle}>
      <div style={{ textAlign: 'center', fontSize: '4rem', marginBottom: '1rem' }}>✅</div>
      <h2 style={{ textAlign: 'center', marginBottom: '0.5rem', color: '#2e7d32' }}>¡Bienvenido!</h2>
      <p style={{ textAlign: 'center', marginBottom: '1.5rem', color: '#666', fontSize: '0.9rem' }}>
        Hola, <strong>{pendingUser?.name}</strong>
      </p>
      <p style={{ textAlign: 'center', color: '#666', fontSize: '0.9rem' }}>
        Has iniciado sesión correctamente.
      </p>

      <button
        onClick={() => {
          setView('login')
          setMessage({ type: '', text: '' })
          setPendingUser(null)
          setVerificationCode('')
        }}
        style={{
          width: '100%',
          marginTop: '1.5rem',
          padding: '0.75rem',
          background: '#f5f5f5',
          color: '#333',
          border: '1px solid #ddd',
          borderRadius: '6px',
          fontSize: '0.9rem',
          cursor: 'pointer'
        }}
      >
        Cerrar Sesión (volver al demo)
      </button>
    </div>
  )

  // Renderizar vista actual
  const renderView = () => {
    switch (view) {
      case 'login': return renderLogin()
      case 'register': return renderRegister()
      case 'forgot': return renderForgotPassword()
      case 'reset': return renderResetPassword()
      case 'verify2fa': return renderVerify2FA()
      case 'locked': return renderLocked()
      case 'success': return renderSuccess()
      default: return renderLogin()
    }
  }

  return (
    <div style={{ padding: '20px' }}>
      <h2 style={{ marginBottom: '1rem' }}>🌐 Simulación de Login Completo</h2>

      {/* Panel de pruebas */}
      <div style={{
        background: '#f5f5f5',
        padding: '1rem',
        borderRadius: '8px',
        marginBottom: '2rem',
        fontSize: '0.85rem'
      }}>
        <strong>📋 Usuarios de prueba:</strong>
        <table style={{ width: '100%', marginTop: '0.5rem', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ textAlign: 'left', borderBottom: '1px solid #ddd' }}>
              <th style={{ padding: '0.5rem' }}>Email</th>
              <th style={{ padding: '0.5rem' }}>Contraseña</th>
              <th style={{ padding: '0.5rem' }}>Caso</th>
            </tr>
          </thead>
          <tbody>
            <tr><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>admin@example.com</td><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>Admin123!secure</td><td style={{ padding: '0.5rem' }}>✅ Login exitoso</td></tr>
            <tr><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>user@example.com</td><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>User1234!secure</td><td style={{ padding: '0.5rem' }}>✅ Usuario normal</td></tr>
            <tr><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>2fa@example.com</td><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>2FA12345!secure</td><td style={{ padding: '0.5rem' }}>🔐 Requiere 2FA (código: 123456)</td></tr>
            <tr><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>locked@example.com</td><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>Locked123!secure</td><td style={{ padding: '0.5rem' }}>🔒 Cuenta bloqueada</td></tr>
            <tr><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>cualquier@otro.com</td><td style={{ padding: '0.5rem', fontFamily: 'monospace' }}>cualquiera</td><td style={{ padding: '0.5rem' }}>❌ Credenciales incorrectas</td></tr>
            <tr><td style={{ padding: '0.5rem' }} colSpan="3">⚠️ <strong>5 intentos fallidos</strong> = bloqueo temporal de 30 segundos</td></tr>
          </tbody>
        </table>
      </div>

      {/* Contenedor del login */}
      <div style={{
        minHeight: '500px',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        borderRadius: '12px',
        padding: '2rem',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        {renderView()}
      </div>
    </div>
  )
}

/**
 * Todos los ejemplos
 */
export const AllExamples = () => (
  <div style={{ maxWidth: '900px', margin: '0 auto' }}>
    <h1 style={{ padding: '20px', marginBottom: '0' }}>📚 Guía Completa de Login</h1>
    <LoginBoxBasic />
    <hr style={{ margin: '2rem 20px', border: 'none', borderTop: '1px solid #e0e0e0' }} />
    <LoginBoxPrefilled />
    <hr style={{ margin: '2rem 20px', border: 'none', borderTop: '1px solid #e0e0e0' }} />
    <LoginBoxWithChildren />
    <hr style={{ margin: '2rem 20px', border: 'none', borderTop: '1px solid #e0e0e0' }} />
    <LoginBoxStates />
    <hr style={{ margin: '2rem 20px', border: 'none', borderTop: '1px solid #e0e0e0' }} />
    <ResetPassword />
    <hr style={{ margin: '2rem 20px', border: 'none', borderTop: '1px solid #e0e0e0' }} />
    <ResetPasswordOptions />
    <hr style={{ margin: '2rem 20px', border: 'none', borderTop: '1px solid #e0e0e0' }} />
    <PasswordValidation />
    <hr style={{ margin: '2rem 20px', border: 'none', borderTop: '1px solid #e0e0e0' }} />
    <RealWorldLoginSimulation />
  </div>
)

