/* global React, SFIcons */
const LM = window.MADECIDesignSystem_419fb1;
const { Check: LCheck, Shield: LShield, ChevronLeft: LBack, Info: LInfo } = SFIcons;

function Benefit({ text }) {
  return (
    <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-body)' }}>
      <span style={{ width: 22, height: 22, flex: 'none', borderRadius: 999, background: 'var(--madeci-red-50)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <LCheck size={14} stroke="var(--madeci-red)" strokeWidth={2.6} />
      </span>{text}
    </span>
  );
}

const linkStyle = { fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13, color: 'var(--madeci-red)', cursor: 'pointer' };

// Ojo (mostrar) / ojo tachado (ocultar) para el toggle de contraseña.
function EyeIcon({ off, size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      {off ? (
        <>
          <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 10 8 10 8a18.5 18.5 0 0 1-2.16 3.19M6.61 6.61A18.5 18.5 0 0 0 2 12s3 8 10 8a9.12 9.12 0 0 0 5.39-1.61" />
          <path d="M14.12 14.12A3 3 0 1 1 9.88 9.88" /><path d="M2 2l20 20" />
        </>
      ) : (
        <>
          <path d="M2 12s3-8 10-8 10 8 10 8-3 8-10 8-10-8-10-8Z" /><circle cx="12" cy="12" r="3" />
        </>
      )}
    </svg>
  );
}

function Panel({ children }) {
  return (
    <div style={{ background: 'var(--neutral-50)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', padding: '40px 38px 36px' }}>
      {children}
    </div>
  );
}

function BrandFoot() {
  return (
    <div style={{ marginTop: 30, paddingTop: 22, borderTop: '1px solid var(--border-subtle)', textAlign: 'center' }}>
      <img src="assets/logo-horizontal.png" alt="MADECI" style={{ height: 34, opacity: 0.9 }} />
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 11.5, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--text-subtle)', marginTop: 10 }}>
        Distribuidora de bebidas y licores
      </div>
    </div>
  );
}

// Flujo C / recuperación — confirmación con correo enmascarado
function LinkSent({ mode, masked, onBack }) {
  const esRecuperar = mode === 'forgot' || mode === 'recuperar';
  return (
    <Panel>
      <div style={{ textAlign: 'center' }}>
        <div style={{ width: 64, height: 64, borderRadius: 999, background: 'var(--status-success-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
          <LCheck size={34} stroke="var(--status-success)" strokeWidth={2.4} />
        </div>
        <h3 style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-.01em' }}>{esRecuperar ? 'Enlace de recuperación enviado' : 'Enlace de creación enviado'}</h3>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--text-muted)', margin: '10px 0 0', lineHeight: 1.55 }}>
          Te enviamos un enlace {esRecuperar ? 'para restablecer' : 'para crear'} tu contraseña al correo registrado en tu ficha:
        </p>
        <div style={{ fontFamily: 'var(--font-data)', fontWeight: 700, fontSize: 18, color: 'var(--text-strong)', margin: '12px 0', padding: '10px 16px', background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-sm)', display: 'inline-block' }}>{masked}</div>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, textAlign: 'left', margin: '6px auto 0', maxWidth: 380, fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-subtle)' }}>
          <LInfo size={15} style={{ flex: 'none', marginTop: 1 }} /> Por seguridad, el enlace solo se envía al correo que ya tienes registrado con MADECI. El enlace vence en 24 h. ¿No lo tienes? Un ejecutivo te ayuda por WhatsApp +56 9 9443 7835.
        </div>
      </div>
      <div style={{ marginTop: 22 }}><LM.Button block size="lg" onClick={onBack}>Volver a iniciar sesión</LM.Button></div>
    </Panel>
  );
}

function LoginView({ onLogin, onRegister }) {
  const [rut, setRut] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [showPass, setShowPass] = React.useState(false);
  const [mode, setMode] = React.useState('login'); // login | nopass | forgot | sent
  const [idInput, setIdInput] = React.useState('');
  const [sentMode, setSentMode] = React.useState('nopass');
  const [sentMasked, setSentMasked] = React.useState('');
  const [linkErr, setLinkErr] = React.useState('');
  const [linkBusy, setLinkBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  // Pide al backend el enlace de crear/recuperar contraseña (va al correo de la ficha).
  const submitLink = async (m) => {
    setLinkErr('');
    if (!idInput.trim()) { setLinkErr('Ingresa tu RUT o código de cliente.'); return; }
    setLinkBusy(true);
    try {
      const r = await window.MadeciAPI.solicitarClave(idInput.trim());
      setSentMasked(r.email_mascara || '');
      setSentMode(r.modo || m);
      setMode('sent');
    } catch (e) {
      setLinkErr(e.message || 'No se pudo enviar el enlace.');
    } finally {
      setLinkBusy(false);
    }
  };

  // Llama al login real del backend. onLogin(rut, pass) devuelve una promesa.
  const doLogin = async () => {
    setError('');
    setBusy(true);
    try {
      await onLogin(rut, pass);
    } catch (e) {
      setError(e.message || 'No se pudo iniciar sesión.');
    } finally {
      setBusy(false);
    }
  };

  const rightPanel = () => {
    if (mode === 'sent') return <LinkSent mode={sentMode} masked={sentMasked} onBack={() => setMode('login')} />;

    if (mode === 'nopass' || mode === 'forgot') {
      const forgot = mode === 'forgot';
      return (
        <Panel>
          <button onClick={() => setMode('login')} style={{ display: 'flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13.5, color: 'var(--text-muted)', padding: 0, marginBottom: 14 }}><LBack size={16} /> Volver</button>
          <h3 style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-.01em', color: 'var(--madeci-red)' }}>{forgot ? '¿Olvidaste tu contraseña?' : 'Soy cliente, no tengo contraseña'}</h3>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--text-muted)', marginTop: 8, lineHeight: 1.5 }}>
            Ingresa tu RUT o código de cliente. Te enviaremos un enlace {forgot ? 'para restablecer' : 'para crear'} tu contraseña al correo registrado en tu ficha MADECI.
          </p>
          <div style={{ marginTop: 20 }}>
            <LM.Input label="RUT o código de cliente" value={idInput} onChange={(e) => setIdInput(e.target.value)} placeholder="Ej. 76.451.220-8 o C-04821" />
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, margin: '14px 0 18px', fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-subtle)' }}>
            <LShield size={15} stroke="var(--text-subtle)" style={{ flex: 'none', marginTop: 1 }} /> Por tu seguridad, el enlace se envía solo al correo en tu ficha — nunca a uno escrito aquí.
          </div>
          {linkErr && (
            <div style={{ margin: '0 0 14px', padding: '10px 14px', background: 'var(--madeci-red-50)', border: '1px solid var(--madeci-red)', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--madeci-red)' }}>{linkErr}</div>
          )}
          <LM.Button block size="lg" onClick={() => submitLink(mode)} disabled={linkBusy}>{linkBusy ? 'Enviando…' : 'Enviar enlace'}</LM.Button>
          <BrandFoot />
        </Panel>
      );
    }

    // login
    return (
      <Panel>
        <h3 style={{ fontSize: 23, fontWeight: 800, letterSpacing: '-.01em', color: 'var(--madeci-red)', textAlign: 'center' }}>¿Ya eres cliente de MADECI?</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 26 }}>
          <LM.Input label="RUT o código de cliente" value={rut} onChange={(e) => setRut(e.target.value)} placeholder="76.451.220-8" />
          <div>
            <LM.Input label="Contraseña" type={showPass ? 'text' : 'password'} value={pass} onChange={(e) => setPass(e.target.value)} placeholder="Tu contraseña" onKeyDown={(e) => { if (e.key === 'Enter') doLogin(); }} />
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 7 }}>
              <button type="button" onClick={() => setShowPass((v) => !v)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center', gap: 6, ...linkStyle }}>
                <EyeIcon off={showPass} /> {showPass ? 'Ocultar contraseña' : 'Mostrar contraseña'}
              </button>
            </div>
          </div>
        </div>
        {error && (
          <div style={{ margin: '12px 0 0', padding: '10px 14px', background: 'var(--madeci-red-50)', border: '1px solid var(--madeci-red)', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--madeci-red)' }}>{error}</div>
        )}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '10px 0 16px', gap: 12 }}>
          <a onClick={() => { setMode('nopass'); setIdInput(''); }} style={linkStyle}>No tengo contraseña</a>
          <a onClick={() => { setMode('forgot'); setIdInput(''); }} style={linkStyle}>¿Olvidaste tu contraseña?</a>
        </div>
        <LM.Button block size="lg" onClick={doLogin} disabled={busy}>{busy ? 'Ingresando…' : 'Iniciar sesión'}</LM.Button>
        <BrandFoot />
      </Panel>
    );
  };

  return (
    <div className="sf-shell" style={{ maxWidth: 1120, margin: '0 auto', padding: '64px 24px 96px' }}>
      <div className="sf-login-cols" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56, alignItems: 'center' }}>

        {/* Registro */}
        <div style={{ textAlign: 'center' }}>
          <h2 style={{ fontSize: 30, fontWeight: 800, letterSpacing: '-.02em', lineHeight: 1.1 }}>
            Inscríbete como cliente en <span style={{ color: 'var(--madeci-red)' }}>MADECI</span>
          </h2>
          <div style={{ marginTop: 24 }}>
            <LM.Button size="lg" onClick={onRegister}>Regístrate</LM.Button>
          </div>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-muted)', margin: '24px 0 14px' }}>
            Regístrate y accede a todos los beneficios de
          </p>
          <img src="assets/logo-horizontal.png" alt="MADECI" style={{ height: 40 }} />
          <div style={{ display: 'inline-flex', flexDirection: 'column', gap: 12, marginTop: 26, textAlign: 'left' }}>
            <Benefit text="Precios mayoristas y descuentos por volumen" />
            <Benefit text="Despacho express en toda la provincia" />
            <Benefit text="Cuenta corriente comercial a 30 días" />
          </div>
        </div>

        {/* Panel derecho (login / sin contraseña / recuperar / enviado) */}
        {rightPanel()}
      </div>
    </div>
  );
}

Object.assign(window, { LoginView });
