// password-gate.jsx — Pantalla bloqueante que pide al user setear una
// contraseña real cuando entró al app vía el flow anonymous-first.
//
// Contexto: el funnel /onboarding crea User+Workspace anónimos sin pedir
// password; capture-email los flipea a no-anónimo pero el passwordHash
// queda como placeholder bcrypt random. Sin password real, el user no
// puede loguearse desde otro browser ni recuperar su cuenta. Este gate
// se monta entre BillingGate y OnboardingWizard si `me.hasPassword === false`.
//
// Submit pega contra POST /api/onboarding/claim — el endpoint ya está
// flexibilizado para aceptar users no-anónimos que aún tienen el
// placeholder bcrypt. En éxito, recargamos /api/me y la siguiente render
// pasa el gate y sigue al wizard.

(function () {
  const { useState, useCallback } = React;

  const C = {
    bg: '#0B0E14',
    bgCard: '#11151D',
    bgInput: '#0F1219',
    border: 'rgba(255,255,255,0.08)',
    t0: '#FAFAFA',
    t1: '#B6BAC4',
    t2: '#7A7F8B',
    t3: '#4F5562',
    accent: '#F97316',
    accentSoft: 'rgba(249,115,22,0.16)',
    accentGlow: 'rgba(249,115,22,0.55)',
    success: '#10B981',
    danger: '#EF4444',
  };
  const HEAD_FONT = "'Geist', -apple-system, sans-serif";
  const UI_FONT = "'Geist', -apple-system, sans-serif";

  function _Backdrop() {
    return (
      <div aria-hidden style={{
        position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 0,
        background: `radial-gradient(ellipse at 20% 0%, rgba(249,115,22,0.10), transparent 50%),
                     radial-gradient(ellipse at 80% 100%, rgba(249,115,22,0.06), transparent 55%)`,
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(rgba(249,115,22,0.16) 1px, transparent 1px)',
          backgroundSize: '40px 40px',
          maskImage: 'radial-gradient(ellipse at 50% 40%, rgba(0,0,0,0.6) 0%, transparent 70%)',
          WebkitMaskImage: 'radial-gradient(ellipse at 50% 40%, rgba(0,0,0,0.6) 0%, transparent 70%)',
          opacity: 0.4,
        }} />
      </div>
    );
  }

  function PasswordGate({ onDone }) {
    const [password, setPassword] = useState('');
    const [confirm, setConfirm] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const [error, setError] = useState(null);
    const [showPw, setShowPw] = useState(false);

    const email = (window.ME && window.ME.email) || '';
    const displayName = (window.ME && (window.ME.displayName || window.ME.name)) || '';

    const tooShort = password.length > 0 && password.length < 8;
    const mismatch = confirm.length > 0 && password !== confirm;
    const valid = password.length >= 8 && password === confirm && !submitting;

    const submit = useCallback(async (e) => {
      e?.preventDefault?.();
      if (!valid) return;
      setError(null);
      setSubmitting(true);
      try {
        await window.api('POST', '/api/onboarding/claim', { password });
        // Recargar /api/me para que window.ME.hasPassword pase a true y el
        // gate desaparezca en el próximo render.
        try { await window.loadMe?.(); } catch (_e) {}
        onDone && onDone();
      } catch (err) {
        setError(err?.body?.error || err?.message || 'No pudimos guardar tu contraseña. Intenta de nuevo.');
        setSubmitting(false);
      }
    }, [password, valid, onDone]);

    return (
      <div style={{
        position: 'fixed', inset: 0, background: C.bg, color: C.t0,
        fontFamily: UI_FONT, overflow: 'auto',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 'clamp(16px, 4vw, 40px)',
      }}>
        <_Backdrop />
        <form
          onSubmit={submit}
          style={{
            position: 'relative', zIndex: 1,
            width: '100%', maxWidth: 520,
            padding: 'clamp(28px, 4vw, 44px)',
            background: C.bgCard,
            border: `1px solid ${C.border}`,
            borderRadius: 18,
            boxShadow: '0 30px 60px -20px rgba(0,0,0,0.6), 0 0 0 1px rgba(249,115,22,0.05)',
          }}
        >
          <div style={{
            fontFamily: UI_FONT, fontWeight: 700, fontSize: 11,
            letterSpacing: '1.6px', textTransform: 'uppercase',
            color: C.accent, marginBottom: 10,
          }}>
            Último paso · seguridad
          </div>
          <h1 style={{
            fontFamily: HEAD_FONT, fontSize: 'clamp(26px, 4vw, 34px)',
            fontWeight: 800, color: C.t0, letterSpacing: '-0.02em',
            lineHeight: 1.1, margin: '0 0 12px',
          }}>
            Crea tu contraseña.
          </h1>
          <p style={{ fontSize: 14, color: C.t1, lineHeight: 1.6, margin: '0 0 24px' }}>
            Sin contraseña no podrías volver a entrar desde otro dispositivo.
            La usamos para que tu cuenta {displayName ? <strong style={{ color: C.t0 }}>({displayName})</strong> : null} quede tuya de verdad.
          </p>

          {email && (
            <div style={{
              padding: '10px 12px', marginBottom: 16, borderRadius: 10,
              background: 'rgba(255,255,255,0.03)',
              border: '1px solid rgba(255,255,255,0.06)',
              fontSize: 13, color: C.t1,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={C.t2} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{email}</span>
            </div>
          )}

          <div style={{ marginBottom: 14 }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 600,
              color: C.t2, textTransform: 'uppercase', letterSpacing: 0.4,
              marginBottom: 6,
            }}>
              Nueva contraseña
            </label>
            <div style={{ position: 'relative' }}>
              <input
                type={showPw ? 'text' : 'password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                autoFocus
                autoComplete="new-password"
                placeholder="Mínimo 8 caracteres"
                style={{
                  width: '100%', padding: '13px 44px 13px 14px',
                  background: C.bgInput,
                  border: `1px solid ${tooShort ? 'rgba(239,68,68,0.5)' : 'rgba(255,255,255,0.10)'}`,
                  borderRadius: 10, color: C.t0, fontSize: 14,
                  outline: 'none',
                  fontFamily: UI_FONT,
                }}
              />
              <button
                type="button"
                onClick={() => setShowPw((v) => !v)}
                className="btn-reset"
                aria-label={showPw ? 'Ocultar contraseña' : 'Mostrar contraseña'}
                style={{
                  position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
                  padding: '6px 10px', background: 'transparent', color: C.t2,
                  fontSize: 11, fontWeight: 600, cursor: 'pointer',
                }}
              >
                {showPw ? 'Ocultar' : 'Ver'}
              </button>
            </div>
            {tooShort && (
              <div style={{ fontSize: 11.5, color: C.danger, marginTop: 6 }}>
                Mínimo 8 caracteres.
              </div>
            )}
          </div>

          <div style={{ marginBottom: 20 }}>
            <label style={{
              display: 'block', fontSize: 11, fontWeight: 600,
              color: C.t2, textTransform: 'uppercase', letterSpacing: 0.4,
              marginBottom: 6,
            }}>
              Confirma la contraseña
            </label>
            <input
              type={showPw ? 'text' : 'password'}
              value={confirm}
              onChange={(e) => setConfirm(e.target.value)}
              autoComplete="new-password"
              placeholder="Vuelve a escribirla"
              style={{
                width: '100%', padding: '13px 14px',
                background: C.bgInput,
                border: `1px solid ${mismatch ? 'rgba(239,68,68,0.5)' : 'rgba(255,255,255,0.10)'}`,
                borderRadius: 10, color: C.t0, fontSize: 14,
                outline: 'none',
                fontFamily: UI_FONT,
              }}
            />
            {mismatch && (
              <div style={{ fontSize: 11.5, color: C.danger, marginTop: 6 }}>
                No coinciden.
              </div>
            )}
          </div>

          {error && (
            <div style={{
              padding: '10px 12px', marginBottom: 16, borderRadius: 10,
              background: 'rgba(239,68,68,0.10)',
              border: '1px solid rgba(239,68,68,0.30)',
              color: C.danger, fontSize: 13, lineHeight: 1.5,
            }}>
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={!valid}
            style={{
              width: '100%', padding: '14px 22px',
              background: valid ? C.accent : 'rgba(249,115,22,0.25)',
              color: valid ? '#fff' : 'rgba(255,255,255,0.5)',
              border: 'none', borderRadius: 12,
              fontFamily: UI_FONT, fontSize: 15, fontWeight: 700,
              letterSpacing: '-0.1px',
              cursor: valid ? 'pointer' : 'not-allowed',
              boxShadow: valid ? `0 16px 36px -14px ${C.accentGlow}` : 'none',
              transition: 'transform .08s ease',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            }}
          >
            {submitting ? 'Guardando…' : 'Guardar contraseña y continuar'}
            {!submitting && valid && (
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            )}
          </button>

          <div style={{
            marginTop: 18, fontSize: 11.5, color: C.t3,
            lineHeight: 1.6, textAlign: 'center',
          }}>
            Guardada con bcrypt. No la compartimos ni la mostramos en logs.
          </div>
        </form>
      </div>
    );
  }

  window.PasswordGate = PasswordGate;
})();
