// ============================================================
// SECTION HAID — Manfaat
// • Sticky title on the left
// • Sachet (real photo, rotated 180°) scrolls fully right → left
//   and exits the screen — no stop, no tear, no liquid, no shadow
// • 6 benefits appear one by one on the right as sachet travels
// ============================================================

function SectionHaid() {
  const sectionRef = React.useRef(null);
  const [p, setP] = React.useState(0);
  const [isMobile, setIsMobile] = React.useState(false);

  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 700px)');
    const update = () => setIsMobile(mq.matches);
    update();
    if (mq.addEventListener) mq.addEventListener('change', update);
    else mq.addListener(update);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', update);
      else mq.removeListener(update);
    };
  }, []);

  React.useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      if (!sectionRef.current) return;
      const rect = sectionRef.current.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const scrolled = -rect.top;
      const np = Math.max(0, Math.min(1, scrolled / Math.max(1, total)));
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => setP(np));
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, []);

  // Sachet starts rotated -90° (horizontal) and 2.5× larger.
  // • Desktop: settles upright (0°) at normal size, centered.
  // • Mobile : settles HORIZONTAL (stays at -90°), slightly larger (1.2×),
  //   with a 25px-lower start that lifts 30px as it scrolls into final pose.
  const sachetP = Math.max(0, Math.min(1, p / 0.70));
  // ease-out cubic
  const ease = 1 - Math.pow(1 - sachetP, 3);
  const sachetEndRotate = isMobile ? -90 : 0;
  const sachetEndScale  = isMobile ? 1.2 : 1.0;
  const sachetRotate = -90 + ease * (sachetEndRotate - (-90));
  const sachetScale  = 2.5 + ease * (sachetEndScale - 2.5); // 2.5 → endScale
  // Mobile-only Y offset during scroll: starts +25px, ends -5px
  const startYOffset = isMobile ? 25 : 0;
  const endYOffset   = isMobile ? -5 : 0;
  const yOffset = startYOffset + ease * (endYOffset - startYOffset);

  // BG color: cream → deep crimson over the first half, then locks dark
  const bgT = Math.min(1, p / 0.50);
  const lerp = (a, b, t) => a + (b - a) * t;
  const rc = Math.round(lerp(248, 90, bgT));
  const gc = Math.round(lerp(241, 14, bgT));
  const bc = Math.round(lerp(231, 18, bgT));
  const bgColor = `rgb(${rc}, ${gc}, ${bc})`;
  const lightMode = bgT < 0.4;

  const BENEFITS = [
    'Membantu Melancarkan Haid',
    'Membantu Mengurangi Nyeri Haid',
    'Membantu Mengurangi Gangguan Haid',
    'Membantu Mengurangi Keputihan',
    'Membantu Memperbaiki Siklus Haid',
    'Membantu Mengurangi Bau Tidak Sedap Pada Area Kewanitaan',
  ];

  // Benefits appear progressively across the section so all 6 are visible
  // by the time the sachet has fully passed.
  const benefitP = Math.max(0, (p - 0.10) / 0.80);

  return (
    <section className="sh" id="manfaat" ref={sectionRef} style={{ background: bgColor }}>
      <div className="sh-sticky">
        {/* Soft red glow when bg goes dark */}
        <div className="sh-glow" style={{ opacity: bgT }} />

        {/* STICKY title — stays visible through entire section */}
        <div className={'sh-title-wrap' + (lightMode ? ' light' : ' dark')}>
          <div className="sh-eyebrow">
            <span className="sh-eyebrow-line" />
            Manfaat Yojea
          </div>
          <h2 className="sh-title">
            6 manfaat untuk<br/>
            <em>kesehatan haid</em><br/>
            wanita Indonesia.
          </h2>
          <p className="sh-title-sub">
            Diformulasikan khusus untuk kebutuhan kesehatan wanita —
            membantu siklus, mengurangi nyeri, dan menjaga area kewanitaan.
          </p>
        </div>

        {/* Sachet — starts at the right edge (60% visible, rotated -90°, 2.5×)
            and travels to the center while rotating upright and scaling down. */}
        <div
          className="sh-sachet"
          style={{
            transform: `translate(calc(${(1 - ease) * 50}vw + ${-60 + ease * 10}%), calc(-50% + ${yOffset}px)) rotate(${sachetRotate}deg) scale(${sachetScale})`,
          }}
        >
          <img
            src="assets/sachet-yojea.webp"
            alt="Yojea Sachet"
            className="sh-sachet-img"
          />
        </div>

        {/* Benefits stack — right side, appear staggered as sachet travels */}
        <div className="sh-benefits">
          {BENEFITS.map((text, i) => {
            const t = Math.max(0, Math.min(1, (benefitP - i * 0.12) * 5));
            return (
              <div
                key={i}
                className={'sh-benefit' + (t > 0.05 ? ' show' : '')}
                style={{
                  opacity: t,
                  transform: `translateX(${(1 - t) * 50}px)`,
                }}
              >
                <div className="sh-benefit-num">{String(i + 1).padStart(2, '0')}</div>
                <div className="sh-benefit-text">{text}</div>
                <div className="sh-benefit-tick">
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                    <path d="M2 6.5L5 9.5L10.5 3" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </div>
              </div>
            );
          })}
        </div>

        {/* Bottom progress hint */}
        <div className={'sh-hint' + (lightMode ? ' light' : ' dark')}>
          Scroll
          <span className="sh-hint-bar"><span className="sh-hint-fill" style={{ width: (p * 100) + '%' }}/></span>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SectionHaid });
