// ============================================================
// SECTION LAB — White rounded card slides in from below.
// 3 compound boxes (flavonoid, polifenol, alkaloid).
// Below: Download lab-result button + parallax field of
// sachet + test-tube illustrations (uniform speed, random heights).
// ============================================================

function CompoundIcon({ name }) {
  // Stylized molecular icons per compound.
  if (name === 'flavonoid') {
    return (
      <svg viewBox="0 0 80 80" fill="none">
        <g stroke="#E85D1A" strokeWidth="1.4">
          <circle cx="40" cy="22" r="6" fill="#E85D1A"/>
          <circle cx="22" cy="44" r="6"/>
          <circle cx="58" cy="44" r="6"/>
          <circle cx="40" cy="62" r="6" fill="#1F1612" stroke="#1F1612"/>
          <path d="M40 28v8M22 50l13 10M58 50l-13 10M28 44h26"/>
        </g>
      </svg>
    );
  }
  if (name === 'polifenol') {
    return (
      <svg viewBox="0 0 80 80" fill="none">
        <g stroke="#E85D1A" strokeWidth="1.4">
          <polygon points="40,16 56,26 56,46 40,56 24,46 24,26" fill="rgba(232,93,26,0.15)"/>
          <circle cx="40" cy="16" r="4" fill="#E85D1A"/>
          <circle cx="56" cy="26" r="4" fill="#1F1612" stroke="#1F1612"/>
          <circle cx="56" cy="46" r="4" fill="#E85D1A"/>
          <circle cx="40" cy="56" r="4" fill="#1F1612" stroke="#1F1612"/>
          <circle cx="24" cy="46" r="4" fill="#E85D1A"/>
          <circle cx="24" cy="26" r="4" fill="#1F1612" stroke="#1F1612"/>
        </g>
      </svg>
    );
  }
  // alkaloid
  return (
    <svg viewBox="0 0 80 80" fill="none">
      <g stroke="#E85D1A" strokeWidth="1.4">
        <polygon points="40,18 56,30 50,50 30,50 24,30" fill="rgba(232,93,26,0.15)"/>
        <circle cx="40" cy="18" r="5" fill="#1F1612" stroke="#1F1612"/>
        <circle cx="56" cy="30" r="5" fill="#E85D1A"/>
        <circle cx="50" cy="50" r="5" fill="#E85D1A"/>
        <circle cx="30" cy="50" r="5" fill="#1F1612" stroke="#1F1612"/>
        <circle cx="24" cy="30" r="5" fill="#E85D1A"/>
        <circle cx="40" cy="62" r="4" fill="#E85D1A"/>
        <path d="M40 55v3"/>
      </g>
    </svg>
  );
}

// SVG sachet icon — small version for parallax field
function MiniSachet({ color = '#E85D1A' }) {
  return (
    <svg viewBox="0 0 80 130" fill="none">
      <rect x="6" y="4" width="68" height="8" rx="1.5" fill={color}/>
      <rect x="6" y="11" width="68" height="110" rx="2" fill="#F8F1E7" stroke={color} strokeWidth="0.8"/>
      <rect x="6" y="35" width="68" height="22" fill={color}/>
      <text x="40" y="51" textAnchor="middle" fontFamily="Instrument Serif" fontStyle="italic" fontSize="14" fill="#fff">Yojea</text>
      <circle cx="40" cy="82" r="14" fill="none" stroke={color} strokeWidth="0.8" strokeDasharray="1.5 2.5"/>
      <circle cx="40" cy="82" r="6" fill={color} opacity="0.5"/>
      <rect x="6" y="118" width="68" height="6" rx="1.5" fill={color} opacity="0.7"/>
    </svg>
  );
}

// Test tube icon
function TestTube({ fill = '#E85D1A' }) {
  return (
    <svg viewBox="0 0 60 140" fill="none">
      <path
        d="M22 6 h16 v2 h-2 v90 a10 10 0 0 1 -12 0 v-90 h-2 z"
        fill="rgba(255,255,255,0.95)"
        stroke="#1F1612"
        strokeWidth="0.8"
      />
      {/* Liquid */}
      <path
        d="M24 60 v32 a8 8 0 0 0 12 0 v-32 z"
        fill={fill}
        opacity="0.85"
      />
      {/* Bubbles */}
      <circle cx="28" cy="78" r="1.2" fill="#fff" opacity="0.6"/>
      <circle cx="32" cy="86" r="0.8" fill="#fff" opacity="0.5"/>
      {/* Top rim highlight */}
      <rect x="20" y="6" width="20" height="2" fill="#fff" opacity="0.5"/>
    </svg>
  );
}

// ============================================================
// LabImageStack — stack of 5 lab certificate pages that slide in
// from the right (one-by-one with stagger when the section enters
// the viewport), then auto-rotate which one is "on top". Clicking
// the stack opens the full PDF in a new tab.
// ============================================================
function LabImageStack() {
  const wrapRef = React.useRef(null);
  const [entered, setEntered] = React.useState(false);
  const [top, setTop] = React.useState(0);
  const IMAGES = [
    'assets/lab-1.webp',
    'assets/lab-2.webp',
    'assets/lab-3.webp',
    'assets/lab-4.webp',
    'assets/lab-5.webp',
  ];

  // Trigger slide-in when section enters viewport
  React.useEffect(() => {
    if (!wrapRef.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setEntered(true); });
    }, { threshold: 0.18 });
    io.observe(wrapRef.current);
    return () => io.disconnect();
  }, []);

  // Auto-rotate which page is on top
  React.useEffect(() => {
    if (!entered) return;
    const id = setInterval(() => setTop(t => (t + 1) % IMAGES.length), 3200);
    return () => clearInterval(id);
  }, [entered]);

  // Manual cycle on click — opens the full PDF on the topmost click
  const handleClick = () => {
    window.open(
      'https://drive.google.com/file/d/1yXF9ZxzD2h1y6FrcyWortXIfaAwFodcN/view',
      '_blank',
      'noopener,noreferrer'
    );
  };

  return (
    <div
      ref={wrapRef}
      className={'sl-lab-stack' + (entered ? ' entered' : '')}
      onClick={handleClick}
      role="button"
      tabIndex={0}
      aria-label="Buka hasil uji laboratorium (PDF)"
    >
      <div className="sl-lab-stack-glow" />
      {IMAGES.map((src, i) => {
        // Distance from "top" position (0 = on top, larger = further back)
        const dist = (i - top + IMAGES.length) % IMAGES.length;
        const offsetX = dist * 14; // px shift to the right
        const offsetY = dist * -10; // px shift up
        const rot = (i % 2 === 0 ? -1 : 1) * (2 + dist * 1.2);
        const scale = 1 - dist * 0.04;
        const opacity = dist === 0 ? 1 : Math.max(0.35, 1 - dist * 0.18);
        const zIndex = IMAGES.length - dist;
        // Entrance: start far to the right, slide into stacked pose with stagger
        const enterX = entered ? offsetX : 480 + i * 60;
        const enterRot = entered ? rot : rot + 18;
        const enterOpacity = entered ? opacity : 0;
        return (
          <div
            key={src}
            className="sl-lab-page"
            style={{
              transform: `translate(${enterX}px, ${offsetY}px) rotate(${enterRot}deg) scale(${scale})`,
              opacity: enterOpacity,
              zIndex,
              transitionDelay: entered ? (i * 90) + 'ms' : '0ms',
            }}
          >
            <img src={src} alt={'Hasil uji lab halaman ' + (i + 1)} />
            <span className="sl-lab-page-stamp">Page {i + 1}/5</span>
          </div>
        );
      })}
      <div className="sl-lab-stack-hint">
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
          <path d="M2 6h8m0 0L6.5 2.5M10 6L6.5 9.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
        Buka PDF lengkap
      </div>
    </div>
  );
}

function SectionLab() {
  const sectionRef = React.useRef(null);
  const [scrollY, setScrollY] = React.useState(0);
  const [intro, setIntro] = React.useState(0);

  React.useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      if (!sectionRef.current) return;
      const rect = sectionRef.current.getBoundingClientRect();
      // Slide-in intro: 0 when top below viewport, 1 when top reaches 50% viewport.
      const introT = Math.max(0, Math.min(1, 1 - rect.top / (window.innerHeight * 0.6)));
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        setIntro(introT);
        setScrollY(window.scrollY);
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, []);

  const COMPOUNDS = [
    {
      key: 'flavonoid',
      name: 'Flavonoid',
      tag: 'Senyawa Aktif 01',
      text: 'Senyawa yang memiliki sifat antioksidan dan antiinflamasi.',
    },
    {
      key: 'polifenol',
      name: 'Polifenol',
      tag: 'Senyawa Aktif 02',
      text: 'Senyawa dengan aktivitas antibakteri dan antijamur.',
    },
    {
      key: 'alkaloid',
      name: 'Alkaloid',
      tag: 'Senyawa Aktif 03',
      text: 'Senyawa yang dikenal memiliki sifat analgesik dan antispasmodik alami.',
    },
  ];

  // Parallax field: 12 items distributed across the width at random heights.
  // Uniform vertical speed driven by scrollY, random base offset.
  const FIELD = React.useMemo(() => {
    const items = [];
    const n = 14;
    for (let i = 0; i < n; i++) {
      const isTube = i % 3 === 0;
      items.push({
        kind: isTube ? 'tube' : 'sachet',
        leftPct: (i + 0.5) * (100 / n) + (Math.random() * 4 - 2),
        baseY: Math.random() * 80 - 40,          // random base vertical offset (px)
        scale: isTube ? 0.85 + Math.random() * 0.3 : 0.7 + Math.random() * 0.5,
        rot: (Math.random() * 16 - 8),
        speed: 0.30 + Math.random() * 0.08,      // ~uniform with tiny variation so it doesn't look canned
        color: ['#E85D1A', '#C84A14', '#1F1612', '#6A7A5C'][i % 4],
      });
    }
    return items;
  }, []);

  const slideUp = (1 - intro) * 120; // px slide-in

  return (
    <section className="sl" ref={sectionRef} id="lab">
      {/* Rising white bubbles — fizz that seamlessly bubbles upward as you
          scroll into the lab section. Sits behind the card; clipped by .sl
          overflow so they appear contained within the section bounds. */}
      <div className="sl-bubbles" aria-hidden="true">
        {Array.from({ length: 6 }).map((_, i) => {
          const size = 8 + ((i * 37) % 56);
          const left = ((i * 53) % 100);
          const delay = -((i * 1.7) % 14);
          const dur = 11 + ((i * 13) % 11);
          const drift = (i % 2 ? 1 : -1) * (8 + (i * 7) % 22);
          const opacity = 0.5 + ((i * 11) % 40) / 100;
          return (
            <span
              key={i}
              className="sl-bubble"
              style={{
                left: left + '%',
                width: size + 'px',
                height: size + 'px',
                animationDelay: delay + 's',
                animationDuration: dur + 's',
                opacity,
                '--drift': drift + 'px',
              }}
            />
          );
        })}
      </div>

      <div
        className="sl-card"
        style={{
          transform: `translateY(${slideUp}px)`,
          opacity: 0.3 + intro * 0.7,
        }}
      >
        <div className="sl-card-tag">
          <span className="sl-card-tag-dot" />
          Lab Tested · 2025
        </div>

        <div className="sl-header">
          <div className="sl-header-text">
            <h2 className="sl-title">
              Kandungan zat aktif<br/>
              dalam Yojea<br/>
              <em>sudah teruji lab!</em>
            </h2>

            <p className="sl-lead">
              Berdasarkan hasil uji laboratorium, Yojea mengandung senyawa aktif berupa
              <strong> flavonoid</strong>, <strong>alkaloid</strong>, dan <strong>polifenol</strong>.
              Senyawa-senyawa ini secara umum dikenal terdapat pada bahan alami dan sering
              dikaitkan dengan pemeliharaan kesehatan, termasuk dalam membantu mengurangi
              ketidaknyamanan yang berkaitan dengan menstruasi.
            </p>
          </div>

          {/* Lab result image carousel — slides in from the right.
              5 certificate pages auto-rotate; clicking opens the full PDF.
              Replaces the prior 3D test tube. */}
          <LabImageStack />
        </div>

        <div className="sl-compounds">
          {COMPOUNDS.map((c, i) => (
            <article key={c.key} className="sl-compound">
              <div className="sl-compound-icon">
                <CompoundIcon name={c.key} />
              </div>
              <div className="sl-compound-tag">{c.tag}</div>
              <h3 className="sl-compound-name">{c.name}</h3>
              <p className="sl-compound-text">{c.text}</p>
            </article>
          ))}
        </div>

        {/* Download button */}
        <div className="sl-download-wrap">
          <a className="sl-download" href="https://drive.google.com/file/d/1yXF9ZxzD2h1y6FrcyWortXIfaAwFodcN/view" target="_blank" rel="noopener noreferrer">
            <span className="sl-download-icon">
              <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                <path d="M9 2v10m0 0l-4-4m4 4l4-4M3 15h12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </span>
            <span className="sl-download-text">
              <span className="sl-download-title">Download Hasil Uji Lab</span>
              <span className="sl-download-sub">PDF · SIG · 2025</span>
            </span>
            <span className="sl-download-arrow">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 7h8m0 0L7 3m4 4L7 11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </span>
          </a>
        </div>

        {/* Parallax field of sachets & test tubes */}
        <div className="sl-field" aria-hidden="true">
          {FIELD.map((item, i) => {
            const y = item.baseY + Math.sin(scrollY * 0.005 + i) * 0 + (scrollY - 4000) * item.speed * 0.15;
            return (
              <div
                key={i}
                className="sl-field-item"
                style={{
                  left: item.leftPct + '%',
                  transform: `translate(-50%, ${y}px) rotate(${item.rot}deg) scale(${item.scale})`,
                  zIndex: item.kind === 'tube' ? 2 : 1,
                }}
              >
                {item.kind === 'tube'
                  ? <TestTube fill={item.color} />
                  : <MiniSachet color={item.color} />
                }
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SectionLab });
