const { useState: useRState, useEffect: useREffect, useRef: useRRef } = React;

function useSectionProgress(ref, extra) {
  const [p, setP] = useRState(0);
  const [pinned, setPinned] = useRState(false);
  const [isMobile, setIsMobile] = useRState(false);
  useREffect(() => {
    const mq = window.matchMedia('(max-width: 820px)');
    const on = () => setIsMobile(mq.matches);
    on(); mq.addEventListener('change', on);
    return () => mq.removeEventListener('change', on);
  }, []);
  useREffect(() => {
    const el = ref.current; if (!el) return;
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) { setP(1); return; }
    if (isMobile) {
      let raf = null, start = null, playing = false;
      const step = (t) => { if (!start) start = t; const e = Math.min(1, (t - start) / 5200); setP(e); if (e < 1) raf = requestAnimationFrame(step); };
      const io = new IntersectionObserver((ents) => {
        ents.forEach((en) => { if (en.isIntersecting && !playing) { playing = true; raf = requestAnimationFrame(step); io.disconnect(); } });
      }, { threshold: 0.3 });
      io.observe(el);
      return () => { io.disconnect(); if (raf) cancelAnimationFrame(raf); };
    }
    let raf = null;
    const compute = () => {
      const r = el.getBoundingClientRect();
      setP(Math.max(0, Math.min(1, -r.top / extra)));
      setPinned(r.top <= 4 && r.bottom > window.innerHeight * 0.55);
    };
    const onScroll = () => { if (raf) return; raf = requestAnimationFrame(() => { compute(); raf = null; }); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    compute();
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, [extra, isMobile]);
  return { p, isMobile, pinned };
}

function FallingIngredient({ text, icon, startAt, endAt, progress, fromX, toX, travel, compact }) {
  const t = Math.max(0, Math.min(1, (progress - startAt) / Math.max(0.001, endAt - startAt)));
  const eased = t * t * (3 - 2 * t);
  const y = -20 + eased * travel;
  const x = fromX + (toX - fromX) * eased;
  const opacity = t <= 0 ? 0 : (t < 0.15 ? t / 0.15 : (t > 0.85 ? Math.max(0, (1 - t) / 0.15) : 1));
  return (
    <div style={{
      position: 'absolute', top: 0, left: '50%', width: compact ? 76 : 128,
      transform: `translate(-50%, ${y}px) translateX(${x}px) scale(${0.85 + 0.15 * eased})`,
      opacity, pointerEvents: 'none', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
    }}>
      <span style={{ width: compact ? 24 : 30, height: compact ? 24 : 30, borderRadius: '50%', border: '1px solid var(--line-gold)', background: 'rgba(201,168,106,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', flex: 'none' }}>
        {(window.PS_ING_IMAGES || {})[text]
          ? <img src={window.PS_ING_IMAGES[text]} alt="" draggable={false} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          : <IconGlyph kind={icon} size={compact ? 12 : 15} />}
      </span>
      <span className="ps-tick" style={{ fontSize: compact ? 7 : 9, textAlign: 'center', color: 'var(--bone-100)', lineHeight: 1.2 }}>{text}</span>
    </div>
  );
}

const PS_RING_SEGS = [
  { id: 'frequency', start: 0.04, end: 0.175 },
  { id: 'needmax', start: 0.175, end: 0.31 },
  { id: 'spg', start: 0.31, end: 0.445 },
  { id: 'pulse', start: 0.445, end: 0.58 },
  { id: 'gaian8', start: 0.63, end: 0.88 },
];
const psRingFill = (s, p) => Math.max(0, Math.min(1, (p - s.start) / (s.end - s.start)));
function psRingCounts() {
  return PS_RING_SEGS.map((s) => ((window.PS_PRODUCTS[s.id] || {}).ingredients || []).length);
}

function IngredientRing({ p }) {
  const R = 45, C = 2 * Math.PI * R, SW = 3.6;
  const counts = psRingCounts(), total = counts.reduce((a, b) => a + b, 0) || 1;
  let acc = 0;
  const arcs = PS_RING_SEGS.map((s, i) => {
    const frac = counts[i] / total, a0 = acc; acc += frac;
    const full = Math.max(0, frac * C - 1.6);
    return { key: s.id, color: ((window.PS_PRODUCTS[s.id] || {}).sig) || 'var(--gold-bright)', rot: -90 + a0 * 360, len: full * psRingFill(s, p), fill: psRingFill(s, p) };
  });
  const lit = arcs.reduce((n, a) => n + a.fill, 0) / arcs.length;
  return (
    <svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden="true" style={{ display: 'block', overflow: 'visible' }}>
      <circle cx="50" cy="50" r={R} fill="none" stroke="rgba(198,168,104,0.14)" strokeWidth={SW} />
      <circle cx="50" cy="50" r={R + 4.2} fill="none" stroke="rgba(198,168,104,0.16)" strokeWidth="0.35" />
      <circle cx="50" cy="50" r={R - 4.2} fill="none" stroke="rgba(198,168,104,0.1)" strokeWidth="0.35" />
      <g style={{ filter: 'blur(2.6px)', opacity: 0.55 + lit * 0.35 }}>
        {arcs.map((a) => (
          <circle key={'g' + a.key} cx="50" cy="50" r={R} fill="none" stroke={a.color} strokeWidth={SW * 1.9}
            strokeDasharray={a.len + ' ' + C} transform={'rotate(' + a.rot + ' 50 50)'} style={{ transition: 'stroke-dasharray 140ms linear' }} />
        ))}
      </g>
      <g style={{ filter: 'drop-shadow(0 0 5px rgba(224,196,126,0.65))' }}>
        {arcs.map((a) => (
          <circle key={a.key} cx="50" cy="50" r={R} fill="none" stroke={a.color} strokeWidth={SW}
            strokeDasharray={a.len + ' ' + C} transform={'rotate(' + a.rot + ' 50 50)'} style={{ transition: 'stroke-dasharray 140ms linear' }} />
        ))}
      </g>
    </svg>
  );
}

function BodyFigure({ inner, outer, spoon, size, p }) {
  const w = size, h = Math.round(size * 0.953);
  return (
    <div style={{ position: 'relative', width: w, height: h }}>
      <div style={{ position: 'absolute', left: '50%', top: '50%', width: Math.round(w * 1.04), height: Math.round(w * 1.04), transform: 'translate(-50%,-50%)', pointerEvents: 'none', zIndex: 3 }}>
        <IngredientRing p={p} />
      </div>
      <img src="assets/vitruvian-sm.png" alt="" aria-hidden="true" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain',
        opacity: 0.78, filter: 'invert(1) sepia(1) saturate(0.7) hue-rotate(2deg) brightness(1.35)',
      }} />
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0, overflow: 'hidden',
        WebkitMaskImage: 'url(assets/vitruvian-sm.png)', maskImage: 'url(assets/vitruvian-sm.png)',
        WebkitMaskSize: 'contain', maskSize: 'contain', WebkitMaskRepeat: 'no-repeat', maskRepeat: 'no-repeat',
        WebkitMaskPosition: 'center', maskPosition: 'center',
      }}>
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0, height: `${Math.round(inner * 100)}%`,
          background: 'linear-gradient(180deg, rgba(224,196,126,0.95), rgba(201,168,106,0.55))',
          boxShadow: '0 -8px 26px rgba(201,168,106,0.55)', transition: 'height 180ms linear',
        }} />
      </div>
      <div aria-hidden="true" className={outer > 0.85 ? 'ps-skin-pulse' : undefined} style={{
        position: 'absolute', inset: 0,
        WebkitMaskImage: 'url(assets/vitruvian-sm.png)', maskImage: 'url(assets/vitruvian-sm.png)',
        WebkitMaskSize: 'contain', maskSize: 'contain', WebkitMaskRepeat: 'no-repeat', maskRepeat: 'no-repeat',
        WebkitMaskPosition: 'center', maskPosition: 'center',
        background: 'radial-gradient(ellipse at 50% 42%, rgba(255,232,168,1), rgba(224,196,126,0.75) 55%, rgba(201,168,106,0.4) 76%, transparent 88%)',
        opacity: outer, transition: 'opacity 300ms linear', mixBlendMode: 'screen',
      }} />
      <div aria-hidden="true" className={outer > 0.85 ? 'ps-skin-pulse' : undefined} style={{
        position: 'absolute', inset: '-8%', borderRadius: '50%',
        background: 'radial-gradient(circle at 50% 46%, rgba(224,196,126,0.55), rgba(201,168,106,0.18) 46%, transparent 68%)',
        opacity: Math.max(inner * 0.5, outer), transition: 'opacity 300ms linear', pointerEvents: 'none',
      }} />
    </div>
  );
}

function RoutineCue({ states, p }) {
  if (p >= 0.97) return null;
  const filled = states.filter((x) => x !== 'wait').length;
  return (
    <div aria-hidden="true" style={{
      position: 'fixed', right: 14, top: '50%', transform: 'translateY(-50%)', zIndex: 22, pointerEvents: 'none',
      display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 12,
      padding: '14px 14px 13px', background: 'rgba(16,18,23,0.78)', backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
      border: '1px solid var(--line-gold)', maxWidth: 132, textAlign: 'right',
    }}>
      <span className="ps-tick" style={{ color: 'var(--gold-bright)', fontSize: 10, letterSpacing: '0.16em', lineHeight: 1.5 }}>GÖRGESS<br />TOVÁBB</span>
      <span style={{ display: 'flex', flexDirection: 'column', gap: 7, alignItems: 'flex-end' }}>
        {states.map((st, i) => (
          <span key={i} style={{
            width: st === 'active' ? 22 : 14, height: 2,
            background: st === 'wait' ? 'rgba(233,227,214,0.22)' : 'var(--gold-bright)',
            transition: 'width 500ms var(--ease-out), background 500ms var(--ease-out)',
          }} />
        ))}
      </span>
      <span className="ps-tick" style={{ color: 'rgba(233,227,214,0.55)', fontSize: 9, letterSpacing: '0.14em' }}>{filled} / {states.length}</span>
      <span style={{ width: '100%', height: 1, background: 'var(--line)' }} />
      <span className="ps-tick" style={{ color: 'rgba(233,227,214,0.6)', fontSize: 8.5, letterSpacing: '0.13em', lineHeight: 1.6 }}>A RUTIN<br />FELTÁRUL</span>
    </div>
  );
}

function SecondsClock({ progress }) {
  const total = 180;
  const s = Math.round(Math.max(0, Math.min(1, progress)) * total);
  const mm = Math.floor(s / 60), ss = String(s % 60).padStart(2, '0');
  return (
    <div style={{ position: 'absolute', top: 0, right: 0, textAlign: 'right' }}>
      <span className="ps-tick" style={{ display: 'block', color: 'var(--fg-faint)', fontSize: 9, marginBottom: 4 }}>ELTELT IDŐ</span>
      <span className="ps-display" style={{ fontSize: 'clamp(1.6rem,3vw,2.4rem)', color: 'var(--accent)', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{mm}:{ss}</span>
    </div>
  );
}

function BottleFrame({ product, height, width, state = 'active' }) {
  const wait = state === 'wait', active = state === 'active';
  return (
    <div style={{
      position: 'relative', width, flex: '0 0 auto', padding: '10px 5px 6px',
      border: `1px solid ${wait ? 'var(--line)' : active ? 'var(--gold-bright)' : 'var(--line-strong)'}`,
      background: active ? 'rgba(201,168,106,0.12)' : 'transparent',
      boxShadow: active ? '0 0 26px -6px rgba(201,168,106,0.55)' : 'none',
      transition: 'opacity 620ms var(--ease-out), border-color 620ms var(--ease-out), background 620ms var(--ease-out), box-shadow 620ms var(--ease-out)',
      opacity: wait ? 0.3 : 1, display: 'flex', flexDirection: 'column', alignItems: 'center',
    }}>
      <CornerMarks inset={4} />
      <div style={{ height, width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <img src={product.img} alt={product.name} style={{ maxHeight: '100%', maxWidth: '100%', objectFit: 'contain', display: 'block', filter: 'drop-shadow(0 14px 22px rgba(0,0,0,0.6))' }} />
      </div>
      <span className="ps-tick" style={{ display: 'block', marginTop: 6, minHeight: 24, fontSize: width < 78 ? 7 : 10, lineHeight: 1.25, color: wait ? 'var(--fg-faint)' : active ? 'var(--gold-bright)' : 'rgba(233,227,214,0.72)', textAlign: 'center', letterSpacing: '0.06em', transition: 'color 620ms var(--ease-out)' }}>{product.name}</span>
    </div>
  );
}

function RoutineDemo() {
  const ref = useRRef();
  const { p: pRaw, isMobile, pinned } = useSectionProgress(ref, 1500);
  const [pMax, setPMax] = useRState(0);
  useREffect(() => { if (pRaw > pMax + 0.001) setPMax(pRaw); }, [pRaw, pMax]);
  const p = Math.max(pRaw, pMax);
  const [vh, setVh] = useRState(typeof window !== 'undefined' ? window.innerHeight : 800);
  const [vw, setVw] = useRState(typeof window !== 'undefined' ? window.innerWidth : 1200);
  useREffect(() => {
    const on = () => { setVh(window.innerHeight); setVw(window.innerWidth); };
    on(); window.addEventListener('resize', on);
    return () => window.removeEventListener('resize', on);
  }, []);
  const inner = ['frequency', 'needmax', 'spg', 'pulse'].map((id) => window.PS_PRODUCTS[id]);
  const outer = window.PS_PRODUCTS['gaian8'];
  const phase1 = Math.max(0, Math.min(1, p / 0.62));
  const phase2 = Math.max(0, Math.min(1, (p - 0.62) / 0.34));
  const showOuter = p > 0.6;
  const clamp = (min, val, max) => Math.max(min, Math.min(max, val));
  const rowGap = isMobile ? 5 : 18;
  const cueGutter = isMobile ? 0 : 148;
  const maxRowW = Math.min(vw - (isMobile ? 34 : 96) - cueGutter, 1200);
  const widthCap = Math.floor((maxRowW - rowGap * 4) / 5);
  const closeFont = isMobile ? 22 : Math.round(clamp(26, vw * 0.032, 42));
  const subFont = isMobile ? 15 : Math.round(clamp(16, vw * 0.014, 19));
  const closeBlock = Math.round(closeFont * 1.25 + 10 + subFont * 1.45 + (isMobile ? 20 : 28));
  const headBlock = isMobile ? 78 : 104;
  const labelBlock = 34;
  let budget = Math.max(230, vh - headBlock - closeBlock - labelBlock - (isMobile ? 40 : 52));
  const bottleH = Math.round(clamp(44, Math.min(budget * 0.26, widthCap - 20), 170));
  budget -= bottleH;
  const bottleW = Math.min(widthCap, Math.round(bottleH + 28));
  const travel = Math.round(clamp(44, budget * 0.18, 120));
  const counterReserve = isMobile ? 60 : Math.round(clamp(54, budget * 0.2, 82));
  const counterFont = counterReserve - 16;
  const figH = Math.round(clamp(150, Math.min(budget - travel + 24 - counterReserve, vw * 0.82), 340));
  const figSize = Math.round(figH / 0.953);
  const ringR = Math.round(figSize * 0.53);
  const ringCounts = psRingCounts();
  const ringShown = PS_RING_SEGS.reduce((n, s, i) => n + Math.round(psRingFill(s, p) * ringCounts[i]), 0);
  const stageH = travel - 24 + figH + counterReserve;
  const step = isMobile ? Math.round((bottleW + rowGap)) : 168;
  const innerList = inner.map((prod) => (prod.ingredients || []).slice(0, 6));
  const innerTotal = inner.reduce((s, prod) => s + (prod.ingredients || []).length, 0);
  const innerShown = Math.round(phase1 * innerTotal);
  const outerAll = outer.ingredients || [];
  const outerList = outerAll.slice(0, 6);
  const outerShown = Math.round(Math.max(0, Math.min(1, (p - 0.63) / 0.24)) * outerAll.length);
  const stateFor = (gs, ge) => (p < gs ? 'wait' : p < ge ? 'active' : 'done');
  const innerStates = inner.map((_, pi) => stateFor(0.04 + pi * 0.135, 0.04 + pi * 0.135 + 0.135));
  const outerState = stateFor(0.63, 0.88);
  const allStates = innerStates.concat([outerState]);
  return (
    <section id="rutin" data-screen-label="3 perces rutin" ref={ref} style={{ position: 'relative', background: 'var(--ink-900)', height: isMobile ? 'auto' : 'calc(100vh + 1500px)' }}>
      <div style={{ position: isMobile ? 'static' : 'sticky', top: 0, height: isMobile ? 'auto' : '100vh', display: 'flex', alignItems: 'center', overflow: 'hidden', padding: 'var(--sp-5) var(--gutter)' }}>
        <div style={{ position: 'relative', width: '100%', maxWidth: 'var(--container)', margin: '0 auto', textAlign: 'center' }}>
          <Eyebrow gold style={{ justifyContent: 'center', marginBottom: 8 }}>EGY PÉLDA</Eyebrow>
          <h2 className="ps-h3" style={{ margin: '0 0 var(--sp-4)', color: 'var(--bone-100)', fontSize: 'clamp(1.1rem,2.2vw,1.7rem)' }}>Így néz ki egy <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>3 perces rutin.</em></h2>
          <SecondsClock progress={p} />

          {isMobile && p < 0.94 && (
            <p className="ps-tick" aria-hidden="true" style={{ margin: '0 0 10px', color: 'var(--gold-bright)', fontSize: 10, letterSpacing: '0.15em', animation: p < 0.06 ? 'psScrollPulse 2.4s ease-in-out infinite' : 'none' }}>
              GÖRGESS — FELTÁRUL A RUTIN ↓
            </p>
          )}
          {!isMobile && pinned && <RoutineCue states={allStates} p={p} />}
          {!isMobile && pinned && p < 0.05 && (
            <p className="ps-tick" aria-hidden="true" style={{ position: 'fixed', left: '50%', bottom: 92, transform: 'translateX(-50%)', zIndex: 22, margin: 0, padding: '11px 20px', background: 'rgba(16,18,23,0.82)', border: '1px solid var(--line-gold)', color: 'var(--gold-bright)', fontSize: 11.5, letterSpacing: '0.17em', whiteSpace: 'nowrap', pointerEvents: 'none', animation: 'psScrollPulse 2.4s ease-in-out infinite' }}>
              GÖRGESS — ÉS FELTÁRUL A 3 PERCES RUTIN ↓
            </p>
          )}
          <div style={{ display: 'flex', justifyContent: 'center', gap: rowGap, alignItems: 'flex-end', marginBottom: 4 }}>
            {inner.map((prod, pi) => <BottleFrame key={prod.id} product={prod} height={bottleH} width={bottleW} state={innerStates[pi]} />)}
            <BottleFrame product={outer} height={bottleH} width={bottleW} state={outerState} />
          </div>

          <div style={{ position: 'relative', height: stageH }}>
            <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: travel, pointerEvents: 'none', zIndex: 2 }}>
              {innerList.map((list, pi) => {
                const from = (pi - 2) * step;
                const groupStart = 0.04 + pi * 0.135;
                return list.map((ing, ii) => {
                  const slot = groupStart + ii * 0.018;
                  return (
                    <FallingIngredient key={ing + pi} text={ing} icon={window.ICON_CYCLE[(pi * 3 + ii) % window.ICON_CYCLE.length]}
                      startAt={slot} endAt={slot + 0.1} progress={p}
                      fromX={from} toX={(ii - 2) * 6} travel={travel - 10} compact={isMobile} />
                  );
                });
              })}
              {outerList.map((ing, ii) => (
                <FallingIngredient key={ing} text={ing} icon={window.ICON_CYCLE[(ii + 5) % window.ICON_CYCLE.length]}
                  startAt={0.64 + ii * 0.033} endAt={0.76 + ii * 0.033} progress={p}
                  fromX={2 * step} toX={(ii - 2) * 10} travel={travel + 10} compact={isMobile} />
              ))}
            </div>

            <div style={{ position: 'absolute', top: travel - 24, left: 0, right: 0, display: 'flex', justifyContent: 'center', pointerEvents: 'none' }} className={phase2 > 0.85 ? 'ps-vitruv-pulse' : undefined}>
              <BodyFigure inner={phase1} outer={phase2} size={figSize} p={p} />
            </div>

            <div style={{ position: 'absolute', top: travel - 24 + figH + 12, left: 0, right: 0, display: 'flex', justifyContent: 'center', alignItems: 'baseline', gap: isMobile ? 10 : 16 }}>
              <span className="ps-tick" style={{ color: 'var(--fg-faint)', fontSize: isMobile ? 11 : 13, letterSpacing: '0.2em' }}>ÖSSZESEN</span>
              <span className="ps-display" style={{ fontSize: counterFont, lineHeight: 1, color: 'var(--gold-bright)', fontVariantNumeric: 'tabular-nums', textShadow: '0 0 26px rgba(224,196,126,0.4)' }}>{ringShown}</span>
              <span className="ps-tick" style={{ color: 'var(--accent)', fontSize: isMobile ? 12 : 15, letterSpacing: '0.2em' }}>ÖSSZETEVŐ</span>
            </div>

            <div style={{ position: 'absolute', top: travel + 20, left: 0, right: 'calc(50% + ' + (ringR + 20) + 'px)', textAlign: 'right' }}>
              <span className="ps-tick" style={{ display: 'block', color: 'var(--accent)', fontSize: isMobile ? 15 : 21, letterSpacing: '0.1em' }}>{innerShown} ÖSSZETEVŐ</span>
              <span className="ps-small" style={{ display: 'block', marginTop: 6, color: 'var(--fg-2)', fontSize: isMobile ? 14 : 18 }}>Belsőleg</span>
            </div>
            <div style={{ position: 'absolute', top: travel + 20, right: cueGutter, left: 'calc(50% + ' + (ringR + 20) + 'px)', textAlign: 'left' }}>
              <span className="ps-tick" style={{ display: 'block', color: showOuter ? 'var(--accent)' : 'var(--fg-faint)', fontSize: isMobile ? 15 : 21, letterSpacing: '0.1em' }}>{outerShown} ÖSSZETEVŐ</span>
              <span className="ps-small" style={{ display: 'block', marginTop: 6, color: 'var(--fg-2)', fontSize: isMobile ? 14 : 18 }}>Külsőleg</span>
            </div>
          </div>

          <p className={`ps-display${phase2 > 0.85 ? ' ps-vitruv-pulse' : ''}`} style={{
            margin: 'var(--sp-4) 0 0', fontStyle: 'italic', fontSize: closeFont, lineHeight: 1.25, color: 'var(--bone-100)',
            opacity: phase2 > 0.85 ? 1 : 0, transform: phase2 > 0.85 ? 'none' : 'translateY(10px)', transition: 'opacity 700ms var(--ease-out), transform 700ms var(--ease-out)',
          }}>
            Ennyi volt. <span style={{ color: 'var(--accent)' }}>Összesen 3 perc, {innerTotal + outerAll.length} összetevő.</span>
          </p>
          <p className="ps-small" style={{
            margin: '10px 0 0', color: 'var(--fg-3)', fontSize: subFont, lineHeight: 1.45,
            opacity: phase2 > 0.9 ? 1 : 0, transition: 'opacity 700ms var(--ease-out) 200ms',
          }}>Egy napi ebéd árából.</p>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { RoutineDemo });
