/* global React, TimelineContext, clamp, Easing */
// ScrollStage — sticky scroll-driven video. The page scroll within the section
// drives the timeline 0 → duration, instead of a RAF playhead.
// Reuses TimelineContext from animations.jsx so Sprite/useTime still work.

const _sc = (v, lo, hi) => Math.max(lo, Math.min(hi, v));

function useIsMobile() {
  const [isMobile, setIsMobile] = React.useState(typeof window !== 'undefined' ? window.innerWidth < 1024 : false);
  React.useEffect(() => {
    const check = () => setIsMobile(window.innerWidth < 1024);
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);
  return isMobile;
}

function ScrollStage({
  width = 1920,
  height = 1080,
  duration = 60,
  background,
  scrollVH = 700,
  children,
  label,
  fit = 0.94, // fraction of viewport to occupy
}) {
  const isMobile = useIsMobile();
  const cWidth = isMobile ? 1080 : width;
  const cHeight = isMobile ? 1920 : height;

  const outerRef = React.useRef(null);
  const [time, setTime] = React.useState(0);
  const [scale, setScale] = React.useState(1);
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    const onScroll = () => {
      const el = outerRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = el.offsetHeight - vh;
      if (total <= 0) return;
      const scrolled = _sc(-rect.top, 0, total);
      const p = scrolled / total;
      setProgress(p);
      setTime(p * duration);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [duration]);

  React.useEffect(() => {
    const fit_ = () => {
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      const s = Math.min(vw / cWidth, vh / cHeight) * fit;
      setScale(s);
    };
    fit_();
    window.addEventListener('resize', fit_);
    return () => window.removeEventListener('resize', fit_);
  }, [cWidth, cHeight, fit]);

  const ctxValue = React.useMemo(() => ({ time, duration, playing: false }), [time, duration]);

  return (
    <section
      ref={outerRef}
      data-screen-label={label || `Reel · scroll ${Math.round(progress * 100)}%`}
      style={{ height: `${scrollVH}vh`, position: 'relative' }}
    >
      <div
        style={{
          position: 'sticky', top: 0, height: '100vh',
          overflow: 'hidden',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: 'var(--bataj-bg)',
        }}
      >
        {/* Clean solid background */}
        <div
          aria-hidden="true"
          style={{
            position: 'absolute', inset: 0,
            background: 'var(--bataj-bg)',
            pointerEvents: 'none',
          }}
        />

        {/* The canvas */}
        <div
          style={{
            width: cWidth, height: cHeight, background: background || 'transparent',
            position: 'relative',
            transform: `scale(${scale})`,
            transformOrigin: 'center',
            flexShrink: 0,
          }}
        >
          <TimelineContext.Provider value={ctxValue}>
            {children}
          </TimelineContext.Provider>
        </div>

        {/* Bottom hint */}
        <div
          style={{
            position: 'absolute', bottom: 24, left: '50%',
            transform: 'translateX(-50%)',
            fontFamily: 'JetBrains Mono, monospace',
            fontSize: 12, letterSpacing: '0.18em', textTransform: 'uppercase',
            color: 'color-mix(in srgb, var(--bataj-ink) 55%, transparent)',
            pointerEvents: 'none',
            display: 'flex', alignItems: 'center', gap: 14,
          }}
        >
          <span>↓ desplazá para avanzar</span>
          <span style={{
            width: 120, height: 2, background: 'color-mix(in srgb, var(--bataj-ink) 15%, transparent)',
            position: 'relative', overflow: 'hidden', borderRadius: 99,
          }}>
            <span style={{
              position: 'absolute', inset: 0, transform: `scaleX(${progress})`,
              transformOrigin: 'left', background: 'var(--bataj-accent)',
              transition: 'transform .1s linear',
            }} />
          </span>
          <span style={{ fontVariantNumeric: 'tabular-nums', width: 36, textAlign: 'right' }}>{Math.round(progress * 100)}%</span>
        </div>
      </div>
    </section>
  );
}

/* ──────────────────────────────────────────────────────────────
   Animated cursor — used in product scenes to show interactions.
   Provide keyframes [{t, x, y, click?}]; cursor lerps between them.
   ────────────────────────────────────────────────────────────── */

function CursorTrail({ keyframes, color = 'var(--bataj-ink)' }) {
  const { localTime } = useSprite();
  // find current segment
  let kfA = keyframes[0];
  let kfB = keyframes[keyframes.length - 1];
  let local = 1;
  for (let i = 0; i < keyframes.length - 1; i++) {
    if (localTime >= keyframes[i].t && localTime <= keyframes[i + 1].t) {
      kfA = keyframes[i]; kfB = keyframes[i + 1];
      const span = kfB.t - kfA.t || 0.0001;
      local = (localTime - kfA.t) / span;
      break;
    }
  }
  if (localTime <= keyframes[0].t) { kfA = keyframes[0]; kfB = keyframes[0]; local = 0; }
  if (localTime >= keyframes[keyframes.length - 1].t) {
    kfA = keyframes[keyframes.length - 1]; kfB = kfA; local = 1;
  }
  const eased = Easing.easeInOutCubic(local);
  const x = kfA.x + (kfB.x - kfA.x) * eased;
  const y = kfA.y + (kfB.y - kfA.y) * eased;
  // click pulse: if the segment ENDS in a click, pulse near local=1
  const click = kfB.click ? Math.max(0, 1 - Math.abs(local - 0.95) / 0.18) : 0;

  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: 'translate(-6px, -4px)',
      pointerEvents: 'none', zIndex: 50,
      willChange: 'left, top',
      transition: 'left .04s linear, top .04s linear',
    }}>
      <svg width="32" height="36" viewBox="0 0 32 36" style={{ filter: 'drop-shadow(0 4px 6px rgba(0,0,0,.25))' }}>
        <path d="M5 4 L5 28 L12 22 L17 32 L21 30 L16 20 L24 20 Z" fill={color} stroke="white" strokeWidth="1.3" strokeLinejoin="round"/>
      </svg>
      {/* click ripple */}
      {click > 0 && (
        <span style={{
          position: 'absolute', left: -4, top: -2,
          width: 40 * click + 18, height: 40 * click + 18,
          borderRadius: '50%',
          border: `2px solid var(--bataj-accent)`,
          opacity: 1 - click,
          transform: `translate(${-(40 * click + 18) / 2 + 10}px, ${-(40 * click + 18) / 2 + 12}px)`,
          pointerEvents: 'none',
        }} />
      )}
    </div>
  );
}

/* Chrome banner along the canvas top: section number, product name, counter */
function CanvasChrome({ idx, total, code, title, sub, accent }) {
  const isMobile = useIsMobile();
  return (
    <>
      <div style={{
        position: 'absolute', top: isMobile ? 50 : 30, left: isMobile ? 50 : 30,
        fontFamily: 'JetBrains Mono, monospace', fontSize: isMobile ? 22 : 14,
        letterSpacing: '0.18em', textTransform: 'uppercase',
        color: 'color-mix(in srgb, var(--bataj-ink) 60%, transparent)',
        zIndex: 5,
      }}>
        ┌── BATAJ.REEL · SEC.03
      </div>
      <div style={{
        position: 'absolute', top: isMobile ? 80 : 30, right: isMobile ? 50 : 30, left: isMobile ? 50 : 'auto',
        display: 'flex', alignItems: 'center', gap: 14,
        fontFamily: 'JetBrains Mono, monospace', fontSize: isMobile ? 18 : 14,
        letterSpacing: '0.18em', textTransform: 'uppercase',
        color: 'color-mix(in srgb, var(--bataj-ink) 60%, transparent)',
        zIndex: 5,
      }}>
        <span style={{ color: accent || 'var(--bataj-accent)' }}>● {code || ''}</span>
        <span>{title || ''}</span>
        {!isMobile && <span>{sub || ''}</span>}
        <span style={{ marginLeft: isMobile ? 'auto' : 0 }}>──┐</span>
      </div>
      {idx != null && (
        <div style={{
          position: 'absolute', bottom: isMobile ? 50 : 30, left: isMobile ? 50 : 30,
          fontFamily: 'Pixelify Sans, monospace', fontWeight: 700,
          fontSize: isMobile ? 260 : 96, lineHeight: 0.85, letterSpacing: '-0.04em',
          color: accent || 'var(--bataj-accent)',
          zIndex: 1,
        }}>
          {String(idx).padStart(2, '0')}
          <span style={{ color: 'color-mix(in srgb, var(--bataj-ink) 25%, transparent)' }}>
            /{String(total).padStart(2, '0')}
          </span>
        </div>
      )}
    </>
  );
}

/* Simple side panel renderer used by product scenes */
function SidePanel({ name, code, kicker, tagline, blurb, stats, stack, accent, dark = false }) {
  const isMobile = useIsMobile();
  const ink = dark ? '#F4EFE3' : 'var(--bataj-ink)';
  const mute = dark ? 'rgba(244,239,227,.55)' : 'color-mix(in srgb, var(--bataj-ink) 55%, transparent)';
  return (
    <div style={{
      position: 'absolute',
      left: isMobile ? 50 : undefined, right: isMobile ? undefined : 64,
      top: isMobile ? 140 : 140, bottom: isMobile ? undefined : 140,
      width: isMobile ? 980 : 460,
      color: ink,
      display: 'flex', flexDirection: 'column',
      pointerEvents: 'none', zIndex: 4,
    }}>
      <div style={{
        fontFamily: 'JetBrains Mono, monospace', fontSize: isMobile ? 24 : 13,
        letterSpacing: '0.18em', textTransform: 'uppercase',
        color: mute, marginBottom: isMobile ? 20 : 24,
      }}>
        <span style={{ color: accent }}>● {kicker}</span>
        <div style={{ marginTop: 6 }}>{code}</div>
      </div>
      <h3 style={{
        fontFamily: 'var(--bataj-display)',
        fontSize: isMobile ? 120 : 96, lineHeight: 0.88, letterSpacing: '-0.02em',
        color: ink, margin: 0, marginBottom: isMobile ? 12 : 8,
      }}>
        {name}
      </h3>
      <div style={{
        fontFamily: 'var(--bataj-display)', fontStyle: 'italic',
        fontSize: isMobile ? 54 : 40, lineHeight: 1.05, color: accent,
        marginBottom: isMobile ? 24 : 28,
      }}>
        {tagline}
      </div>
      <p style={{
        fontFamily: 'var(--bataj-sans)', fontSize: isMobile ? 36 : 18, lineHeight: 1.5,
        color: dark ? 'rgba(244,239,227,.75)' : 'color-mix(in srgb, var(--bataj-ink) 80%, transparent)',
        margin: 0, marginBottom: isMobile ? 24 : 28, maxWidth: isMobile ? 900 : 380,
      }}>
        {blurb}
      </p>
      {stats && (
        <div style={{
          borderTop: `1px solid ${dark ? 'rgba(244,239,227,.15)' : 'color-mix(in srgb, var(--bataj-ink) 18%, transparent)'}`,
          paddingTop: isMobile ? 16 : 14, marginBottom: isMobile ? 24 : 22,
        }}>
          {stats.map((s, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 16,
              padding: isMobile ? '12px 0' : '8px 0',
              borderBottom: `1px solid ${dark ? 'rgba(244,239,227,.1)' : 'color-mix(in srgb, var(--bataj-ink) 10%, transparent)'}`,
            }}>
              <span style={{
                fontFamily: 'JetBrains Mono, monospace', fontSize: isMobile ? 26 : 12,
                letterSpacing: '0.14em', textTransform: 'uppercase',
                color: mute,
              }}>{s.l}</span>
              <span style={{
                fontFamily: 'Pixelify Sans, monospace', fontWeight: 700,
                fontSize: isMobile ? 60 : 28, lineHeight: 1, color: ink, letterSpacing: '-0.02em',
              }}>{s.v}</span>
            </div>
          ))}
        </div>
      )}
      {stack && (
        <div style={{
          display: 'flex', flexWrap: 'wrap', gap: isMobile ? 16 : 6, marginTop: isMobile ? 10 : 'auto',
        }}>
          {stack.map((s) => (
            <span key={s} style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: isMobile ? 26 : 11,
              letterSpacing: '0.14em', textTransform: 'uppercase',
              padding: isMobile ? '12px 20px' : '4px 8px',
              border: `1px solid ${dark ? 'rgba(244,239,227,.2)' : 'color-mix(in srgb, var(--bataj-ink) 25%, transparent)'}`,
              color: mute, borderRadius: 8,
            }}>{s}</span>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ScrollStage, CursorTrail, CanvasChrome, SidePanel, useIsMobile });
