// ============================================================
// SECTION HORMON — Hormonal imbalance explanation
// Two-column editorial. Left: big serif title + visual.
// Right: explanation paragraphs.
// ============================================================

function SectionHormon() {
  const [balanced, setBalanced] = React.useState(false);
  // Bubble lifecycle per symptom id: 'visible' | 'popping-out' | 'gone' | 'popping-in'
  const [bubbleStates, setBubbleStates] = React.useState({});

  // Track mobile viewport so the hormone bubbles can scale up for narrow screens.
  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);
    };
  }, []);

  // Circle radii — imbalanced: progesteron noticeably bigger than estrogen.
  // After Yojea: both equal. Mobile pushes radii close to the viewBox limits
  // so the bubbles fill the entire diagram area dramatically.
  const balancedR   = isMobile ? 84 : 64;

  // Imbalanced → both circles continuously take new RANDOM radii that are
  // always clearly different and either one can be the bigger — so sometimes
  // estrogen > progesteron and sometimes the reverse. A new target is set
  // before the previous transition finishes (interval < transition duration)
  // so the circles glide continuously and never visibly "snap".
  const [dynR, setDynR] = React.useState(null);
  React.useEffect(() => {
    if (balanced) { setDynR(null); return; }
    const lo  = isMobile ? 52 : 42;
    const hi  = isMobile ? 104 : 92;
    const gap = isMobile ? 16 : 13;   // guaranteed min difference
    const tick = () => {
      const a = lo + Math.random() * (hi - lo);
      let b = lo + Math.random() * (hi - lo);
      let guard = 0;
      while (Math.abs(a - b) < gap && guard++ < 20) b = lo + Math.random() * (hi - lo);
      setDynR({ a: Math.round(a), b: Math.round(b) });
    };
    tick();
    const id = setInterval(tick, 1900);
    return () => clearInterval(id);
  }, [balanced, isMobile]);

  const estrogenR    = balanced ? balancedR : (dynR ? dynR.a : (isMobile ? 60 : 48));
  const progesteronR = balanced ? balancedR : (dynR ? dynR.b : (isMobile ? 96 : 86));

  // Envelope rect dimensions follow balanced radius so margin stays consistent
  // (~10px around the two balanced bubbles centered at cx=102 and cx=282 in
  // the 0–384 viewBox).
  const CX_A = 102;
  const CX_B = 282;
  const CY   = 120;
  const VB_W = 384;
  const envMargin = 10;
  const envX = CX_A - balancedR - envMargin;
  const envY = CY - balancedR - envMargin;
  const envW = VB_W - 2 * envX;
  const envH = 2 * (balancedR + envMargin);
  const envR = balancedR + envMargin;

  // Floating symptom bubbles scattered across the WHOLE "Akar Masalah" section.
  // The set is randomized every Reset click (duplicates allowed) so the user
  // sees a different count and mix each cycle.
  const BASE_SYMPTOMS = React.useMemo(() => [
    { key: 'pd',        label: 'Tidak Percaya Diri', size: 96 },
    { key: 'keputihan', label: 'Keputihan',          size: 84 },
    { key: 'mood',      label: 'Mood Swing',         size: 88 },
    { key: 'siklus',    label: 'Siklus Tak Teratur', size: 92 },
    { key: 'jerawat',   label: 'Jerawatan',          size: 80 },
    { key: 'nyeri',     label: 'Nyeri Berlebih',     size: 86 },
    { key: 'bau',       label: 'Bau Tak Sedap',      size: 90 },
    { key: 'lelah',     label: 'Mudah Lelah',        size: 84 },
    { key: 'sakit',     label: 'Sakit Kepala',       size: 88 },
    { key: 'cemas',     label: 'Mudah Cemas',        size: 86 },
    { key: 'gemuk',     label: 'Berat Naik',         size: 82 },
  ], []);

  const makeBatch = React.useCallback(() => {
    // Always 10 bubbles, with duplicates allowed (random sample).
    const count = 10;
    const batch = [];
    for (let i = 0; i < count; i++) {
      const src = BASE_SYMPTOMS[Math.floor(Math.random() * BASE_SYMPTOMS.length)];
      const sizeJitter = Math.round((Math.random() - 0.5) * 18);
      batch.push({
        id: `${src.key}_${i}_${Math.random().toString(36).slice(2, 6)}`,
        key: src.key,
        label: src.label,
        size: Math.max(70, src.size + sizeJitter),
        top: 6 + Math.random() * 86,
        left: 3 + Math.random() * 94,
      });
    }
    return batch;
  }, [BASE_SYMPTOMS]);

  const [symptomBatch, setSymptomBatch] = React.useState(makeBatch);

  // Positions keyed by bubble id, regenerated whenever the batch changes.
  const [positions, setPositions] = React.useState(() => {
    const p = {};
    symptomBatch.forEach(s => { p[s.id] = { top: s.top, left: s.left }; });
    return p;
  });
  React.useEffect(() => {
    const p = {};
    symptomBatch.forEach(s => { p[s.id] = { top: s.top, left: s.left }; });
    setPositions(p);
  }, [symptomBatch]);

  // Continuously reposition each symptom bubble to a new random spot within
  // the section (with safe-zone padding from edges). Each bubble has its own
  // independent timing so the motion looks organic, not synchronized.
  React.useEffect(() => {
    const timeouts = {};
    const scheduleNext = (id, initialDelay) => {
      const tick = () => {
        setPositions(prev => ({
          ...prev,
          [id]: {
            top: 6 + Math.random() * 86,
            left: 3 + Math.random() * 94,
          },
        }));
        timeouts[id] = setTimeout(tick, 5000 + Math.random() * 6000);
      };
      timeouts[id] = setTimeout(tick, initialDelay);
    };
    symptomBatch.forEach((s, i) => {
      scheduleNext(s.id, 1200 + i * 220 + Math.random() * 1500);
    });
    return () => Object.values(timeouts).forEach(clearTimeout);
  }, [symptomBatch]);

  // Drive the staggered pop-out (on Yojea) and pop-in (on Reset) lifecycles.
  const isFirstRun = React.useRef(true);
  React.useEffect(() => {
    if (isFirstRun.current) {
      isFirstRun.current = false;
      return;
    }
    const timers = [];
    symptomBatch.forEach((s, i) => {
      const stagger = Math.min(900, 50 * i);
      if (balanced) {
        // POP-OUT: visible → popping-out (0.7s burst) → gone
        timers.push(setTimeout(() => {
          setBubbleStates(prev => ({ ...prev, [s.id]: 'popping-out' }));
        }, stagger));
        timers.push(setTimeout(() => {
          setBubbleStates(prev => ({ ...prev, [s.id]: 'gone' }));
        }, stagger + 700));
      } else {
        // POP-IN: gone → popping-in (0.6s reverse burst) → visible
        timers.push(setTimeout(() => {
          setBubbleStates(prev => ({ ...prev, [s.id]: 'popping-in' }));
        }, stagger));
        timers.push(setTimeout(() => {
          setBubbleStates(prev => ({ ...prev, [s.id]: 'visible' }));
        }, stagger + 600));
      }
    });
    return () => timers.forEach(clearTimeout);
  }, [balanced, symptomBatch]);

  // Click handler: toggles balanced; when Reset is pressed we also regenerate
  // a fresh random batch (so count + mix changes every cycle).
  const handleMinumClick = () => {
    if (balanced) {
      // Reset → regenerate batch & start new bubbles hidden, then flip.
      const newBatch = makeBatch();
      const initial = {};
      newBatch.forEach(s => { initial[s.id] = 'gone'; });
      setBubbleStates(initial);
      setSymptomBatch(newBatch);
      setBalanced(false);
    } else {
      setBalanced(true);
    }
  };

  // ─── Brighten a bubble's label when it overlaps the (dark) hormone box ──
  // The card is opaque dark-red while imbalanced, so dark bubble text on top
  // of it is unreadable. We poll each bubble's live rect vs the card rect and
  // flag the overlapping ones so their label flips to a light color.
  const cardRef = React.useRef(null);
  const bubbleRefs = React.useRef({});
  const [overBox, setOverBox] = React.useState(() => new Set());
  React.useEffect(() => {
    const check = () => {
      const card = cardRef.current;
      if (!card) return;
      const cr = card.getBoundingClientRect();
      const next = new Set();
      for (const id in bubbleRefs.current) {
        const el = bubbleRefs.current[id];
        if (!el) continue;
        const r = el.getBoundingClientRect();
        if (r.right > cr.left && r.left < cr.right && r.bottom > cr.top && r.top < cr.bottom) {
          next.add(id);
        }
      }
      setOverBox(prev => {
        if (prev.size === next.size && [...next].every(x => prev.has(x))) return prev;
        return next;
      });
    };
    check();
    const id = setInterval(check, 150);
    return () => clearInterval(id);
  }, [symptomBatch]);

  return (
    <section className="sho" id="hormon">
      {/* Section-wide scatter of floating symptom bubbles — sits behind the
          content layer and across the entire "Akar Masalah" area. */}
      <div className="sho-symptoms" aria-hidden="true">
        {symptomBatch.map((s, i) => {
          const phase = bubbleStates[s.id] || 'visible';
          const cls =
            phase === 'popping-out' ? ' is-popping-out' :
            phase === 'popping-in'  ? ' is-popping-in' :
            phase === 'gone'        ? ' is-gone' : '';
          const pos = positions[s.id] || { top: s.top, left: s.left };
          return (
            <div
              key={s.id}
              ref={el => { if (el) bubbleRefs.current[s.id] = el; else delete bubbleRefs.current[s.id]; }}
              className={'sho-symptom' + cls + (overBox.has(s.id) ? ' is-over-box' : '')}
              style={{
                top: pos.top + '%',
                left: pos.left + '%',
                width: s.size + 'px',
                height: s.size + 'px',
                animationDelay: `-${(i % 8) * 0.4}s`,
                animationDuration: `${3.2 + (i % 4) * 0.4}s`,
              }}
            >
              <div className="sho-symptom-inner">
                <span className="sho-symptom-label">{s.label}</span>
              </div>
              {/* Burst layer used by both pop-out and pop-in */}
              <div className="sho-symptom-pop">
                <span className="sho-symptom-ring" />
                {[...Array(8)].map((_, k) => (
                  <span
                    key={k}
                    className="sho-symptom-shard"
                    style={{ '--a': (k * 45) + 'deg' }}
                  />
                ))}
              </div>
            </div>
          );
        })}
      </div>

      <div className="sho-container">
        {/* Interactive hormone balance diagram — full-width card on top */}
        <div ref={cardRef} className={'sho-diagram sho-diagram--card' + (balanced ? ' is-balanced' : '')}>
          {/* State-reactive background FX:
              • imbalanced → harsh red radial pulse
              • balanced   → soft blue wave drift */}
          <div className="sho-fx" aria-hidden="true">
            <span className="sho-fx-red" />
            <span className="sho-fx-red sho-fx-red-2" />
            <span className="sho-fx-blue" />
            <span className="sho-fx-blue sho-fx-blue-2" />
          </div>
              {/* Status indicator — matches "Akar Masalah" eyebrow style */}
              <div
                className="sho-status"
                data-state={balanced ? 'balanced' : 'imbalanced'}
              >
                {balanced ? 'Seimbang' : 'Tidak Seimbang'}
              </div>

              {/* Stage — SVG diagram + floating symptom bubbles around it */}
              <div className="sho-stage">
                <svg viewBox="0 14 384 212" fill="none" aria-hidden="true">
                <defs>
                  <linearGradient id="shoHormone1" x1="0" y1="0" x2="1" y2="1">
                    <stop offset="0%" stopColor="#E85D1A"/>
                    <stop offset="100%" stopColor="#C84A14"/>
                  </linearGradient>
                  <linearGradient id="shoHormone2" x1="0" y1="0" x2="1" y2="1">
                    <stop offset="0%" stopColor="#1F1612"/>
                    <stop offset="100%" stopColor="#3D2F25"/>
                  </linearGradient>
                </defs>

                {/* Yojea envelope — rounded rectangle ("pill" with full
                    rounded edges) sized to give consistent margin around
                    the two balanced bubbles. Adapts to mobile bubble size. */}
                <rect
                  className="sho-envelope-fill"
                  x={envX} y={envY} width={envW} height={envH}
                  rx={envR} ry={envR}
                  fill="rgba(232,93,26,0.06)"
                />
                <rect
                  className="sho-envelope"
                  x={envX} y={envY} width={envW} height={envH}
                  rx={envR} ry={envR}
                  fill="none"
                  stroke="#E85D1A"
                  strokeWidth="1.6"
                  strokeDasharray="6 5"
                />

                {/* Left bubble — Estrogen */}
                <g className="sho-bubble-group sho-bubble-group--a">
                  <circle
                    className="sho-bubble"
                    cx={CX_A} cy={CY}
                    r={estrogenR}
                    fill="url(#shoHormone1)"
                  />
                  <text className="sho-bubble-eyebrow" x={CX_A} y="110" textAnchor="middle"
                        fontFamily="Plus Jakarta Sans" fontSize="8" fontWeight="600"
                        letterSpacing="2.2" fill="rgba(255,255,255,0.78)">
                    HORMON
                  </text>
                  <text className="sho-bubble-name" x={CX_A} y="134" textAnchor="middle"
                        fontFamily="Instrument Serif" fontStyle="italic" fontSize="19" fill="#fff">
                    Estrogen
                  </text>
                </g>

                {/* Right bubble — Progesteron */}
                <g className="sho-bubble-group sho-bubble-group--b">
                  <circle
                    className="sho-bubble"
                    cx={CX_B} cy={CY}
                    r={progesteronR}
                    fill="url(#shoHormone2)"
                  />
                  <text className="sho-bubble-eyebrow" x={CX_B} y="110" textAnchor="middle"
                        fontFamily="Plus Jakarta Sans" fontSize="8" fontWeight="600"
                        letterSpacing="2.2" fill="rgba(255,255,255,0.7)">
                    HORMON
                  </text>
                  <text className="sho-bubble-name" x={CX_B} y="134" textAnchor="middle"
                        fontFamily="Instrument Serif" fontStyle="italic" fontSize="18" fill="#fff">
                    Progesteron
                  </text>
                </g>

                {/* Sparkles — drift when balanced */}
                <g className="sho-sparkles" fill="#E85D1A">
                  <circle cx="192" cy="38" r="2.5"/>
                  <circle cx="216" cy="60" r="1.5"/>
                  <circle cx="168" cy="60" r="1.5"/>
                  <circle cx="192" cy="202" r="2.5"/>
                  <circle cx="168" cy="180" r="1.5"/>
                  <circle cx="216" cy="180" r="1.5"/>
                </g>
              </svg>
              </div>

              <div className="sho-diagram-caption">
                <button
                  type="button"
                  className="sho-action"
                  onClick={handleMinumClick}
                  aria-pressed={balanced}
                >
                  <span className="sho-action-dot" />
                  {balanced ? 'Reset' : 'Minum Yojea'}
                  <span className="click-hint click-hint-minum" 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>
                </button>
              </div>
            </div>

        {/* Akar Masalah — eyebrow */}
        <div className="sho-eyebrow">
          <span className="sho-eyebrow-line" />
          Akar Masalah
        </div>

        {/* Two-column: big serif title (left) + explanation (right) */}
        <div className="sho-grid">
          <div className="sho-left">
            <h2 className="sho-title">
              Ketidakseimbangan<br/>
              hormon<br/>
              <em>pangkal gangguan</em><br/>
              <em>haid.</em>
            </h2>
          </div>

          <div className="sho-right">
            <p className="sho-lead">
              Yojea bekerja dengan menyeimbangkan hormon <strong>estrogen</strong> dan
              <strong> progesteron</strong> dalam tubuh wanita.
            </p>
            <p className="sho-body">
              Formula Yojea mengandung bahan aktif dengan sifat <em>anti-inflamasi</em> dan
              <em> antioksidan</em> yang berperan penting dalam menjaga kesehatan tubuh.
            </p>
            <p className="sho-body">
              Dengan kombinasi ini, Yojea tidak hanya membantu mengatasi nyeri menstruasi,
              tetapi juga mendukung kesehatan tubuh secara menyeluruh.
            </p>
          </div>
        </div>

        {/* Feature trio — full-width row below the columns.
            Order: Penyeimbang Hormonal · Antioksidan · Anti-inflamasi */}
        <div className="sho-features sho-features--row">
          <div className="sho-feature">
            <div className="sho-feature-icon">
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                <path d="M3 11h4l2-6 4 12 2-6h4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <div>
              <div className="sho-feature-title">Penyeimbang Hormonal</div>
              <div className="sho-feature-text">Menstabilkan siklus &amp; mood sepanjang bulan.</div>
            </div>
          </div>
          <div className="sho-feature">
            <div className="sho-feature-icon">
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                <path d="M11 2C7 6 4 9 4 13a7 7 0 0014 0c0-4-3-7-7-11z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/>
              </svg>
            </div>
            <div>
              <div className="sho-feature-title">Antioksidan</div>
              <div className="sho-feature-text">Membantu melawan radikal bebas, menjaga sel tubuh tetap sehat.</div>
            </div>
          </div>
          <div className="sho-feature">
            <div className="sho-feature-icon">
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                <path d="M11 2v18M2 11h18" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
                <circle cx="11" cy="11" r="9" stroke="currentColor" strokeWidth="1.4"/>
              </svg>
            </div>
            <div>
              <div className="sho-feature-title">Anti-inflamasi</div>
              <div className="sho-feature-text">Membantu mengurangi peradangan &amp; nyeri haid secara alami.</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SectionHormon });
