// login-modal.jsx — modal de login integrado en la landing

const SUPABASE_URL = 'https://vvbnkaexeexthvlfyhaj.supabase.co'
const SUPABASE_ANON = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InZ2Ym5rYWV4ZWV4dGh2bGZ5aGFqIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODA1OTYxODgsImV4cCI6MjA5NjE3MjE4OH0.40KY3eRjc3m1E7bzidLelk6pwM4p2q053cS0JwYloNA'

let _supabase = null
function getSupabase() {
  if (!_supabase) _supabase = supabase.createClient(SUPABASE_URL, SUPABASE_ANON)
  return _supabase
}

function LoginModal({ open, onClose }) {
  const [email, setEmail] = React.useState('')
  const [password, setPassword] = React.useState('')
  const [error, setError] = React.useState('')
  const [loading, setLoading] = React.useState(false)

  React.useEffect(() => {
    if (!open) { setEmail(''); setPassword(''); setError('') }
  }, [open])

  // Cerrar con Escape
  React.useEffect(() => {
    if (!open) return
    const handler = (e) => { if (e.key === 'Escape') onClose() }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [open, onClose])

  if (!open) return null

  async function handleSubmit(e) {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      })
      const data = await res.json()
      if (!res.ok) {
        setError(data.error || 'Email o contraseña incorrectos.')
        setLoading(false)
        return
      }
      window.location.href = '/dashboard'
    } catch {
      setError('Error de conexión. Intentá de nuevo.')
      setLoading(false)
    }
  }

  const overlay = {
    position: 'fixed', inset: 0, zIndex: 9999,
    background: 'rgba(5,10,18,0.75)', backdropFilter: 'blur(6px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem',
  }
  const card = {
    background: '#0A1626', borderRadius: 12, width: '100%', maxWidth: 420,
    boxShadow: '0 32px 80px -20px rgba(0,0,0,0.7)',
    border: '1px solid rgba(176,136,59,0.25)',
    overflow: 'hidden',
  }
  const header = {
    background: '#11243C', padding: '28px 32px 20px',
    borderBottom: '1px solid rgba(176,136,59,0.18)',
  }
  const body = { padding: '28px 32px 32px' }
  const label = { display: 'block', fontSize: 13, fontWeight: 600, color: '#F2ECDC', marginBottom: 6 }
  const input = {
    display: 'block', width: '100%', padding: '10px 12px',
    border: '1px solid rgba(176,136,59,0.25)', borderRadius: 6,
    fontSize: 15, color: '#F2ECDC', background: '#0C1B2E',
    outline: 'none', boxSizing: 'border-box',
    fontFamily: 'inherit',
  }
  const btn = {
    display: 'block', width: '100%', padding: '12px',
    background: '#B0883B', color: '#0A1626',
    border: 'none', borderRadius: 6, fontSize: 15, fontWeight: 700,
    cursor: loading ? 'not-allowed' : 'pointer', marginTop: 20,
    opacity: loading ? 0.7 : 1, fontFamily: 'inherit',
    letterSpacing: '0.02em',
  }

  return (
    <div style={overlay} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={card}>
        <div style={header}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <p style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#B0883B', fontFamily: 'monospace', marginBottom: 6 }}>
                Excelencia Legal CR
              </p>
              <h2 style={{ fontSize: 22, fontWeight: 400, color: '#F2ECDC', fontFamily: "'Marcellus', serif", margin: 0 }}>
                Iniciar sesión
              </h2>
            </div>
            <button onClick={onClose} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              color: '#A9B6CB', fontSize: 20, lineHeight: 1, padding: 4,
            }}>✕</button>
          </div>
        </div>

        <div style={body}>
          <form onSubmit={handleSubmit}>
            {error && (
              <div style={{
                background: 'rgba(220,38,38,0.12)', border: '1px solid rgba(220,38,38,0.35)',
                color: '#fca5a5', borderRadius: 6, padding: '10px 12px',
                fontSize: 13, marginBottom: 16,
              }}>
                {error}
              </div>
            )}

            <div style={{ marginBottom: 16 }}>
              <label style={label}>Correo electrónico</label>
              <input
                style={input}
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="tu@correo.com"
                required
                autoComplete="email"
                autoFocus
              />
            </div>

            <div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                <label style={{ ...label, marginBottom: 0 }}>Contraseña</label>
                <a
                  href="/forgot-password"
                  style={{ fontSize: 12, color: '#B0883B', textDecoration: 'none', opacity: 0.85 }}
                  onMouseOver={e => e.target.style.opacity = 1}
                  onMouseOut={e => e.target.style.opacity = 0.85}
                >
                  ¿Olvidaste tu contraseña?
                </a>
              </div>
              <input
                style={input}
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="••••••••"
                required
                autoComplete="current-password"
              />
            </div>

            <button type="submit" style={btn} disabled={loading}>
              {loading ? 'Ingresando…' : 'Ingresar'}
            </button>
          </form>

          <p style={{ marginTop: 20, fontSize: 13, color: '#A9B6CB', textAlign: 'center' }}>
            ¿No tenés cuenta?{' '}
            <a href="/register" style={{ color: '#B0883B', fontWeight: 600, textDecoration: 'none' }}>
              Solicitar acceso
            </a>
          </p>
        </div>
      </div>
    </div>
  )
}

Object.assign(window, { LoginModal })
