// login.jsx — Pantalla de inicio de sesión (estética boutique cálido)

function LoginView({ theme, onLogin }) {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const passwordRef = React.useRef(null);

  const handleSubmit = async () => {
    if (!username.trim() || !password.trim()) return;
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: username.trim(), password }),
      });
      const data = await res.json();
      if (res.ok) {
        onLogin(data.token, data.user);
      } else {
        setError(data.error || 'Credenciales incorrectas');
      }
    } catch {
      setError('No se pudo conectar con el servidor');
    } finally {
      setLoading(false);
    }
  };

  const fieldStyle = {
    width: '100%', height: 48, padding: '0 16px',
    borderRadius: 14, border: `0.5px solid ${theme.border}`,
    background: theme.input, color: theme.ink,
    fontSize: 16, font: 'inherit', outline: 'none',
    boxSizing: 'border-box', WebkitAppearance: 'none',
  };

  const labelStyle = {
    fontSize: 10.5, fontWeight: 600, letterSpacing: 0.6,
    color: theme.muted, textTransform: 'uppercase',
  };

  return (
    <div style={{
      height: '100%', display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      background: theme.bg, padding: '0 28px 32px',
    }}>
      {/* Encabezado */}
      <div style={{ marginBottom: 44, textAlign: 'center' }}>
        <div style={{
          width: 72, height: 90, margin: '0 auto 20px', opacity: 0.9,
        }}>
          <window.DressPlaceholder seed={2} tone={theme.accent} bg={theme.placeholderBg} />
        </div>
        <div style={{
          fontSize: 10.5, letterSpacing: 2, textTransform: 'uppercase',
          color: theme.muted, fontWeight: 600, marginBottom: 8,
        }}>Atelier</div>
        <div style={{
          fontFamily: theme.serif, fontSize: 32, fontWeight: 500,
          color: theme.ink, letterSpacing: 0.3, lineHeight: 1,
        }}>Catálogo</div>
        <div style={{
          fontSize: 12.5, color: theme.mutedSoft, marginTop: 8, letterSpacing: 0.1,
        }}>Acceso interno del taller</div>
      </div>

      {/* Formulario */}
      <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={labelStyle}>Usuario</span>
          <input
            type="text"
            value={username}
            autoCapitalize="none"
            autoCorrect="off"
            autoComplete="username"
            onChange={e => setUsername(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && passwordRef.current?.focus()}
            style={fieldStyle}
            placeholder="admin"
          />
        </label>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={labelStyle}>Contraseña</span>
          <input
            ref={passwordRef}
            type="password"
            value={password}
            autoComplete="current-password"
            onChange={e => setPassword(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && handleSubmit()}
            style={fieldStyle}
          />
        </label>

        {error && (
          <div style={{
            fontSize: 12.5, color: '#C0533A', textAlign: 'center',
            lineHeight: 1.4, padding: '2px 0',
          }}>{error}</div>
        )}

        <button
          onClick={handleSubmit}
          disabled={loading || !username.trim() || !password.trim()}
          style={{
            width: '100%', height: 52, borderRadius: 14, marginTop: 4,
            background: (loading || !username.trim() || !password.trim())
              ? theme.mutedSoft : theme.accent,
            color: '#fff', border: 0,
            fontFamily: theme.serif, fontSize: 18, fontWeight: 500, letterSpacing: 0.3,
            cursor: (loading || !username.trim() || !password.trim()) ? 'default' : 'pointer',
            boxShadow: '0 2px 10px rgba(180,140,100,0.22)',
            transition: 'background 0.2s',
          }}>
          {loading ? 'Entrando…' : 'Entrar'}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { LoginView });
