// ── Pantalla de bienvenida (solo primera visita) ─────────────────────────────
// Se muestra una sola vez, a un visitante nuevo en el navegador. Si ya ha
// entrado antes, si la app está instalada (standalone), o si ya tiene datos,
// va directo al panel. Textos aprobados (narrativa de marca condensada de
// BrandStory + Method; sin textos de Hero/Mobile/Closing).

const WELCOME_SEEN_KEY = 'atlas.welcome.seen.v1';

function welcomeShouldShow() {
  try {
    // App instalada (modo standalone) → directo al panel.
    const standalone = (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) || window.navigator.standalone === true;
    if (standalone) return false;
    // Ya la ha visto / ya ha pulsado "Empezar".
    if (localStorage.getItem(WELCOME_SEEN_KEY) === 'true') return false;
    // Usuario que ya ha entrado antes (tiene nombre, onboarding o historial).
    const raw = localStorage.getItem('atlas.store.v2');
    if (raw) {
      const s = JSON.parse(raw);
      if (s && (s.user?.onboarded || (s.user?.name || '').trim() || (Array.isArray(s.log) && s.log.length))) return false;
    }
    return true;
  } catch (e) { return false; }
}

function WelcomeGate() {
  const [open, setOpen] = React.useState(() => welcomeShouldShow());
  if (!open || typeof ReactDOM === 'undefined') return null;

  const start = () => { try { localStorage.setItem(WELCOME_SEEN_KEY, 'true'); } catch {} setOpen(false); };
  const openInstall = () => { try { window.AtlasPWA && window.AtlasPWA.open(); } catch {} };
  const canInstall = (() => { try { return !!(window.AtlasPWA && window.AtlasPWA.available()); } catch { return false; } })();

  const cream = '#FAFAF7';
  const serif = { fontFamily: '"Instrument Serif",Georgia,serif', fontStyle: 'italic', fontWeight: 400 };

  const offerings = [
    ['Rutinas con criterio', 'Volumen, intensidad y frecuencia según la evidencia, no la rutina viral de turno.'],
    ['Registro de tu entrenamiento', 'Cargas, series y progreso, un día y una serie a la vez.'],
    ['Aula con ciencia', 'Artículos con referencias para entrenar entendiendo el porqué.'],
  ];

  return ReactDOM.createPortal(
    <div role="dialog" aria-modal="true" aria-label="Bienvenido a Atlas Method"
      style={{ position: 'fixed', inset: 0, zIndex: 7000, background: '#0F1A2E', color: cream, overflowY: 'auto',
        WebkitOverflowScrolling: 'touch', animation: 'fadeIn .25s ease' }}>
      <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column', maxWidth: 560, margin: '0 auto',
        padding: 'calc(28px + env(safe-area-inset-top)) 22px calc(24px + env(safe-area-inset-bottom))' }}>

        {/* Ruido que Atlas deja atrás */}
        <p style={{ ...serif, fontSize: 'clamp(18px, 5vw, 24px)', lineHeight: 1.2, letterSpacing: -0.3, color: 'rgba(250,250,247,0.42)', margin: '4px 0 18px' }}>
          “La mejor rutina para crecer.”<br />
          “Haz esto y en una semana notarás el cambio.”
        </p>

        <span style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 10.5, fontWeight: 700, letterSpacing: 1.6, textTransform: 'uppercase', color: 'rgba(250,250,247,0.5)' }}>
          Bienvenido a Atlas Method
        </span>

        <h1 style={{ fontFamily: '"Inter",system-ui', fontSize: 'clamp(28px, 8vw, 40px)', fontWeight: 800, letterSpacing: -1, lineHeight: 1.08, margin: '10px 0 16px', color: cream }}>
          Entrena con criterio, no con modas.
        </h1>

        <p style={{ fontFamily: '"Inter",system-ui', fontSize: 'clamp(15px, 4vw, 17px)', lineHeight: 1.6, letterSpacing: -0.15, color: 'rgba(250,250,247,0.82)', margin: '0 0 24px' }}>
          Las redes están llenas de promesas tajantes. Atlas Method nace para <span style={serif}>poner algo de orden en ese ruido</span>: entrenar con fundamento, <span style={serif}>preguntarse por qué antes de hacer</span>, sabiendo que la evidencia cambia y se afina. No se trata de tener todas las respuestas, sino de <span style={serif}>dejar de adivinar</span>.
        </p>

        {/* Qué ofrece */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, margin: '0 0 24px' }}>
          {offerings.map(([t, d], i) => (
            <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <span aria-hidden style={{ flexShrink: 0, marginTop: 7, width: 6, height: 6, borderRadius: '50%', background: '#3B82F6', boxShadow: '0 0 10px rgba(59,130,246,0.7)' }} />
              <div>
                <div style={{ fontFamily: '"Inter",system-ui', fontSize: 15.5, fontWeight: 800, letterSpacing: -0.2, color: cream }}>{t}</div>
                <div style={{ fontFamily: '"Inter",system-ui', fontSize: 13.5, lineHeight: 1.5, color: 'rgba(250,250,247,0.66)', marginTop: 2 }}>{d}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Cierre de marca */}
        <p style={{ ...serif, fontSize: 'clamp(19px, 5.2vw, 26px)', lineHeight: 1.25, letterSpacing: -0.4, color: cream, margin: '0 0 28px' }}>
          El peso lo cargas tú. Nosotros te ayudamos a sostenerlo con criterio.
        </p>

        {/* Acciones (abajo) */}
        <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <button onClick={start} className="wp-press" style={{ width: '100%', minHeight: 52, borderRadius: 14, border: 'none', cursor: 'pointer',
            background: cream, color: '#0F1A2E', fontFamily: '"Inter",system-ui', fontSize: 16, fontWeight: 800, letterSpacing: -0.2 }}>
            Empezar →
          </button>
          {canInstall && (
            <button onClick={openInstall} style={{ width: '100%', background: 'none', border: 'none', cursor: 'pointer',
              fontFamily: '"Inter",system-ui', fontSize: 13.5, fontWeight: 700, color: '#93C5FD' }}>
              ¿Cómo instalar Atlas en tu móvil? →
            </button>
          )}
        </div>
      </div>
    </div>,
    document.body
  );
}

Object.assign(window, { WelcomeGate });
