// Features section — "Toutes les réponses, en un seul outil."
// 3x2 grid of question cards + 1 bordeaux CTA card.

function FeaturesSection({ mobile = false }) {
  const [visible, setVisible] = React.useState(false);
  const [openIdx, setOpenIdx] = React.useState(-1); // mobile accordion — toutes fermées par défaut
  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(14px)',
    transition: `opacity .7s cubic-bezier(.2,.7,.2,1) ${i * 80}ms, transform .7s cubic-bezier(.2,.7,.2,1) ${i * 80}ms`,
  });

  // Icons
  const IconTrend = (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
      <path d="M2.5 11.5L6 7.5L8.5 10L13.5 4" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M10 4h3.5v3.5" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
  const IconEuro = (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
      <path d="M11 4.5a3.5 3.5 0 0 0-6.3 2.1M11 11.5a3.5 3.5 0 0 1-6.3-2.1" stroke="#1D1D1D" strokeWidth="1.8" strokeLinecap="round"/>
      <path d="M3 7h6M3 9h6" stroke="#1D1D1D" strokeWidth="1.6" strokeLinecap="round"/>
    </svg>
  );
  const IconBank = (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
      <path d="M8 2L14 5H2L8 2Z" fill="#fff"/>
      <rect x="3" y="6" width="1.6" height="6" fill="#fff"/>
      <rect x="7.2" y="6" width="1.6" height="6" fill="#fff"/>
      <rect x="11.4" y="6" width="1.6" height="6" fill="#fff"/>
      <rect x="2" y="12.5" width="12" height="1.5" fill="#fff"/>
    </svg>
  );
  const IconStar = (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
      <path d="M8 1.5l2.06 4.2 4.64.67-3.36 3.28.8 4.62L8 11.98 3.86 14.27l.8-4.62-3.36-3.28 4.64-.67L8 1.5z" fill="#fff"/>
    </svg>
  );
  const IconDoc = (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
      <path d="M4 2h5l3 3v9H4V2z" stroke="#fff" strokeWidth="1.6" strokeLinejoin="round" fill="none"/>
      <path d="M9 2v3h3" stroke="#fff" strokeWidth="1.6" strokeLinejoin="round"/>
      <path d="M6 8h4M6 10.5h4" stroke="#fff" strokeWidth="1.4" strokeLinecap="round"/>
    </svg>
  );

  const questions = [
    {
      q: 'Mon projet est-il vraiment rentable ?',
      a: <>Simulez <u>votre rentabilité réelle</u> et identifiez vos leviers d'optimisation. Projection à 5, 10, 15 ans.</>,
      icon: IconTrend, iconBg: TOKENS.blue,
    },
    {
      q: 'Ce bien sera-t-il cashflow positif ?',
      a: <>Projetez vos flux mensuels et testez plusieurs stratégies de financement pour <u>optimiser votre cashflow</u>.</>,
      icon: IconEuro, iconBg: TOKENS.green,
    },
    {
      q: 'La banque va-t-elle me suivre ?',
      a: <>Calculez votre <u>capacité d'emprunt réelle</u> et testez l'impact de l'apport et du taux.</>,
      icon: IconBank, iconBg: TOKENS.bordeaux,
    },
    {
      q: 'Comment savoir si je prends la bonne décision ?',
      a: <><u>Comparez vos scénarios</u> côte à côte, détectez les red flags et validez avec nos Moneyshapers si besoin.</>,
      icon: IconStar, iconBg: TOKENS.coral,
    },
    {
      q: 'Comment penser à tout avant d\'acheter ?',
      a: <>Une <u>roadmap complète</u> vous guide jusqu'à l'achat final. Rien n'est laissé au hasard.</>,
      icon: IconDoc, iconBg: TOKENS.ink,
    },
  ];

  const Card = ({ q, a, icon, iconBg, i }) => (
    <div style={{
      background: '#fff',
      border: `1px solid ${TOKENS.line}`,
      borderRadius: mobile ? 16 : 18,
      padding: mobile ? 22 : 28,
      minHeight: mobile ? 'auto' : 220,
      display: 'flex', flexDirection: 'column',
      transition: 'transform .3s cubic-bezier(.2,.7,.2,1), box-shadow .3s',
      cursor: 'default',
      ...reveal(i + 1),
    }}
    onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-3px)'; e.currentTarget.style.boxShadow = '0 18px 40px -14px rgba(29,29,29,0.12)'; }}
    onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'none'; }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 14, marginBottom: 18 }}>
        <div style={{
          fontFamily: FONTS.display, fontWeight: 700,
          fontSize: mobile ? 17 : 18, lineHeight: 1.3, letterSpacing: -0.3,
          color: TOKENS.ink, flex: 1,
        }}>
          {q}
        </div>
        <div style={{
          width: 36, height: 36, borderRadius: 99, background: iconBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          {icon}
        </div>
      </div>
      <div style={{
        fontFamily: FONTS.sans, fontSize: mobile ? 13 : 14, lineHeight: 1.55,
        color: TOKENS.ink60,
      }}>
        {a}
      </div>
    </div>
  );

  // CTA card — fond paper comme les autres, CTA bordeaux
  const CTACard = (
    <div style={{
      background: TOKENS.paper,
      border: `1px solid ${TOKENS.line}`,
      borderRadius: mobile ? 16 : 18,
      padding: mobile ? 22 : 28,
      color: TOKENS.ink, position: 'relative', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
      minHeight: mobile ? 'auto' : 220,
      ...reveal(6),
    }}>
      {/* avatars en haut à droite — signal "experts" */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
        gap: 14, marginBottom: 18,
      }}>
        <div style={{
          fontFamily: FONTS.display, fontWeight: 700,
          fontSize: mobile ? 17 : 18, lineHeight: 1.3, letterSpacing: -0.3,
          color: TOKENS.ink, flex: 1,
        }}>
          Nos Moneyshapers répondent à vos questions.
        </div>
        <div style={{ display: 'flex', flexShrink: 0 }}>
          {[
            { src: 'assets/expert-homme.jpg', pos: '50% 28%' },
            { src: 'assets/expert-femme.jpg', pos: '50% 28%' },
          ].map((a, i) => (
            <div key={i} style={{
              position: 'relative',
              width: 36, height: 36, borderRadius: 99,
              overflow: 'hidden',
              border: `2px solid ${TOKENS.paper}`,
              boxShadow: '0 2px 6px rgba(0,0,0,0.12)',
              marginLeft: i ? -10 : 0,
              flexShrink: 0,
              background: TOKENS.bordeaux,
            }}>
              <div style={{
                position: 'absolute', inset: 0,
                backgroundImage: `url(${a.src})`,
                backgroundSize: 'cover',
                backgroundPosition: a.pos,
              }}/>
            </div>
          ))}
        </div>
      </div>
      <div style={{
        fontFamily: FONTS.sans, fontSize: mobile ? 13 : 14, lineHeight: 1.55,
        color: TOKENS.ink60, marginBottom: 18,
      }}>
        Des experts immobilier, fiscalité et financement, disponibles à la demande.
      </div>
      <button
        data-cal-link="team/moneyshape/demo-moneyshape"
        data-cal-namespace="demo-moneyshape"
        data-cal-config='{"layout":"month_view","useSlotsViewOnSmallScreen":"true","metadata[cta_source]":"features"}'
        style={{
          background: TOKENS.bordeaux, color: '#fff', border: 'none',
          padding: '14px 22px', borderRadius: 12, fontSize: 15, fontWeight: 600,
          fontFamily: FONTS.sans, cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          marginTop: 'auto', alignSelf: 'flex-start',
          boxShadow: '0 10px 30px -5px rgba(92,13,7,0.4)',
        }}>
        Parler à un expert
        <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 (
    <section ref={ref} id="fonctionnalites" style={{
      width: '100%',
      padding: mobile ? '60px 20px 60px' : '100px 56px 100px',
      scrollMarginTop: 80,
      background: TOKENS.paper,
      position: 'relative',
    }}>
      {/* heading */}
      <div style={{ textAlign: 'center', marginBottom: mobile ? 40 : 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 }}/>
          Fonctionnalités
          <span style={{ width: 6, height: 6, borderRadius: 99, background: TOKENS.bordeaux }}/>
        </div>
        <h2 style={{
          fontFamily: FONTS.display, fontWeight: 700,
          fontSize: mobile ? 36 : 64, lineHeight: 1.04, letterSpacing: mobile ? -1.2 : -2.2,
          margin: 0, color: TOKENS.ink,
        }}>
          Toutes les réponses,<br/>
          en un seul outil<span style={{ color: TOKENS.bordeaux }}>.</span>
        </h2>
      </div>

      {/* grid (desktop) / accordion (mobile) */}
      {mobile ? (
        <div style={{
          maxWidth: 1100, margin: '0 auto',
          display: 'flex', flexDirection: 'column',
          gap: 8,
        }}>
          {questions.map((item, i) => {
            const isOpen = openIdx === i;
            return (
              <div key={i} style={{
                background: '#fff',
                border: `1px solid ${TOKENS.line}`,
                borderRadius: 14,
                overflow: 'hidden',
                ...reveal(i + 1),
              }}>
                {/* row header — always visible, tappable */}
                <button
                  onClick={() => setOpenIdx(isOpen ? -1 : i)}
                  style={{
                    width: '100%',
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '12px 14px',
                    background: 'transparent',
                    border: 'none',
                    cursor: 'pointer',
                    textAlign: 'left',
                    fontFamily: 'inherit',
                  }}
                >
                  <div style={{
                    width: 28, height: 28, borderRadius: 99, background: item.iconBg,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                  }}>
                    {/* smaller icon for accordion header */}
                    <div style={{ transform: 'scale(0.82)', display: 'flex' }}>{item.icon}</div>
                  </div>
                  <div style={{
                    fontFamily: FONTS.display, fontWeight: 700,
                    fontSize: 14.5, lineHeight: 1.3, letterSpacing: -0.2,
                    color: TOKENS.ink, flex: 1,
                  }}>
                    {item.q}
                  </div>
                  {/* Chevron — même style que product-section (cercle ink06) */}
                  <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={{
                  maxHeight: isOpen ? 200 : 0,
                  opacity: isOpen ? 1 : 0,
                  overflow: 'hidden',
                  transition: 'max-height .35s cubic-bezier(.2,.7,.2,1), opacity .3s ease',
                }}>
                  <div style={{
                    padding: '0 14px 14px 52px', // aligné sous le texte (28px icon + 10px gap + 14px = 52)
                    fontFamily: FONTS.sans, fontSize: 13, lineHeight: 1.55,
                    color: TOKENS.ink60,
                  }}>
                    {item.a}
                  </div>
                </div>
              </div>
            );
          })}
          {CTACard}
        </div>
      ) : (
        <div style={{
          maxWidth: 1100, margin: '0 auto',
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 14,
        }}>
          {questions.slice(0, 3).map((item, i) => (
            <Card key={i} {...item} i={i}/>
          ))}
          {questions.slice(3).map((item, i) => (
            <Card key={i + 3} {...item} i={i + 3}/>
          ))}
          {CTACard}
        </div>
      )}
    </section>
  );
}

window.FeaturesSection = FeaturesSection;
