// Testimonials section — "Ils ont simulé avant d'acheter."
// Carousel avec focus central : 3 cartes visibles, celle du milieu en avant.

function TestimonialsSection({ mobile = false }) {
  const [visible, setVisible] = React.useState(false);
  const [active, setActive] = React.useState(4); // milieu (0..8)
  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`,
  });

  // Palette des badges — on cycle dans 4 couleurs de marque.
  // Chaque témoignage utilise UNE accent : badge + initiales avatar identiques.
  const GREEN = { bg: TOKENS.green, fg: TOKENS.ink };
  const BLUE = { bg: TOKENS.blue, fg: '#fff' };
  const CORAL = { bg: TOKENS.coral, fg: '#fff' };
  const DARK = { bg: TOKENS.ink, fg: '#fff' };
  const PALETTES = [GREEN, BLUE, CORAL, DARK];

  // 9 témoignages — l'accent couleur cycle automatiquement (index % 3)
  const items = [
    { tag: '+140 € / MOIS', stars: 5,
      quote: "Après mon 1er bien, j'ai voulu optimiser le 2ème. Le simulateur m'a fait réaliser qu'un 3 pièces dans ce quartier serait plus rentable qu'un studio en hypercentre. Résultat : +140 €/mois de cashflow qui tombent vraiment dans ma poche.",
      name: 'Anaïs D.', city: 'Paris', initials: 'AD' },
    { tag: '12 K€ ÉCONOMISÉS', stars: 5,
      quote: "Premier achat, donc forcément stressée. Les analyses m'ont donné des arguments concrets pour décider et négocier. J'ai gagné 12 K€ sur le prix en pointant les travaux nécessaires. Sans ça, j'aurais accepté le prix demandé.",
      name: 'Laura H.', city: 'Nantes', initials: 'LH' },
    { tag: 'ERREUR ÉVITÉE', stars: 4,
      quote: "J'ai failli acheter un studio bien placé, mais les simulations ont montré que la renta ne serait pas celle annoncée. J'ai continué à chercher et trouvé mieux 2 mois après.",
      name: 'David G.', city: 'Paris', initials: 'DG' },
    { tag: '+320 € / MOIS', stars: 5,
      quote: "Je gérais mes calculs sur Excel depuis des années, mais c'était chronophage et source d'erreurs. Là, en 10 minutes j'ai une vision complète : impôts, charges, vacance locative. Mon dernier T3 à Lyon tourne à +320 €/mois net.",
      name: 'Thomas B.', city: 'Lyon', initials: 'TB' },
    { tag: 'MEILLEUR MONTAGE TROUVÉ', stars: 5,
      quote: "Le simulateur m'a permis de comparer location nue vs meublé sur le même bien. La différence fiscale était de 3 400 € par an. J'ai choisi le LMNP et ça change tout sur la durée.",
      name: 'Sophie M.', city: 'Bordeaux', initials: 'SM' },
    { tag: 'DÉCISION RAPIDE', stars: 4,
      quote: "En visite, j'avais 48h pour me décider. J'ai lancé la simulation sur mobile pendant le trajet retour. Les chiffres étaient bons, j'ai fait une offre le soir même. Le bien est parti en 3 jours.",
      name: 'Romain C.', city: 'Toulouse', initials: 'RC' },
    { tag: 'PORTFOLIO DE 4 BIENS', stars: 5,
      quote: "J'utilise Moneyshape pour chaque acquisition depuis 2 ans. Aujourd'hui j'ai 4 biens en portefeuille. La cohérence des simulations m'a évité de surpayer et m'a aidé à structurer mes financements.",
      name: 'Alexandre P.', city: 'Paris', initials: 'AP' },
    { tag: '2 BIENS EN 14 MOIS', stars: 5,
      quote: "En 14 mois, j'ai acheté 2 biens locatifs. Le simulateur me permet de filtrer vite : si ça ne passe pas sur le papier, je ne perds pas de temps en visite.",
      name: 'Marc G.', city: 'Marseille', initials: 'MG' },
    { tag: '8 K€ DE TRAVAUX ANTICIPÉS', stars: 4,
      quote: "En intégrant les travaux dans la simulation, j'ai vu que la rentabilité restait positive même avec 8 K€ de rénovation. Ça m'a donné confiance pour négocier en incluant les travaux dans le prix.",
      name: 'Camille R.', city: 'Strasbourg', initials: 'CR' },
  ].map((it, i) => ({ ...it, pal: PALETTES[i % 4] }));

  const count = items.length;

  // Stars renderer
  const Stars = ({ n, mobile }) => (
    <div style={{ display: 'inline-flex', gap: 2 }}>
      {Array.from({ length: 5 }).map((_, i) => (
        <svg key={i} width={mobile ? 12 : 14} height={mobile ? 12 : 14} viewBox="0 0 16 16" fill={i < n ? '#F5B82E' : 'rgba(29,29,29,0.15)'}>
          <path d="M8 1.5l1.95 4.3 4.7.45-3.55 3.1 1.08 4.6L8 11.5l-4.18 2.45 1.08-4.6L1.35 6.25l4.7-.45L8 1.5z"/>
        </svg>
      ))}
    </div>
  );

  // Card
  const Card = ({ it, focused, dim }) => (
    <div style={{
      background: '#fff',
      borderRadius: 18,
      padding: mobile ? '22px 20px' : '28px 28px 24px',
      width: mobile ? 290 : 340,
      boxShadow: focused
        ? '0 24px 48px -12px rgba(29,29,29,0.18), 0 8px 18px -6px rgba(29,29,29,0.08)'
        : '0 8px 20px -10px rgba(29,29,29,0.08)',
      opacity: dim ? 0.5 : 1,
      transform: focused ? 'scale(1)' : 'scale(0.94)',
      transition: 'all .5s cubic-bezier(.2,.7,.2,1)',
      flexShrink: 0,
      display: 'flex', flexDirection: 'column',
      minHeight: mobile ? 280 : 320,
    }}>
      {/* Top row: badge + stars */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, gap: 12 }}>
        <span style={{
          background: it.pal.bg, color: it.pal.fg,
          fontFamily: FONTS.sans, fontSize: 10.5, fontWeight: 700,
          padding: '5px 11px', borderRadius: 99,
          textTransform: 'uppercase', letterSpacing: 0.8,
          whiteSpace: 'nowrap',
        }}>{it.tag}</span>
        <Stars n={it.stars} mobile={mobile}/>
      </div>
      {/* Quote */}
      <p style={{
        fontFamily: FONTS.sans,
        fontSize: mobile ? 13 : 13.5, lineHeight: 1.55,
        color: TOKENS.ink, margin: 0,
        flex: 1,
      }}>
        «&nbsp;{it.quote}&nbsp;»
      </p>
      {/* Author */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        marginTop: 24,
        paddingTop: 18,
        borderTop: `1px solid ${TOKENS.line}`,
      }}>
        <div style={{
          width: 34, height: 34, borderRadius: 99,
          background: it.pal.bg, color: it.pal.fg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: FONTS.sans, fontSize: 11, fontWeight: 700,
          flexShrink: 0,
        }}>{it.initials}</div>
        <div>
          <div style={{ fontFamily: FONTS.sans, fontSize: 14, fontWeight: 700, color: TOKENS.ink }}>
            {it.name}
          </div>
          <div style={{ fontFamily: FONTS.sans, fontSize: 12, color: TOKENS.ink60 }}>
            {it.city}
          </div>
        </div>
      </div>
    </div>
  );

  const go = (delta) => setActive((a) => (a + delta + count) % count);

  // ── Render ──────────────────────────────────────────────────────
  const cardW = mobile ? 290 : 340;
  const gap = mobile ? 16 : 24;
  const step = cardW + gap;

  // Touch swipe support (mobile)
  const touchStart = React.useRef(null);
  const onTouchStart = (e) => { touchStart.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchStart.current == null) return;
    const dx = e.changedTouches[0].clientX - touchStart.current;
    if (Math.abs(dx) > 40) go(dx < 0 ? 1 : -1);
    touchStart.current = null;
  };

  return (
    <section ref={ref} id="temoignages" style={{
      width: '100%',
      padding: mobile ? '70px 0 90px' : '110px 0 120px',
      scrollMarginTop: 80,
      background: TOKENS.paper,
      position: 'relative', overflow: 'hidden',
    }}>
      {/* Heading */}
      <div style={{ textAlign: 'center', marginBottom: mobile ? 36 : 56, padding: '0 20px', ...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 }}/>
          Témoignages
          <span style={{ width: 6, height: 6, borderRadius: 99, background: TOKENS.bordeaux }}/>
        </div>
        <h2 style={{
          fontFamily: FONTS.display, fontWeight: 700,
          fontSize: mobile ? 40 : 72, lineHeight: 1,
          letterSpacing: mobile ? -1.4 : -2.4,
          margin: '0 0 22px', color: TOKENS.ink,
          textWrap: 'balance',
        }}>
          Ils ont simulé avant d'acheter<span style={{ color: TOKENS.bordeaux }}>.</span>
        </h2>
        {/* Rating pill */}
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 10,
          background: '#fff',
          border: `1px solid ${TOKENS.line}`,
          borderRadius: 99,
          padding: '8px 18px',
          boxShadow: '0 6px 14px -6px rgba(29,29,29,0.08)',
        }}>
          <div style={{ display: 'inline-flex', gap: 2 }}>
            {Array.from({ length: 5 }).map((_, i) => (
              <svg key={i} width="14" height="14" viewBox="0 0 16 16" fill="#F5B82E">
                <path d="M8 1.5l1.95 4.3 4.7.45-3.55 3.1 1.08 4.6L8 11.5l-4.18 2.45 1.08-4.6L1.35 6.25l4.7-.45L8 1.5z"/>
              </svg>
            ))}
          </div>
          <span style={{ fontFamily: FONTS.sans, fontSize: 14, fontWeight: 700, color: TOKENS.ink }}>4.8/5</span>
        </div>
      </div>

      {/* Carousel track */}
      <div
        onTouchStart={mobile ? onTouchStart : undefined}
        onTouchEnd={mobile ? onTouchEnd : undefined}
        style={{
        position: 'relative',
        ...reveal(1),
      }}>
        <div style={{
          display: 'flex',
          gap: `${gap}px`,
          padding: `20px calc(50% - ${cardW / 2}px)`,
          transform: `translateX(${-active * step}px)`,
          transition: 'transform .7s cubic-bezier(.2,.7,.2,1)',
          willChange: 'transform',
        }}>
          {items.map((it, i) => (
            <Card key={i} it={it}
              focused={i === active}
              dim={i !== active}
            />
          ))}
        </div>
      </div>

      {/* Controls */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        gap: 14, marginTop: mobile ? 28 : 36,
        ...reveal(2),
      }}>
        <button onClick={() => go(-1)} aria-label="Précédent" style={{
          width: 38, height: 38, borderRadius: 99,
          background: '#fff', border: `1px solid ${TOKENS.line}`,
          cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 4px 10px -4px rgba(29,29,29,0.12)',
        }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
            <path d="M10 3L5 8L10 13" stroke={TOKENS.ink} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>

        {/* Dots */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {items.map((_, i) => (
            <button key={i} onClick={() => setActive(i)}
              aria-label={`Témoignage ${i + 1}`}
              style={{
                width: i === active ? 22 : 8,
                height: 4, borderRadius: 4,
                background: i === active ? TOKENS.ink : TOKENS.ink12,
                border: 'none', cursor: 'pointer', padding: 0,
                transition: 'all .3s',
              }}/>
          ))}
        </div>

        <button onClick={() => go(1)} aria-label="Suivant" style={{
          width: 38, height: 38, borderRadius: 99,
          background: '#fff', border: `1px solid ${TOKENS.line}`,
          cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 4px 10px -4px rgba(29,29,29,0.12)',
        }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
            <path d="M6 3L11 8L6 13" stroke={TOKENS.ink} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>
    </section>
  );
}

window.TestimonialsSection = TestimonialsSection;
