// Product section — "Simulez. Comparez. Validez."
// 3 étape cards, un par couleur de marque.
// Desktop: cards empilées, toujours ouvertes.
// Mobile: accordéon — seul le step actif est déplié.

function ProductSection({ mobile = false }) {
  const [visible, setVisible] = React.useState(false);
  const [activeBien, setActiveBien] = React.useState(0);
  const [openStep, setOpenStep] = React.useState(0); // mobile accordion
  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`,
  });

  const steps = [
    {
      n: '01',
      title: 'Simulez vos projets',
      accent: TOKENS.bordeaux,
      intro: "Transformez vos intuitions en scénarios concrets. Rentabilité, cashflow, financement, fiscalité — tout au même endroit.",
      ctaLabel: 'Démarrer maintenant',
      ctaSource: 'lpi_product-simulez',
    },
    {
      n: '02',
      title: 'Comparez pour avancer',
      accent: TOKENS.blue,
      intro: "Placez des biens et scénarios côte à côte. Affinez votre décision avec des données fiables.",
      ctaLabel: 'Démarrer maintenant',
      ctaSource: 'lpi_product-comparez',
    },
    {
      n: '03',
      title: "Validez et passez à l'action",
      accent: TOKENS.green,
      intro: "Trouvez l'investissement le plus optimisé. Nos experts valident votre projet avant la signature.",
      ctaLabel: 'Démarrer maintenant',
      ctaSource: 'lpi_product-validez',
    },
  ];

  const biens = [
    { name: 'Studio Paris 12', prix: '225 400 €', notaire: '18 632 €', credit: '985 €', loyer: '1 272 €', cash: '+ 287 €', rent: '6,8 %' },
    { name: 'Studio Vincennes', prix: '198 000 €', notaire: '16 380 €', credit: '862 €', loyer: '1 095 €', cash: '+ 175 €', rent: '4,9 %' },
  ];
  const b = biens[activeBien];

  // Visuals per step
  const stepVisuals = [
    // 01 — scenario table
    (onDark) => (
      <div style={{
        background: '#fff',
        border: `1px solid ${TOKENS.line}`,
        borderRadius: 14,
        padding: mobile ? 14 : 20,
        position: 'relative',
        boxShadow: '0 1px 2px rgba(29,29,29,0.04)',
      }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
          {biens.map((bb, i) => (
            <button key={i} onClick={(e) => { e.stopPropagation(); setActiveBien(i); }} style={{
              background: activeBien === i ? TOKENS.green : 'transparent',
              color: activeBien === i ? TOKENS.ink : TOKENS.ink60,
              border: activeBien === i ? 'none' : `1px solid ${TOKENS.line}`,
              padding: '6px 12px', borderRadius: 999,
              fontFamily: FONTS.sans, fontSize: 12, fontWeight: 600,
              cursor: 'pointer', transition: 'all .2s',
              whiteSpace: 'nowrap',
            }}>{bb.name}</button>
          ))}
        </div>
        {[
          ['Prix d\'achat', b.prix],
          ['Frais de notaire', b.notaire],
          ['Mensualité crédit', b.credit],
          ['Loyer attendu', b.loyer],
          ['Cashflow mensuel', b.cash, true],
        ].map(([k, v, hl], i) => (
          <div key={i} style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: mobile ? '8px 4px' : '11px 4px',
            borderBottom: i < 4 ? `1px solid ${TOKENS.line}` : 'none',
            fontFamily: FONTS.sans, fontSize: mobile ? 13 : 14,
          }}>
            <span style={{ color: TOKENS.ink60 }}>{k}</span>
            <span style={{
              color: hl ? TOKENS.success : TOKENS.ink, fontWeight: hl ? 700 : 500,
              fontFamily: hl ? FONTS.display : FONTS.sans,
              fontVariantNumeric: 'tabular-nums',
            }}>{v}</span>
          </div>
        ))}
      </div>
    ),
    // 02 — comparator (light bg version)
    () => (
      <div style={{
        background: '#fff',
        border: `1px solid ${TOKENS.line}`,
        borderRadius: 14,
        padding: mobile ? 14 : 22,
        position: 'relative',
      }}>
        <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: TOKENS.ink60, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 16 }}>
          Comparateur · 2 biens
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <div style={{
            background: 'rgba(29,29,29,0.03)',
            border: `1px solid ${TOKENS.line}`,
            borderRadius: 10, padding: 14, opacity: 0.75,
          }}>
            <div style={{ fontFamily: FONTS.sans, fontSize: 12, fontWeight: 600, color: TOKENS.ink60, marginBottom: 10 }}>Studio Paris 12</div>
            <div style={{ fontFamily: FONTS.mono, fontSize: 9, color: TOKENS.ink40, textTransform: 'uppercase', letterSpacing: 1.2 }}>Rentabilité nette</div>
            <div style={{ fontFamily: FONTS.display, fontWeight: 700, fontSize: 26, color: TOKENS.ink, letterSpacing: -0.8, marginTop: 2 }}>4,9 %</div>
            <div style={{ fontFamily: FONTS.mono, fontSize: 9, color: TOKENS.ink40, textTransform: 'uppercase', letterSpacing: 1.2, marginTop: 10 }}>Cashflow</div>
            <div style={{ fontFamily: FONTS.sans, fontSize: 14, fontWeight: 600, color: TOKENS.ink80, marginTop: 2 }}>+175 €</div>
          </div>
          <div style={{
            background: '#fff',
            border: `1.5px solid ${TOKENS.green}`,
            borderRadius: 10, padding: 14,
            position: 'relative', boxShadow: '0 12px 30px -12px rgba(200,255,46,0.5)',
          }}>
            <div style={{
              position: 'absolute', top: -10, left: '50%', transform: 'translateX(-50%)',
              background: TOKENS.green, color: TOKENS.ink,
              padding: '3px 10px', borderRadius: 99,
              fontFamily: FONTS.sans, fontSize: 10, fontWeight: 700, whiteSpace: 'nowrap',
            }}>✓ Meilleur</div>
            <div style={{ fontFamily: FONTS.sans, fontSize: 12, fontWeight: 600, color: TOKENS.ink, marginBottom: 10 }}>Studio Vincennes</div>
            <div style={{ fontFamily: FONTS.mono, fontSize: 9, color: TOKENS.ink60, textTransform: 'uppercase', letterSpacing: 1.2 }}>Rentabilité nette</div>
            <div style={{ fontFamily: FONTS.display, fontWeight: 700, fontSize: 26, color: TOKENS.ink, letterSpacing: -0.8, marginTop: 2 }}>6,8 %</div>
            <div style={{ fontFamily: FONTS.mono, fontSize: 9, color: TOKENS.ink60, textTransform: 'uppercase', letterSpacing: 1.2, marginTop: 10 }}>Cashflow</div>
            <div style={{ fontFamily: FONTS.sans, fontSize: 14, fontWeight: 700, color: TOKENS.greenDark, marginTop: 2 }}>+287 €</div>
          </div>
        </div>
      </div>
    ),
    // 03 — report
    () => (
      <div style={{
        background: '#fff',
        border: `1px solid ${TOKENS.line}`,
        borderRadius: 14,
        padding: mobile ? 14 : 20,
        boxShadow: '0 1px 2px rgba(29,29,29,0.04)',
      }}>
        <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: TOKENS.ink60, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 14 }}>
          Rapport · Projet validé
        </div>
        {[
          ['Analyse fiscalité', 'Optimale'],
          ['Capacité d\'emprunt', 'Confirmée'],
          ['Cashflow 10 ans', 'Positif'],
          ['Red flags détectés', '0', 'neutral'],
        ].map(([k, v, kind], i) => (
          <div key={i} style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: mobile ? '8px 4px' : '11px 4px',
            borderBottom: '1px solid ' + TOKENS.line,
            fontFamily: FONTS.sans, fontSize: mobile ? 13 : 14,
          }}>
            <span style={{ color: TOKENS.ink60 }}>{k}</span>
            <span style={{
              color: kind === 'neutral' ? TOKENS.ink : TOKENS.greenDark,
              fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', gap: 5,
            }}>
              {kind !== 'neutral' && <span aria-hidden>✓</span>}
              {v}
            </span>
          </div>
        ))}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, paddingTop: 14 }}>
          <div style={{ display: 'flex' }}>
            {[
              { src: 'assets/expert-homme.jpg', pos: '50% 28%' },
              { src: 'assets/expert-femme.jpg', pos: '50% 28%' },
            ].map((a, i) => (
              <div key={i} style={{
                width: 34, height: 34, borderRadius: 99,
                backgroundImage: `url(${a.src})`,
                backgroundSize: 'cover',
                backgroundPosition: a.pos,
                border: '2px solid #fff',
                marginLeft: i ? -10 : 0,
                boxShadow: '0 2px 4px rgba(0,0,0,0.12)',
                flexShrink: 0,
              }}/>
            ))}
          </div>
          <div>
            <div style={{ fontFamily: FONTS.sans, fontSize: 13, fontWeight: 600, color: TOKENS.ink }}>
              Validé par nos experts
            </div>
            <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: TOKENS.ink60, letterSpacing: 0.5 }}>
              Moneyshapers
            </div>
          </div>
        </div>
      </div>
    ),
  ];

  // ────────── MOBILE: ACCORDION ──────────
  if (mobile) {
    return (
      <section ref={ref} id="comment-ca-marche" style={{
        width: '100%', padding: '80px 20px 60px',
        background: TOKENS.paper, position: 'relative',
        scrollMarginTop: 80,
      }}>
        {/* heading */}
        <div style={{ textAlign: 'center', marginBottom: 40, ...reveal(0) }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            fontFamily: FONTS.mono, fontSize: 10,
            color: TOKENS.bordeaux, textTransform: 'uppercase', letterSpacing: 2,
            marginBottom: 18,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 99, background: TOKENS.bordeaux }}/>
            Comment ça marche
            <span style={{ width: 6, height: 6, borderRadius: 99, background: TOKENS.bordeaux }}/>
          </div>
          <h2 style={{
            fontFamily: FONTS.display, fontWeight: 700,
            fontSize: 40, lineHeight: 1, letterSpacing: -1.4,
            margin: 0, color: TOKENS.ink,
          }}>
            Simulez. Comparez. Validez<span style={{ color: TOKENS.bordeaux }}>.</span>
          </h2>
        </div>

        {/* accordion stack */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {steps.map((s, i) => {
            const isOpen = openStep === i;
            return (
              <div key={i} style={{
                background: TOKENS.paper,
                border: `1px solid ${TOKENS.line}`,
                borderLeft: `4px solid ${s.accent}`,
                borderRadius: 18,
                overflow: 'hidden',
                transition: 'all .4s cubic-bezier(.2,.7,.2,1)',
                ...reveal(1 + i),
              }}>
                {/* Header row — always visible, clickable */}
                <button
                  onClick={() => setOpenStep(isOpen ? -1 : i)}
                  aria-expanded={isOpen}
                  style={{
                    width: '100%',
                    background: 'transparent', border: 'none',
                    padding: '22px 22px 20px',
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    gap: 14, cursor: 'pointer',
                    textAlign: 'left',
                  }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 16, flex: 1, minWidth: 0 }}>
                    <span style={{
                      fontFamily: FONTS.display, fontWeight: 700,
                      fontSize: 34, lineHeight: 1, letterSpacing: -1.2,
                      color: s.accent, flexShrink: 0,
                      fontVariantNumeric: 'tabular-nums',
                    }}>{s.n}</span>
                    <span style={{
                      fontFamily: FONTS.display, fontWeight: 700,
                      fontSize: 18, lineHeight: 1.2, letterSpacing: -0.4,
                      color: TOKENS.ink,
                    }}>
                      {s.title}
                      <span style={{ color: s.accent }}>.</span>
                    </span>
                  </div>
                  {/* Chevron */}
                  <span style={{
                    flexShrink: 0,
                    width: 28, height: 28, borderRadius: 99,
                    background: TOKENS.ink06,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    transition: 'transform .35s cubic-bezier(.2,.7,.2,1)',
                    transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                  }}>
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                      <path d="M3 4.5L6 7.5L9 4.5" stroke={TOKENS.ink} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </span>
                </button>

                {/* Body — collapsible */}
                <div style={{
                  display: 'grid',
                  gridTemplateRows: isOpen ? '1fr' : '0fr',
                  transition: 'grid-template-rows .45s cubic-bezier(.2,.7,.2,1)',
                }}>
                  <div style={{ overflow: 'hidden' }}>
                    <div style={{ padding: '4px 22px 26px' }}>
                      <p style={{
                        fontFamily: FONTS.sans, fontSize: 14, lineHeight: 1.55,
                        color: TOKENS.ink60,
                        margin: '0 0 20px',
                      }}>
                        {s.intro}
                      </p>
                      <div style={{ marginBottom: 22 }}>
                        {stepVisuals[i]()}
                      </div>
                      <button data-cta-source={s.ctaSource} style={{
                        background: TOKENS.bordeaux, color: '#fff', border: 'none',
                        padding: '14px 24px', borderRadius: 12, fontSize: 15, fontWeight: 600,
                        fontFamily: FONTS.sans, cursor: 'pointer',
                        display: 'inline-flex', alignItems: 'center', gap: 10,
                        boxShadow: '0 10px 30px -5px rgba(92,13,7,0.4)',
                      }}>
                        {s.ctaLabel}
                        <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>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </section>
    );
  }

  // ────────── DESKTOP: full stacked cards (unchanged) ──────────
  return (
    <section ref={ref} id="comment-ca-marche" style={{
      width: '100%', padding: '120px 56px 100px',
      background: TOKENS.paper, position: 'relative',
      scrollMarginTop: 80,
    }}>
      <div style={{ textAlign: 'center', marginBottom: 64, ...reveal(0) }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          fontFamily: FONTS.mono, fontSize: 11,
          color: TOKENS.bordeaux, textTransform: 'uppercase', letterSpacing: 2,
          marginBottom: 22,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 99, background: TOKENS.bordeaux }}/>
          Comment ça marche
          <span style={{ width: 6, height: 6, borderRadius: 99, background: TOKENS.bordeaux }}/>
        </div>
        <h2 style={{
          fontFamily: FONTS.display, fontWeight: 700,
          fontSize: 72, lineHeight: 1, letterSpacing: -2.4,
          margin: 0, color: TOKENS.ink,
        }}>
          Simulez. Comparez. Validez<span style={{ color: TOKENS.bordeaux }}>.</span>
        </h2>
      </div>

      <div style={{
        maxWidth: 1100, margin: '0 auto',
        display: 'flex', flexDirection: 'column', gap: 18,
      }}>
        {steps.map((s, i) => {
          const leftFirst = i !== 1; // 01 & 03 = text left, 02 = visual left
          const TextPane = (
            <div style={{ position: 'relative' }}>
              {/* Huge step number */}
              <div style={{
                fontFamily: FONTS.display, fontWeight: 700,
                fontSize: 96, lineHeight: 0.9, letterSpacing: -4,
                color: s.accent, marginBottom: 10,
                fontVariantNumeric: 'tabular-nums',
              }}>{s.n}</div>
              <h3 style={{
                fontFamily: FONTS.display, fontWeight: 700,
                fontSize: 36, lineHeight: 1.1, letterSpacing: -1,
                margin: '0 0 14px', color: TOKENS.ink,
              }}>
                {s.title}<span style={{ color: s.accent }}>.</span>
              </h3>
              <p style={{
                fontFamily: FONTS.sans, fontSize: 15, lineHeight: 1.55,
                color: TOKENS.ink60,
                margin: '0 0 24px', maxWidth: 380,
              }}>{s.intro}</p>
              <button data-cta-source={s.ctaSource} style={{
                background: TOKENS.bordeaux, color: '#fff', border: 'none',
                padding: '14px 24px', borderRadius: 12, fontSize: 15, fontWeight: 600,
                fontFamily: FONTS.sans, cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 10,
                boxShadow: '0 10px 30px -5px rgba(92,13,7,0.4)',
              }}>
                {s.ctaLabel}
                <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>
          );

          return (
            <div key={i} style={{
              background: TOKENS.paper,
              border: `1px solid ${TOKENS.line}`,
              borderLeft: `6px solid ${s.accent}`,
              borderRadius: 22,
              padding: '48px 56px',
              color: TOKENS.ink,
              position: 'relative', overflow: 'hidden',
              display: 'grid',
              gridTemplateColumns: i === 1 ? '1.05fr 1fr' : '1fr 1.1fr',
              gap: 56,
              alignItems: 'center',
              ...reveal(1 + i),
            }}>
              {leftFirst ? <>{TextPane}{stepVisuals[i]()}</> : <>{stepVisuals[i]()}{TextPane}</>}
            </div>
          );
        })}
      </div>
    </section>
  );
}

window.ProductSection = ProductSection;
