// welcome-preview.jsx — Pantalla 9 del funnel. Es la pantalla más
// importante del flujo: el user llega aquí después de hacer click en el
// botón del email de aceptación. Le mostramos TODO lo que personalizamos
// para él (substeps animados, stats grandes, lista de tareas reales,
// documento seed con título real, welcomeNote, acceptanceMessage), y al
// final un CTA gigante "Activar mi acceso ($15 USD/mes)" → Stripe Checkout.
//
// Llega aquí vía: email → /api/onboarding/welcome?token=... → server valida
// y redirige a /onboarding/welcome (SPA). App.jsx en Workspace.html
// intercepta ese path y monta este componente.

(function () {
  const { useState, useEffect, useRef, 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: 'fixed', 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%),
                     ${C.bg}`,
      }}>
        <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>
    );
  }

  // Count-up animation para los stats grandes.
  function _StatCount({ target, label }) {
    const [n, setN] = useState(0);
    useEffect(() => {
      const t0 = Date.now();
      const dur = 900;
      const id = setInterval(() => {
        const p = Math.min(1, (Date.now() - t0) / dur);
        // easeOutCubic
        const eased = 1 - Math.pow(1 - p, 3);
        setN(Math.round(target * eased));
        if (p >= 1) clearInterval(id);
      }, 32);
      return () => clearInterval(id);
    }, [target]);
    return (
      <div style={{
        padding: 'clamp(16px, 2.5vw, 26px) clamp(14px, 2vw, 22px)',
        background: C.bgCard,
        border: `1px solid ${C.border}`,
        borderRadius: 16,
        textAlign: 'left',
      }}>
        <div style={{
          fontFamily: HEAD_FONT, fontWeight: 800,
          fontSize: 'clamp(36px, 5vw, 64px)',
          color: C.accent, lineHeight: 1,
          letterSpacing: '-0.03em',
          fontVariantNumeric: 'tabular-nums',
        }}>{n}</div>
        <div style={{
          marginTop: 8,
          fontFamily: UI_FONT, fontSize: 12,
          color: C.t2, letterSpacing: 0.4,
          textTransform: 'lowercase',
        }}>{label}</div>
      </div>
    );
  }

  function _Substep({ index, label, sub, isLast, revealed }) {
    if (!revealed) return null;
    return (
      <div style={{
        display: 'flex', alignItems: 'flex-start', gap: 14,
        padding: '14px 16px', borderRadius: 12,
        background: isLast ? 'rgba(16,185,129,0.08)' : C.accentSoft,
        border: `1px solid ${isLast ? 'rgba(16,185,129,0.32)' : 'rgba(249,115,22,0.32)'}`,
        animation: 'wp-fade-up .35s ease both',
      }}>
        <div style={{
          width: 28, height: 28, borderRadius: 8,
          background: isLast ? C.success : C.accent, color: '#fff',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: UI_FONT, fontSize: 14, fontWeight: 600, color: C.t0, marginBottom: sub ? 4 : 0 }}>
            {label}
          </div>
          {sub && (
            <div style={{ fontFamily: UI_FONT, fontSize: 12.5, color: C.t1, lineHeight: 1.5 }}>
              {sub}
            </div>
          )}
        </div>
      </div>
    );
  }

  function _PriorityChip({ priority }) {
    const map = {
      P1: { color: '#ef4444', label: 'Alta' },
      P2: { color: '#f59e0b', label: 'Media' },
      P3: { color: '#a3a3a3', label: 'Baja' },
    };
    const m = map[priority] || map.P2;
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center',
        padding: '2px 8px', borderRadius: 4,
        background: `${m.color}22`, color: m.color,
        fontFamily: UI_FONT, fontSize: 10.5, fontWeight: 700,
        letterSpacing: 0.4, textTransform: 'uppercase',
      }}>{m.label}</span>
    );
  }

  function WelcomePreview() {
    const [state, setState] = useState(null);  // server data
    const [error, setError] = useState(null);
    const [revealed, setRevealed] = useState(0);
    const [activating, setActivating] = useState(false);
    // Ref al contenedor con overflow:auto — es ESE el que scrollea (no el
    // window, porque el shell tiene position:fixed). Sin esto, el browser
    // restaura posición vieja al hacer back/forward y la pantalla aparece
    // a media tabla.
    const scrollHostRef = useRef(null);

    // Forzar scroll arriba al montar y también después de que el state
    // cargue (cuando el DOM final con todo el contenido aparece). El
    // botón "Hacerlo mío" ya NO tiene autoFocus, así que el browser no
    // intenta llevárselo a la vista.
    useEffect(() => {
      try {
        if ('scrollRestoration' in window.history) {
          window.history.scrollRestoration = 'manual';
        }
        window.scrollTo(0, 0);
        document.documentElement.scrollTop = 0;
        document.body.scrollTop = 0;
        if (scrollHostRef.current) scrollHostRef.current.scrollTop = 0;
      } catch (_e) {}
    }, []);

    useEffect(() => {
      if (!state) return;
      // Dos rAFs: uno para esperar al DOM tras setState, otro para esperar
      // al layout final tras animaciones/imágenes. Sin esto el contenedor
      // recién montado todavía no existe.
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          try {
            if (scrollHostRef.current) scrollHostRef.current.scrollTop = 0;
            window.scrollTo(0, 0);
          } catch (_e) {}
        });
      });
    }, [state]);

    useEffect(() => {
      let cancelled = false;
      (async () => {
        try {
          const r = await fetch('/api/onboarding/welcome-state', { credentials: 'include' });
          if (r.status === 401) {
            // Cookie perdida — mandar al login con hint.
            window.location.href = '/login?from=welcome-no-cookie';
            return;
          }
          if (!r.ok) {
            const body = await r.json().catch(() => ({}));
            throw new Error(body?.message || `HTTP ${r.status}`);
          }
          const data = await r.json();
          if (!cancelled) setState(data);
        } catch (e) {
          if (!cancelled) setError(e?.message || 'No se pudo cargar tu workspace.');
        }
      })();
      return () => { cancelled = true; };
    }, []);

    // Reveal cascada de substeps cada 350ms tras carga.
    useEffect(() => {
      if (!state) return;
      const id = setInterval(() => {
        setRevealed((r) => (r < 4 ? r + 1 : r));
      }, 380);
      return () => clearInterval(id);
    }, [state]);

    // Meta Pixel — esta es la "key moment" antes del checkout.
    useEffect(() => {
      if (typeof window.fbq === 'function') {
        try { window.fbq('track', 'ViewContent', { content_name: 'welcome_preview' }); } catch (_e) {}
      }
    }, []);

    const activate = useCallback(async () => {
      if (activating) return;
      setActivating(true);
      try {
        if (typeof window.fbq === 'function') {
          try { window.fbq('track', 'InitiateCheckout', { content_name: 'workspace_ai_monthly', currency: 'USD', value: 15 }); } catch (_e) {}
        }
        await window.startCheckout();
      } catch (e) {
        setActivating(false);
        setError(e?.message || 'No pudimos abrir el checkout. Intenta de nuevo.');
      }
    }, [activating]);

    if (error) {
      return (
        <div style={{ position: 'fixed', inset: 0, background: C.bg, color: C.t0, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
          <_Backdrop />
          <div style={{ position: 'relative', zIndex: 1, maxWidth: 480, textAlign: 'center', fontFamily: UI_FONT }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: C.t0, marginBottom: 10 }}>Algo salió mal.</div>
            <div style={{ fontSize: 14, color: C.t1, lineHeight: 1.55, marginBottom: 22 }}>{error}</div>
            <a href="/" style={{ display: 'inline-block', padding: '12px 20px', borderRadius: 10, background: C.accent, color: '#fff', textDecoration: 'none', fontWeight: 700 }}>Volver al inicio</a>
          </div>
        </div>
      );
    }
    if (!state) {
      return (
        <div style={{ position: 'fixed', inset: 0, background: C.bg, color: C.t2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: UI_FONT, fontSize: 14 }}>
          Cargando tu workspace…
        </div>
      );
    }

    const name = state.displayName || 'tú';
    const taskCount = state.stats?.tasks ?? 0;
    const docCount = state.stats?.documents ?? 0;
    const phaseCount = state.stats?.phases ?? 0;
    const projectName = state.project?.name || 'Tu proyecto';
    const firstThreeTasks = (state.tasks || []).slice(0, 3);
    const firstDoc = (state.documents || [])[0];
    const phases = state.phases || [];

    // Quitamos el "{Nombre}, " que la AI suele poner al inicio para evitar
    // que el nombre se repita (ya está en el h1).
    const trimmedAcceptance = (() => {
      const raw = (state.acceptanceMessage || '').trim();
      if (!raw) return '';
      const first = name.trim();
      if (!first) return raw;
      const re = new RegExp('^' + first.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*[,:;\\-—–]\\s*', 'i');
      let out = raw.replace(re, '');
      // Si quedó empezando con minúscula, capitalizamos.
      if (out && out !== raw) out = out.charAt(0).toUpperCase() + out.slice(1);
      return out;
    })();

    return (
      <div ref={scrollHostRef} style={{
        position: 'fixed', inset: 0, background: C.bg, color: C.t0,
        overflow: 'auto', fontFamily: UI_FONT,
      }}>
        <style>{`
          @keyframes wp-fade-up {
            from { opacity: 0; transform: translateY(6px); }
            to   { opacity: 1; transform: translateY(0); }
          }
        `}</style>
        <_Backdrop />
        <div style={{
          position: 'relative', zIndex: 1,
          padding: 'clamp(28px, 5vw, 56px) clamp(20px, 4vw, 48px)',
          maxWidth: 880, margin: '0 auto',
        }}>
          <div style={{
            fontFamily: UI_FONT, fontWeight: 700, fontSize: 12,
            letterSpacing: '1.6px', textTransform: 'uppercase',
            color: C.success, marginBottom: 22,
            display: 'inline-flex', alignItems: 'center', gap: 8,
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={C.success} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            Bienvenido al movimiento
          </div>
          <h1 style={{
            fontFamily: HEAD_FONT, fontSize: 'clamp(36px, 6vw, 68px)',
            lineHeight: 1.02, letterSpacing: '-0.03em',
            fontWeight: 800, color: C.t0, margin: '0 0 18px',
          }}>
            {name} esto es lo que<br/>
            <span style={{ color: C.accent }}>personalizamos para ti.</span>
          </h1>
          {trimmedAcceptance && (
            <p style={{
              fontFamily: UI_FONT, fontSize: 'clamp(15px, 2vw, 18px)',
              lineHeight: 1.6, color: C.t1,
              margin: '0 0 22px', maxWidth: 760,
            }}>
              {trimmedAcceptance}
            </p>
          )}

          {/* welcomeNote — debajo del acceptanceMessage, reemplaza los
              substeps que solían vivir aquí. Halago de habilidades del user
              + confirmación de que el workspace está alineado a sus
              objetivos, SIN promesas de outcomes ni timelines. */}
          {state.welcomeNote && (
            <div style={{
              padding: '18px 22px', borderRadius: 14,
              background: C.bgCard, border: `1px solid ${C.border}`,
              borderLeft: `3px solid ${C.accent}`,
              fontFamily: UI_FONT, fontSize: 15, lineHeight: 1.6, color: C.t1,
              marginBottom: 36, maxWidth: 760,
            }}>
              {state.welcomeNote}
            </div>
          )}

          {/* Stats grandes */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',
            gap: 12, marginBottom: 36,
          }}>
            <_StatCount target={taskCount} label="tareas" />
            <_StatCount target={docCount} label={docCount === 1 ? 'documento' : 'documentos'} />
            <_StatCount target={phaseCount} label={phaseCount === 1 ? 'fase' : 'fases'} />
            <_StatCount target={1} label="proyecto" />
          </div>

          {/* Proyecto + lista preview de tareas */}
          <div style={{
            padding: 'clamp(18px, 3vw, 26px)',
            background: C.bgCard, border: `1px solid ${C.border}`,
            borderRadius: 16, marginBottom: 24,
          }}>
            <div style={{
              fontFamily: UI_FONT, fontWeight: 700, fontSize: 11,
              letterSpacing: 1.4, textTransform: 'uppercase',
              color: C.accent, marginBottom: 8,
            }}>
              Proyecto
            </div>
            <div style={{
              fontFamily: HEAD_FONT, fontSize: 'clamp(20px, 3vw, 26px)',
              fontWeight: 700, color: C.t0, letterSpacing: '-0.01em',
              marginBottom: 18,
            }}>
              {projectName}
            </div>
            {firstThreeTasks.length > 0 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {firstThreeTasks.map((t) => (
                  <div key={t.id} style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '10px 14px', borderRadius: 10,
                    background: 'rgba(255,255,255,0.02)',
                    border: '1px solid rgba(255,255,255,0.05)',
                  }}>
                    <span style={{
                      fontFamily: 'Geist Mono, monospace',
                      fontSize: 11, color: C.t3,
                      flexShrink: 0,
                    }}>{t.id}</span>
                    <span style={{ flex: 1, minWidth: 0, fontSize: 14, color: C.t0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {t.title}
                    </span>
                    <_PriorityChip priority={t.priority} />
                  </div>
                ))}
                {taskCount > 3 && (
                  <div style={{
                    padding: '8px 14px', fontSize: 12.5, color: C.t2,
                    fontFamily: UI_FONT, fontStyle: 'italic',
                  }}>
                    y {taskCount - 3} más esperándote dentro del workspace.
                  </div>
                )}
              </div>
            )}
            {firstDoc && (
              <div style={{
                marginTop: 14, padding: '12px 14px', borderRadius: 10,
                background: 'rgba(255,255,255,0.02)',
                border: '1px solid rgba(255,255,255,0.05)',
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 6,
                  background: C.accentSoft, color: C.accent,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, color: C.t0, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {firstDoc.title}
                  </div>
                  <div style={{ fontSize: 12, color: C.t3, fontFamily: 'Geist Mono, monospace' }}>
                    documento seed
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* CTA Stripe — centrado. Copy "claim ownership" en vez del
              flojo "Tu workspace está activado / Activar mi acceso". */}
          <div style={{
            padding: 'clamp(28px, 4vw, 40px) clamp(22px, 3.5vw, 36px)',
            background: 'linear-gradient(135deg, rgba(249,115,22,0.10), rgba(249,115,22,0.02))',
            border: '1px solid rgba(249,115,22,0.3)',
            borderRadius: 18,
            textAlign: 'center',
          }}>
            <div style={{
              fontFamily: HEAD_FONT, fontSize: 'clamp(22px, 3.2vw, 32px)',
              fontWeight: 800, color: C.t0, letterSpacing: '-0.02em',
              lineHeight: 1.1, marginBottom: 24,
            }}>
              Está armado.<br/>Falta que sea tuyo.
            </div>
            <button
              onClick={activate}
              disabled={activating}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 12,
                padding: '19px 36px', borderRadius: 14, border: 'none',
                background: activating ? 'rgba(249,115,22,0.4)' : C.accent,
                color: '#fff',
                fontFamily: UI_FONT, fontSize: 'clamp(16px, 1.9vw, 18px)',
                fontWeight: 700, letterSpacing: '-0.1px',
                cursor: activating ? 'wait' : 'pointer',
                boxShadow: activating ? 'none' : `0 26px 58px -18px ${C.accentGlow}`,
                transition: 'transform .08s ease',
              }}
              onMouseEnter={(e) => { if (!activating) e.currentTarget.style.transform = 'translateY(-1px)'; }}
              onMouseLeave={(e) => { if (!activating) e.currentTarget.style.transform = 'translateY(0)'; }}
            >
              {activating ? 'Abriendo Stripe…' : 'Hacerlo mío'}
              {!activating && <svg width="18" height="18" 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>
        </div>
      </div>
    );
  }

  window.WelcomePreview = WelcomePreview;
})();
