/* Cambio obligatorio de contraseña en primer acceso al portal */

const StudentChangePasswordModal = ({ open, onClose, theme, studentCode, onSuccess }) => {
  const [current, setCurrent] = React.useState('');
  const [next, setNext] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    if (!open) return;
    setCurrent('');
    setNext('');
    setConfirm('');
    setErr('');
  }, [open]);

  const submit = async () => {
    if (next.length < 8) { setErr('La nueva contraseña debe tener al menos 8 caracteres.'); return; }
    if (next !== confirm) { setErr('Las contraseñas no coinciden.'); return; }
    setBusy(true);
    setErr('');
    try {
      await changeStudentPortalPassword({ studentCode, currentPassword: current, newPassword: next });
      onSuccess?.();
      onClose?.();
    } catch (e) {
      setErr(e.message || 'No se pudo actualizar');
    }
    setBusy(false);
  };

  if (!open) return null;

  return (
    <Modal open={open} onClose={() => {}} theme={theme} width={440}>
      <div style={{ padding: 24 }}>
        <h3 style={{ fontFamily: 'Bebas Neue, sans-serif', fontSize: 26, color: theme.text, margin: '0 0 8px', letterSpacing: 1 }}>
          CAMBIAR CONTRASEÑA
        </h3>
        <p style={{ fontSize: 13, color: theme.textDim, margin: '0 0 16px', fontFamily: 'Inter, sans-serif' }}>
          Por seguridad, define una contraseña nueva antes de entrar al portal.
        </p>
        <div style={{ display: 'grid', gap: 12 }}>
          <Input theme={theme} label="Contraseña temporal" type="password" value={current} onChange={e => setCurrent(e.target.value)} />
          <Input theme={theme} label="Nueva contraseña" type="password" value={next} onChange={e => setNext(e.target.value)} />
          <Input theme={theme} label="Confirmar nueva" type="password" value={confirm} onChange={e => setConfirm(e.target.value)} />
        </div>
        {err && <p style={{ color: theme.danger, fontSize: 13, marginTop: 12 }}>{err}</p>}
        <Btn theme={theme} icon="check" style={{ width: '100%', marginTop: 16 }} onClick={submit} disabled={busy}>
          {busy ? 'Guardando…' : 'Guardar y continuar'}
        </Btn>
      </div>
    </Modal>
  );
};

Object.assign(window, { StudentChangePasswordModal });
