// Login de vendedora — usa Supabase si está configurado, fallback a localStorage demo.
function LoginScreen({ onLogin }) {
  const T = window.T;
  const { Icon } = window;

  const [form, setForm] = React.useState({ cedula: '', clave: '' });
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const useSupabase = window.SUPABASE_CONFIGURED;

  const handleSubmit = async () => {
    setError('');
    if (!form.cedula || !form.clave) { setError('Ingresa cédula y clave'); return; }
    setLoading(true);

    try {
      if (useSupabase) {
        const sb = await window.getSupabase();
        const { data, error: err } = await sb.rpc('login_vendedora', {
          p_cedula: form.cedula.trim(),
          p_clave: form.clave,
        });
        if (err) throw err;
        if (!data?.ok) { setError(data?.error || 'No se pudo iniciar sesión'); return; }
        const v = data.vendedora;
        window.saveSession({ vendedoraId: v.id });
        onLogin(v);
      } else {
        // Modo demo (localStorage)
        const vendedoras = window.loadVendedoras();
        const v = vendedoras.find(x =>
          (x.cedula === form.cedula || x.telefono === form.cedula) && x.clave === form.clave
        );
        if (!v) { setError('Cédula o clave incorrectos'); return; }
        window.saveSession({ vendedoraId: v.id });
        window.seedDemoIfEmpty(v.id);
        onLogin(v);
      }
    } catch (e) {
      console.error(e);
      setError('Error de conexión. Intenta de nuevo.');
    } finally {
      setLoading(false);
    }
  };

  const quickLogin = (cedulaOrTel) => {
    if (useSupabase) return;
    const vendedoras = window.loadVendedoras();
    const v = vendedoras.find(x => x.cedula === cedulaOrTel || x.telefono === cedulaOrTel);
    if (!v) return;
    window.saveSession({ vendedoraId: v.id });
    window.seedDemoIfEmpty(v.id);
    onLogin(v);
  };

  return (
    <div style={{
      width: '100%', minHeight: '100%', background: T.paper,
      display: 'flex', flexDirection: 'column', padding: '64px 28px 32px',
    }}>
      <div style={{ marginBottom: 40 }}>
        <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', color: T.inkMute }}>
          Inova · Pedidos
        </div>
        <div style={{ fontFamily: T.serif, fontSize: 44, lineHeight: 1, color: T.ink, letterSpacing: -1.2, marginTop: 8 }}>
          Hola de nuevo
        </div>
        <div style={{ fontFamily: T.serif, fontStyle: 'italic', fontSize: 20, color: T.inkSoft, letterSpacing: -0.3, marginTop: 6 }}>
          Entra con tu cédula
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
        <Field label="Cédula" value={form.cedula}
          onChange={v => setForm({ ...form, cedula: v.replace(/\D/g, '') })}
          placeholder="V-12345678" type="tel" />
        <Field label="Clave" value={form.clave}
          onChange={v => setForm({ ...form, clave: v })} placeholder="••••" type="password" />

        {error && (
          <div style={{
            padding: '10px 12px', borderRadius: 10,
            background: 'oklch(0.94 0.04 25)', color: 'oklch(0.4 0.14 25)',
            fontFamily: T.sans, fontSize: 12,
          }}>{error}</div>
        )}

        <button onClick={handleSubmit} disabled={loading} style={{
          marginTop: 6, padding: '16px', borderRadius: 14,
          background: T.ink, color: T.paper, border: 'none',
          cursor: loading ? 'wait' : 'pointer', opacity: loading ? 0.6 : 1,
          fontFamily: T.sans, fontSize: 14, fontWeight: 500,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          {loading ? 'Verificando…' : (<>Entrar <Icon name="arrowR" size={14} color={T.paper} /></>)}
        </button>

        <div style={{
          fontFamily: T.sans, fontSize: 11, color: T.inkMute,
          textAlign: 'center', marginTop: 8, lineHeight: 1.5,
        }}>
          ¿No tienes cuenta? Pídele a tu admin que te registre.
        </div>
      </div>

      {!useSupabase && (
        <div style={{ marginTop: 20, padding: 14, borderRadius: 14, background: T.paperAlt, border: `1px solid ${T.hairline}` }}>
          <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute, marginBottom: 8 }}>
            Demo — entrar como
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {window.loadVendedoras().map(v => (
              <button key={v.id} onClick={() => quickLogin(v.cedula || v.telefono)} style={{
                padding: '6px 10px', borderRadius: 999,
                background: T.paper, border: `1px solid ${T.hairline}`,
                cursor: 'pointer', fontFamily: T.sans, fontSize: 11, color: T.ink,
              }}>{v.nombre.split(' ')[0]}</button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function Field({ label, value, onChange, placeholder, type = 'text' }) {
  const T = window.T;
  return (
    <label style={{ display: 'block' }}>
      <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute, marginBottom: 6 }}>
        {label}
      </div>
      <input
        type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
        style={{
          width: '100%', padding: '12px 14px', borderRadius: 12,
          background: T.paperAlt, border: `1px solid ${T.hairline}`,
          fontFamily: T.sans, fontSize: 14, color: T.ink, outline: 'none',
          boxSizing: 'border-box',
        }}
      />
    </label>
  );
}

window.LoginScreen = LoginScreen;
