// ============================================================
// SECTION 2 — React wrapper for the 3D scroll parallax
// Center-top title that animates between "The Product" and
// "The Ingredients" as scroll passes the threshold.
// ============================================================

// ============================================================
// DissolveText — letter-by-letter burst/dissolve transition.
// On text change: each letter of the old text staggers out
// (translate + scale + blur + fade), then new letters stagger
// in from below with the same dissolve curve.
// ============================================================
function DissolveText({ text, duration = 700 }) {
  const [current, setCurrent] = React.useState(text);
  const [outgoing, setOutgoing] = React.useState(null);

  React.useEffect(() => {
    if (current === text) return;
    setOutgoing(current);
    setCurrent(text);
    const t = setTimeout(() => setOutgoing(null), duration);
    return () => clearTimeout(t);
  }, [text]);

  const renderLetters = (str, cls) => str.split('').map((ch, i) => (
    <span
      key={i}
      className={'s2-dl ' + cls}
      style={{ '--idx': i, '--n': str.length }}
    >
      {ch === ' ' ? '\u00A0' : ch}
    </span>
  ));

  return (
    <span className="s2-dissolve">
      {outgoing && (
        <span className="s2-dissolve-layer s2-dissolve-out" key={'o-' + outgoing}>
          {renderLetters(outgoing, 's2-dl-out')}
        </span>
      )}
      <span className="s2-dissolve-layer s2-dissolve-in" key={'i-' + current}>
        {renderLetters(current, 's2-dl-in')}
      </span>
    </span>
  );
}

function Section2() {
  const sectionRef = React.useRef(null);
  const canvasRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0);
  const [ready, setReady] = React.useState(false);
  const [noWebGL, setNoWebGL] = React.useState(false);

  React.useEffect(() => {
    const onNoWebGL = () => setNoWebGL(true);
    window.addEventListener('yojea3d:nowebgl', onNoWebGL);
    return () => window.removeEventListener('yojea3d:nowebgl', onNoWebGL);
  }, []);

  React.useEffect(() => {
    let raf = 0;
    let mounted = true;
    let started = false;

    const tryInit = async () => {
      if (!window.__yojea3D || !canvasRef.current) {
        setTimeout(tryInit, 80);
        return;
      }
      await window.__yojea3D.init(canvasRef.current);
      if (mounted) setReady(true);
    };

    // ⚡ Defer the ~5 MB GLB download + WebGL init until Section 2 is near
    // the viewport — the hero/top of page loads fast and the 3D only
    // fetches when the user actually scrolls toward it.
    const startInit = () => { if (!started) { started = true; tryInit(); } };
    let initObserver = null;
    if ('IntersectionObserver' in window && sectionRef.current) {
      initObserver = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting) { startInit(); initObserver.disconnect(); }
      }, { rootMargin: '800px 0px' });
      initObserver.observe(sectionRef.current);
    } else {
      startInit();
    }

    function onScroll() {
      if (!sectionRef.current) return;
      const rect = sectionRef.current.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const scrolled = -rect.top;
      const p = Math.max(0, Math.min(1, scrolled / Math.max(1, total)));
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        setProgress(p);
        if (window.__yojea3D) window.__yojea3D.setProgress(p);
      });
    }
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();

    return () => {
      mounted = false;
      if (initObserver) initObserver.disconnect();
      window.removeEventListener('scroll', onScroll);
      cancelAnimationFrame(raf);
      if (window.__yojea3D) window.__yojea3D.dispose();
    };
  }, []);

  // 6 ingredients in a hexagon-ish layout around center sachet
  const INGREDIENTS = [
    {
      key: 'bunga-sidowayah', name: 'Bunga Sidowayah', img: 'assets/bunga-sidowayah.webp',
      side: 'l', y: 0.10, threshold: 0.82,
      latin: 'Woodfordia floribunda',
      desc: 'Mengandung asam elagat, asam galat, flavonoid, dan tanin yang membantu mengurangi nyeri haid, serta meringankan keputihan dan pendarahan berlebih.',
      tags: ['Nyeri Haid', 'Keputihan', 'Flavonoid'],
    },
    {
      key: 'kulit-delima', name: 'Kulit Delima', img: 'assets/kulit-delima.webp',
      side: 'l', y: 0.42, threshold: 0.86,
      latin: 'Punica granatum',
      desc: 'Kaya saponin, flavonoid, dan alkaloid yang menghambat keputihan akibat jamur, mengurangi risiko kanker rahim, serta mencegah peradangan dan kerusakan sel.',
      tags: ['Saponin', 'Keputihan', 'Anti-inflamasi'],
    },
    {
      key: 'kayu-rapat', name: 'Kayu Rapat', img: 'assets/kayu-rapat.webp',
      side: 'l', y: 0.72, threshold: 0.90,
      latin: 'Parameria laevigata',
      desc: 'Mengandung flavonoid dan polifenol yang membantu mengencangkan otot kewanitaan, mencegah infeksi, melancarkan haid, dan meredakan sakit pasca melahirkan.',
      tags: ['Kewanitaan', 'Pasca Lahiran', 'Polifenol'],
    },
    {
      key: 'daun-tapak-liman', name: 'Daun Tapak Liman', img: 'assets/daun-tapak-liman.webp',
      side: 'r', y: 0.10, threshold: 0.84,
      latin: 'Elephantopus scaber',
      desc: 'Mengandung senyawa fenolik sebagai antioksidan, antiinflamasi, dan antimikroba, membantu meredakan nyeri haid, membersihkan darah, serta menghambat sel kanker.',
      tags: ['Antioksidan', 'Anti-inflamasi', 'Antimikroba'],
    },
    {
      key: 'pulosari', name: 'Pulosari', img: 'assets/pulosari.webp',
      side: 'r', y: 0.42, threshold: 0.88,
      latin: 'Alyxia reinwardtii',
      desc: 'Mengandung flavonoid, saponin, dan polifenol yang meningkatkan daya tahan tubuh, memperlancar haid, mengurangi keputihan, dan bersifat antioksidan.',
      tags: ['Imunitas', 'Haid', 'Antioksidan'],
    },
    {
      key: 'madu', name: 'Madu Murni', img: 'assets/madu.webp',
      side: 'r', y: 0.72, threshold: 0.92,
      latin: 'Mel purum',
      desc: 'Bersifat antibakteri, antioksidan, dan antiinflamasi. Membantu meredakan nyeri haid.',
      tags: ['Antibakteri', 'Antioksidan', 'Pelembap'],
    },
  ];

  const [selected, setSelected] = React.useState(null);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') setSelected(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // Title timing — "The Product" appears EARLY and stays locked through
  // the entire rotation + windup. Switches to "The Ingredients" as dissolve begins.
  //   p ≤ 0.04         → no title
  //   0.04 – 0.50       → "The Product" (locked, no movement)
  //   p ≥ 0.50         → "The Ingredients"
  const titleTarget = progress <= 0.04 ? '' : progress < 0.50 ? 'The Product' : 'The Ingredients';

  // No parallax during box phase — title stays still.
  const titleParallax = progress < 0.50 ? 0 : (progress - 0.5) * -14;

  return (
    <section className="s2" id="ingredients" ref={sectionRef}>
      <div className="s2-sticky">
        {/* Decorative background */}
        <div className="s2-bg">
          <div className="s2-bg-blob s2-bg-blob-1" />
          <div className="s2-bg-blob s2-bg-blob-2" />
          <svg className="s2-bg-lines" viewBox="0 0 1440 900" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
            <defs>
              <radialGradient id="s2glow" cx="50%" cy="50%" r="50%">
                <stop offset="0%" stopColor="#E85D1A" stopOpacity="0.18"/>
                <stop offset="60%" stopColor="#E85D1A" stopOpacity="0.04"/>
                <stop offset="100%" stopColor="#E85D1A" stopOpacity="0"/>
              </radialGradient>
            </defs>
            <circle cx="720" cy="450" r="340" fill="url(#s2glow)"/>
            <circle cx="720" cy="450" r="260" fill="none" stroke="#1F1612" strokeOpacity="0.06" strokeDasharray="2 6"/>
            <circle cx="720" cy="450" r="380" fill="none" stroke="#1F1612" strokeOpacity="0.05"/>
            <circle cx="720" cy="450" r="500" fill="none" stroke="#1F1612" strokeOpacity="0.04" strokeDasharray="2 8"/>
          </svg>
        </div>

        {/* CENTER-TOP TITLE — dissolve transition + slight scroll parallax */}
        <div
          className="s2-center-title"
          style={{ transform: `translate(-50%, ${titleParallax}px)` }}
        >
          <h2 className="s2-center-title-text">
            <DissolveText text={titleTarget} />
          </h2>
        </div>

        {/* 3D canvas */}
        <div className="s2-canvas" ref={canvasRef}>
          {!ready && !noWebGL && (
            <div className="s2-loading">
              <div className="s2-spinner" />
              <span>Memuat 3D Yojea…</span>
            </div>
          )}
          {noWebGL && (
            <div className="s2-fallback">
              <div className="s2-fallback-box">
                <div className="s2-fallback-eyebrow">3D Preview</div>
                <div className="s2-fallback-title">Buka di browser dengan WebGL</div>
                <div className="s2-fallback-sub">Animasi 3D box → ingredients akan muncul di sini.</div>
              </div>
            </div>
          )}
        </div>

        {/* Ingredient cards around the sachet — clickable */}
        <div className="s2-ingredients">
          {INGREDIENTS.map((ing, i) => {
            const visible = progress >= ing.threshold;
            const showHint = ing.key === 'kayu-rapat';
            return (
              <button
                key={ing.key}
                type="button"
                className={'s2-ing s2-ing-' + ing.side + (visible ? ' show' : '')}
                style={{ top: (ing.y * 100) + '%', '--delay': i * 0.05 + 's' }}
                onClick={() => setSelected(ing)}
                aria-label={'Detail ' + ing.name}
              >
                <div className="s2-ing-photo">
                  <img src={ing.img} alt={ing.name} />
                  {showHint && (
                    <span className="click-hint click-hint-s2-ing" aria-hidden="true">
                      <svg className="click-hint-cursor" viewBox="0 0 24 24" fill="none">
                        <path d="M11.5 2.25 a1.5 1.5 0 0 1 1.5 1.5 V11 a1 1 0 0 1 1 -1 1.5 1.5 0 0 1 1.5 1.5 V12 a1 1 0 0 1 1 -1 1.5 1.5 0 0 1 1.5 1.5 V13 a1 1 0 0 1 1 -1 1.5 1.5 0 0 1 1.5 1.5 V17.5 a4.5 4.5 0 0 1 -4.5 4.5 H12 a4 4 0 0 1 -2.83 -1.17 L4.7 16.36 a1.6 1.6 0 0 1 2.26 -2.26 L9.5 16.64 V3.75 A1.5 1.5 0 0 1 11.5 2.25 Z"
                              fill="#fff" stroke="#1F1612" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round"/>
                      </svg>
                      <span className="click-hint-ring" />
                      <span className="click-hint-ring click-hint-ring-2" />
                    </span>
                  )}
                </div>
                <div className="s2-ing-text">
                  <div className="s2-ing-num">{String(i + 1).padStart(2, '0')}</div>
                  <div className="s2-ing-name">{ing.name}</div>
                  <div className="s2-ing-hint">
                    <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M2 5h6m0 0L5 2m3 3L5 8" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    Lihat manfaat
                  </div>
                </div>
                <div className={'s2-ing-line s2-ing-line-' + ing.side} />
              </button>
            );
          })}
        </div>

        {/* Ingredient detail popup */}
        {selected && (
          <div className="s2-pop" onClick={() => setSelected(null)}>
            <div className="s2-pop-card" onClick={e => e.stopPropagation()}>
              <button className="s2-pop-close" onClick={() => setSelected(null)} aria-label="Tutup">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
              </button>
              <div className="s2-pop-photo">
                <img src={selected.img} alt={selected.name} />
              </div>
              <div className="s2-pop-body">
                <div className="s2-pop-eyebrow">
                  <span className="s2-pop-eyebrow-line" />
                  Bahan Alami Yojea
                </div>
                <h3 className="s2-pop-name">{selected.name}</h3>
                <div className="s2-pop-latin">{selected.latin}</div>
                <p className="s2-pop-desc">{selected.desc}</p>
                <div className="s2-pop-tags">
                  {selected.tags.map(t => <span key={t} className="s2-pop-tag">{t}</span>)}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Progress bar at bottom */}
        <div className="s2-progress">
          <div className="s2-progress-hint">Klik komposisi untuk melihat detail</div>
          <div className="s2-progress-track">
            <div className="s2-progress-fill" style={{ width: (progress * 100) + '%' }} />
          </div>
          <div className="s2-progress-label">Scroll untuk eksplor</div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Section2 });
