/* global React, SFIcons */
// Página que abre el enlace del correo (Flujo C): el cliente crea su nueva contraseña.
const RM = window.MADECIDesignSystem_419fb1;
const { Check: RCheck, Shield: RShield, Info: RInfo } = SFIcons;

function REyeIcon({ 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 RPanel({ children }) {
  return (
    <div style={{ background: 'var(--neutral-50)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-lg)', padding: '40px 38px 34px' }}>
      {children}
    </div>
  );
}

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

function ResetView({ token, onDone }) {
  const [phase, setPhase] = React.useState('checking'); // checking | form | done | invalid
  const [nombre, setNombre] = React.useState('');
  const [pass, setPass] = React.useState('');
  const [pass2, setPass2] = React.useState('');
  const [show, setShow] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  // Al abrir la página, verificamos que el enlace siga siendo válido.
  React.useEffect(() => {
    let vivo = true;
    window.MadeciAPI.validarClave(token).then((r) => {
      if (!vivo) return;
      if (r.ok) { setNombre(r.razon_social || ''); setPhase('form'); }
      else setPhase('invalid');
    }).catch(() => { if (vivo) setPhase('invalid'); });
    return () => { vivo = false; };
  }, [token]);

  const guardar = async () => {
    setErr('');
    if (pass.length < 8) { setErr('La contraseña debe tener al menos 8 caracteres.'); return; }
    if (pass !== pass2) { setErr('Las contraseñas no coinciden.'); return; }
    setBusy(true);
    try {
      await window.MadeciAPI.establecerClave(token, pass);
      setPhase('done');
    } catch (e) {
      setErr(e.message || 'No se pudo guardar la contraseña.');
      // Si el token venció mientras tanto, mostramos la pantalla de enlace inválido.
      if (/venci|válid|valid/i.test(e.message || '')) setPhase('invalid');
    } finally {
      setBusy(false);
    }
  };

  const shell = (children) => (
    <div style={{ minHeight: '100vh', background: 'var(--surface-page)' }}>
      <div style={{ textAlign: 'center', padding: '32px 0 4px' }}>
        <img src="assets/logo-horizontal.png" alt="MADECI" style={{ height: 42 }} />
      </div>
      <div className="sf-shell" style={{ maxWidth: 480, margin: '0 auto', padding: '32px 24px 96px' }}>{children}</div>
    </div>
  );

  if (phase === 'checking') {
    return shell(
      <RPanel>
        <p style={{ textAlign: 'center', fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--text-muted)', margin: 0 }}>Verificando el enlace…</p>
      </RPanel>
    );
  }

  if (phase === 'invalid') {
    return shell(
      <RPanel>
        <div style={{ textAlign: 'center' }}>
          <div style={{ width: 60, height: 60, borderRadius: 999, background: 'var(--madeci-red-50)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
            <RInfo size={30} stroke="var(--madeci-red)" strokeWidth={2.2} />
          </div>
          <h3 style={{ fontSize: 21, fontWeight: 800, letterSpacing: '-.01em' }}>Enlace no válido o vencido</h3>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-muted)', margin: '10px 0 0', lineHeight: 1.55 }}>
            Este enlace ya se usó o pasaron más de 24 horas. Vuelve a iniciar sesión y pide uno nuevo con “No tengo contraseña” o “¿Olvidaste tu contraseña?”.
          </p>
        </div>
        <div style={{ marginTop: 22 }}><RM.Button block size="lg" onClick={onDone}>Volver a iniciar sesión</RM.Button></div>
        <RBrandFoot />
      </RPanel>
    );
  }

  if (phase === 'done') {
    return shell(
      <RPanel>
        <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' }}>
            <RCheck size={34} stroke="var(--status-success)" strokeWidth={2.4} />
          </div>
          <h3 style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-.01em' }}>¡Contraseña creada!</h3>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--text-muted)', margin: '10px 0 0', lineHeight: 1.55 }}>
            Ya puedes iniciar sesión con tu RUT y tu nueva contraseña.
          </p>
        </div>
        <div style={{ marginTop: 22 }}><RM.Button block size="lg" onClick={onDone}>Iniciar sesión</RM.Button></div>
        <RBrandFoot />
      </RPanel>
    );
  }

  // phase === 'form'
  return shell(
    <RPanel>
      <h3 style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-.01em', color: 'var(--madeci-red)', textAlign: 'center' }}>Crea tu contraseña</h3>
      {nombre && (
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--text-muted)', textAlign: 'center', margin: '8px 0 0' }}>
          Hola <b style={{ color: 'var(--text-strong)' }}>{nombre}</b>, define la contraseña para entrar al portal.
        </p>
      )}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 24 }}>
        <RM.Input label="Nueva contraseña" type={show ? 'text' : 'password'} value={pass} onChange={(e) => setPass(e.target.value)} placeholder="Al menos 8 caracteres" />
        <RM.Input label="Repite la contraseña" type={show ? 'text' : 'password'} value={pass2} onChange={(e) => setPass2(e.target.value)} placeholder="Escríbela otra vez" onKeyDown={(e) => { if (e.key === 'Enter') guardar(); }} />
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button type="button" onClick={() => setShow((v) => !v)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13, color: 'var(--madeci-red)' }}>
            <REyeIcon off={show} /> {show ? 'Ocultar' : 'Mostrar'}
          </button>
        </div>
      </div>
      {err && (
        <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)' }}>{err}</div>
      )}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, margin: '16px 0 18px', fontFamily: 'var(--font-body)', fontSize: 12.5, color: 'var(--text-subtle)' }}>
        <RShield size={15} stroke="var(--text-subtle)" style={{ flex: 'none', marginTop: 1 }} /> Usa una contraseña que solo tú conozcas. Podrás cambiarla cuando quieras desde “Mi cuenta”.
      </div>
      <RM.Button block size="lg" onClick={guardar} disabled={busy}>{busy ? 'Guardando…' : 'Guardar contraseña'}</RM.Button>
      <RBrandFoot />
    </RPanel>
  );
}

Object.assign(window, { ResetView });
