// "Pourquoi simuler" section — argumentaire chiffré
// 1 grande carte dark avec photo haussmannienne en fond.
// Gauche : headline + CTA. Droite : 4 stat rows dont la dernière accentuée.

// Count-up animé avec easeOutCubic — démarre quand `active` devient true
function AnimatedNumber({ value, active, duration = 1400, delay = 0, formatThousands = false }) {
  const [display, setDisplay] = React.useState(0);
  const started = React.useRef(false);

  React.useEffect(() => {
    if (!active || started.current) return;
    started.current = true;
    const t0 = performance.now() + delay;
    const ease = (t) => 1 - Math.pow(1 - t, 3);
    let raf;
    const tick = (now) => {
      if (now < t0) { raf = requestAnimationFrame(tick); return; }
      const t = Math.min(1, (now - t0) / duration);
      setDisplay(Math.round(value * ease(t)));
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [active, value, duration, delay]);

  const txt = formatThousands
    ? display.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '\u00A0')
    : display.toString();
  return <>{txt}</>;
}

function WhySimulateSection({ mobile = false }) {
  const [visible, setVisible] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setVisible(true); });
    }, { threshold: 0.15 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, []);

  const reveal = (i) => ({
    opacity: visible ? 1 : 0,
    transform: visible ? 'translateY(0)' : 'translateY(16px)',
    transition: `opacity .8s cubic-bezier(.2,.7,.2,1) ${i * 110}ms, transform .8s cubic-bezier(.2,.7,.2,1) ${i * 110}ms`,
  });

  // Stat data — target values are numeric for count-up
  const stats = [
    { target: 40,   formatThousands: false, unit: '%', label: 'des investissements locatifs ne sont pas rentables', sub: 'Faute de bons calculs' },
    { target: 73,   formatThousands: false, unit: '%', label: 'des Français se sentent démunis', sub: 'Face à l\'investissement' },
    { target: 30,   formatThousands: false, unit: '%', label: 'des primo-investisseurs regrettent leur premier achat', sub: 'Faute d\'analyse préalable' },
    { target: 2500, formatThousands: true,  unit: '€', label: 'le coût moyen d\'un accompagnement traditionnel', sub: 'Pas avec Moneyshape.', highlight: true },
  ];

  // Photo haussmannienne réelle
  const HaussmannBg = () => (
    <div aria-hidden style={{
      position: 'absolute', inset: 0, overflow: 'hidden',
      background: '#5a4d3f',
    }}>
      <img src="assets/photo-haussmann.jpg" alt="" style={{
        width: '100%', height: '100%',
        objectFit: 'cover', objectPosition: 'center 55%',
        display: 'block',
        filter: 'saturate(0.9) brightness(0.88)',
      }}/>
    </div>
  );

  return (
    <section ref={ref} style={{
      width: '100%',
      padding: mobile ? '60px 20px 80px' : '100px 56px 120px',
      background: TOKENS.paper,
      position: 'relative',
    }}>
      {/* Heading */}
      <div style={{ textAlign: 'center', marginBottom: mobile ? 36 : 56, ...reveal(0) }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          fontFamily: FONTS.mono, fontSize: mobile ? 10 : 11,
          color: TOKENS.bordeaux, textTransform: 'uppercase', letterSpacing: 2,
          marginBottom: mobile ? 18 : 22,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 99, background: TOKENS.bordeaux }}/>
          Pourquoi simuler
          <span style={{ width: 6, height: 6, borderRadius: 99, background: TOKENS.bordeaux }}/>
        </div>
        <h2 style={{
          fontFamily: FONTS.display, fontWeight: 700,
          fontSize: mobile ? 38 : 64, lineHeight: 1.02,
          letterSpacing: mobile ? -1.2 : -2.2,
          margin: 0, color: TOKENS.ink,
          textWrap: 'balance',
        }}>
          Pourquoi simuler avant d'investir&nbsp;?
        </h2>
      </div>

      {/* Main card */}
      <div style={{
        maxWidth: 1200, margin: '0 auto',
        position: 'relative', overflow: 'hidden',
        borderRadius: mobile ? 18 : 26,
        color: '#fff',
        ...reveal(1),
      }}>
        <HaussmannBg/>
        {/* Warm dark overlay */}
        <div aria-hidden style={{
          position: 'absolute', inset: 0,
          background: mobile
            ? 'linear-gradient(180deg, rgba(20,10,6,0.55) 0%, rgba(18,10,6,0.84) 55%, rgba(14,8,6,0.92) 100%)'
            : 'linear-gradient(90deg, rgba(18,10,6,0.88) 0%, rgba(20,12,8,0.74) 45%, rgba(24,14,10,0.55) 100%)',
          pointerEvents: 'none',
        }}/>
        {/* Grain 0.08 */}
        <div aria-hidden style={{
          position: 'absolute', inset: 0,
          backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='160' height='160'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 1  0 0 0 0 1  0 0 0 0 1  0 0 0 0.55 0'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>\")",
          opacity: 0.08,
          mixBlendMode: 'overlay',
          pointerEvents: 'none',
        }}/>

        <div style={{
          position: 'relative',
          display: 'grid',
          gridTemplateColumns: mobile ? '1fr' : '1fr 1.15fr',
          gap: mobile ? 32 : 40,
          padding: mobile ? '36px 26px 36px' : '60px 56px',
          alignItems: 'center',
        }}>
          {/* LEFT — headline + CTA */}
          <div>
            <h3 style={{
              fontFamily: FONTS.display, fontWeight: 600,
              fontSize: mobile ? 24 : 28, lineHeight: 1.25, letterSpacing: -0.6,
              color: '#fff',
              margin: '0 0 28px', maxWidth: 380,
            }}>
              L'immobilier locatif peut être <span style={{ color: TOKENS.green }}>très rentable</span>. Mais sans analyse, les erreurs coûtent cher.
            </h3>
            <button data-cta-source="lpi_why-simulate" style={{
              background: TOKENS.bordeaux, color: '#fff', border: 'none',
              padding: '16px 26px', borderRadius: 12,
              fontFamily: FONTS.sans, fontSize: 16, fontWeight: 600,
              cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 10,
              boxShadow: '0 10px 30px -5px rgba(92,13,7,0.4)',
            }}>
              Démarrer maintenant
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                <path d="M2 8h11m0 0L8 3m5 5l-5 5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
              </svg>
            </button>
          </div>

          {/* RIGHT — stats stack (desktop) / grid 2×2 (mobile) */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: mobile ? '1fr 1fr' : '1fr',
            gap: mobile ? 10 : 2,
          }}>
            {stats.map((s, i) => {
              const rowDelay = 300 + i * 140;
              const cellStyleMobile = {
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'flex-start',
                gap: 6,
                padding: '16px 14px',
                background: s.highlight ? 'rgba(10,8,6,0.55)' : 'rgba(255,255,255,0.04)',
                borderRadius: 12,
                border: '1px solid ' + (s.highlight ? 'rgba(200,255,46,0.25)' : 'rgba(255,255,255,0.08)'),
              };
              const cellStyleDesktop = {
                display: 'grid',
                gridTemplateColumns: '170px 1fr',
                alignItems: 'center',
                gap: 22,
                padding: '18px 22px',
                background: s.highlight ? 'rgba(10,8,6,0.55)' : 'transparent',
                borderRadius: s.highlight ? 12 : 0,
                border: s.highlight ? '1px solid rgba(255,255,255,0.08)' : 'none',
              };
              return (
              <div key={i} style={{
                ...(mobile ? cellStyleMobile : cellStyleDesktop),
                opacity: visible ? 1 : 0,
                transform: visible ? 'translateX(0)' : 'translateX(20px)',
                transition: `opacity .7s cubic-bezier(.2,.7,.2,1) ${rowDelay}ms, transform .7s cubic-bezier(.2,.7,.2,1) ${rowDelay}ms`,
              }}>
                {/* Big number */}
                <div style={{
                  fontFamily: FONTS.display, fontWeight: 700,
                  fontSize: mobile ? 32 : 46, lineHeight: 1,
                  letterSpacing: mobile ? -1.2 : -1.5, color: '#fff',
                  fontVariantNumeric: 'tabular-nums',
                  display: 'flex', alignItems: 'baseline', gap: 2,
                  whiteSpace: 'nowrap',
                }}>
                  <AnimatedNumber
                    value={s.target}
                    active={visible}
                    duration={1400}
                    delay={rowDelay + 100}
                    formatThousands={s.formatThousands}
                  />
                  <span style={{
                    fontSize: mobile ? 16 : 22,
                    color: TOKENS.green,
                    fontWeight: 700,
                    opacity: visible ? 1 : 0,
                    transform: visible ? 'translateY(0) scale(1)' : 'translateY(-4px) scale(0.6)',
                    transition: `opacity .5s cubic-bezier(.2,.7,.2,1) ${rowDelay + 1500}ms, transform .5s cubic-bezier(.2,1.4,.5,1) ${rowDelay + 1500}ms`,
                    display: 'inline-block',
                  }}>{s.unit}</span>
                </div>
                {/* Label + sub */}
                <div>
                  <div style={{
                    fontFamily: FONTS.sans, fontSize: mobile ? 12 : 14,
                    fontWeight: 500, lineHeight: 1.3,
                    color: 'rgba(255,255,255,0.95)',
                  }}>
                    {s.label}
                  </div>
                  <div style={{
                    fontFamily: FONTS.sans, fontSize: mobile ? 10.5 : 12,
                    color: s.highlight ? TOKENS.green : 'rgba(255,255,255,0.5)',
                    fontWeight: s.highlight ? 600 : 400,
                    marginTop: 3,
                    lineHeight: 1.3,
                  }}>
                    {s.sub}
                  </div>
                </div>
              </div>
            );})}
          </div>
        </div>
      </div>
    </section>
  );
}

window.WhySimulateSection = WhySimulateSection;
