// ============================================================================
// interactions.jsx — special experience for "Corpo Transparente" only.
//
// Other works use the default Clara-style vertical stack (rendered directly
// in pages.jsx → ObraBody). The TV interaction stays because it mirrors the
// gallery experience: viewer faces a TV with the video, clicks/zooms into
// the screen, then browses the photographs horizontally — as in the
// installation.
// ============================================================================

const { useState: useStateInt, useEffect: useEffectInt, useRef: useRefInt } = React;

function imgSrc(name) { return IMG_BASE + name; }

// ============================================================================
// TV — Corpo Transparente
// ============================================================================
function TVInteraction({ work, lang }) {
  const t = T[lang];
  const cfg = work.interactionConfig || {};
  const cover = work.images[cfg.coverIndex ?? 0];
  const gallery = work.images.slice(cfg.galleryStart ?? 1);

  const [entered, setEntered] = useStateInt(false);
  const [scrollIdx, setScrollIdx] = useStateInt(0);

  useEffectInt(() => {
    if (!entered) return;
    const onKey = (e) => {
      if (e.key === 'Escape') setEntered(false);
      if (e.key === 'ArrowRight') setScrollIdx(i => Math.min(gallery.length - 1, i + 1));
      if (e.key === 'ArrowLeft')  setScrollIdx(i => Math.max(0, i - 1));
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [entered, gallery.length]);

  useEffectInt(() => {
    if (entered) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = prev; };
    }
  }, [entered]);

  return (
    <div style={{ position: 'relative' }}>
      {/* Living-room framing */}
      <div
        aria-hidden={entered}
        style={{
          position: 'relative',
          minHeight: 'min(72vh, 720px)',
          display: 'grid',
          placeItems: 'center',
          padding: '32px 0',
          opacity: entered ? 0 : 1,
          transition: 'opacity 600ms ease',
        }}
      >
        <CRTTelevision cover={cover} onEnter={() => setEntered(true)} lang={lang} />
        <div style={{
          marginTop: 24,
          fontFamily: 'var(--mono)', fontSize: 12,
          color: 'var(--ink-3)',
          textAlign: 'center',
        }}>
          {lang === 'pt'
            ? 'clique para entrar no ecrã'
            : 'click to step inside the screen'}
        </div>
      </div>

      {entered && (
        <div
          role="dialog" aria-modal="true"
          style={{
            position: 'fixed', inset: 0, zIndex: 90,
            background: '#0e0e0e', color: '#ededed',
            animation: 'tvOpen 700ms cubic-bezier(.7,0,.2,1) both',
            display: 'flex', flexDirection: 'column',
          }}
        >
          <div aria-hidden="true" style={{
            position: 'absolute', inset: 0, pointerEvents: 'none',
            background: 'repeating-linear-gradient(180deg, rgba(255,255,255,0.025) 0 1px, transparent 1px 3px)',
            mixBlendMode: 'overlay',
          }} />
          <div aria-hidden="true" style={{
            position: 'absolute', inset: 0, pointerEvents: 'none',
            background: 'radial-gradient(120% 80% at 50% 50%, transparent 50%, rgba(0,0,0,0.55) 100%)',
          }} />

          <div style={{
            position: 'relative', zIndex: 2,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '22px 32px',
            fontFamily: 'var(--mono)', fontSize: 12, letterSpacing: '0.04em',
            color: 'rgba(237,237,237,0.7)',
          }}>
            <span>{work.title.toLowerCase()} — {lang === 'pt' ? 'no interior do ecrã' : 'inside the screen'}</span>
            <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
              <span>{String(scrollIdx + 1).padStart(2, '0')} / {String(gallery.length).padStart(2, '0')}</span>
              <button
                onClick={() => setEntered(false)}
                data-cursor-hover
                style={{ color: '#ededed', fontFamily: 'var(--mono)', fontSize: 12 }}
              >
                {t.works.exit.toLowerCase()} ✕
              </button>
            </div>
          </div>

          <HorizontalGallery
            images={gallery}
            index={scrollIdx}
            onIndexChange={setScrollIdx}
            work={work}
          />

          <div style={{
            position: 'relative', zIndex: 2,
            textAlign: 'center', padding: '14px 0 22px',
            fontFamily: 'var(--mono)', fontSize: 11,
            color: 'rgba(237,237,237,0.55)',
          }}>
            ←   →   esc
          </div>

          <style>{`
            @keyframes tvOpen {
              0%   { clip-path: inset(45% 35% 45% 35% round 18px); opacity: 0.4; }
              60%  { clip-path: inset(8% 4% 8% 4% round 6px); opacity: 1; }
              100% { clip-path: inset(0 0 0 0 round 0); opacity: 1; }
            }
          `}</style>
        </div>
      )}
    </div>
  );
}

function CRTTelevision({ cover, onEnter, lang }) {
  return (
    <button
      onClick={onEnter}
      data-cursor-hover
      aria-label={lang === 'pt' ? 'Entrar no ecrã' : 'Enter the screen'}
      style={{
        position: 'relative',
        width: 'min(560px, 78vw)',
        aspectRatio: '4 / 3.2',
        background: 'linear-gradient(180deg, #2a2622 0%, #1a1714 100%)',
        borderRadius: 18,
        boxShadow: '0 30px 60px -20px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.06), inset 0 -2px 0 rgba(0,0,0,0.3)',
        padding: 18,
        transition: 'transform 300ms cubic-bezier(.2,.6,.2,1)',
      }}
      onMouseOver={(e) => e.currentTarget.style.transform = 'translateY(-2px)'}
      onMouseOut={(e) => e.currentTarget.style.transform = 'translateY(0)'}
    >
      <div style={{
        position: 'relative',
        width: '100%', height: '100%',
        borderRadius: 10,
        overflow: 'hidden',
        background: '#0a0a0a',
        boxShadow: 'inset 0 0 60px rgba(0,0,0,0.6), inset 0 0 3px rgba(255,255,255,0.1)',
      }}>
        <img
          src={imgSrc(cover)}
          alt="" aria-hidden="true"
          style={{
            width: '100%', height: '100%', objectFit: 'cover',
            filter: 'saturate(0.8) contrast(1.05) brightness(0.9)',
            animation: 'crtFlicker 4s ease-in-out infinite',
          }}
          draggable="false"
        />
        <div aria-hidden="true" style={{
          position: 'absolute', inset: 0,
          background: 'repeating-linear-gradient(180deg, rgba(255,255,255,0.04) 0 1px, transparent 1px 3px)',
          mixBlendMode: 'overlay',
        }} />
        <div aria-hidden="true" style={{
          position: 'absolute', inset: 0,
          boxShadow: 'inset 0 0 80px 10px rgba(0,0,0,0.55)',
          borderRadius: 14,
        }} />
      </div>
      <span aria-hidden="true" style={{
        position: 'absolute', left: 14, top: 18,
        width: 4, height: 4, borderRadius: '50%',
        background: '#a83a2a', boxShadow: '0 0 8px #a83a2a55',
      }} />

      <style>{`
        @keyframes crtFlicker { 0%, 100% { filter: saturate(0.8) contrast(1.05) brightness(0.9); }
                                 47% { filter: saturate(0.8) contrast(1.05) brightness(0.94); }
                                 53% { filter: saturate(0.8) contrast(1.05) brightness(0.84); } }
      `}</style>
    </button>
  );
}

function HorizontalGallery({ images, index, onIndexChange, work }) {
  const railRef = useRefInt(null);

  useEffectInt(() => {
    const rail = railRef.current; if (!rail) return;
    const child = rail.children[index]; if (!child) return;
    child.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
  }, [index]);

  return (
    <div style={{ position: 'relative', zIndex: 2, flex: 1, minHeight: 0 }}>
      <div
        ref={railRef}
        onWheel={(e) => {
          if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
            e.currentTarget.scrollBy({ left: e.deltaY, behavior: 'auto' });
          }
        }}
        style={{
          height: '100%', overflowX: 'auto', overflowY: 'hidden',
          display: 'flex', alignItems: 'center', gap: 32,
          padding: '0 calc(50vw - 320px)',
          scrollSnapType: 'x mandatory',
          scrollbarWidth: 'none',
        }}
      >
        {images.map((src, i) => (
          <figure key={i}
            style={{
              flex: '0 0 auto',
              height: '78%',
              maxHeight: '70vh',
              scrollSnapAlign: 'center',
              margin: 0,
            }}
            onClick={() => onIndexChange(i)}
          >
            <img src={imgSrc(src)} alt={`${work.title} ${i + 1}`}
              draggable="false"
              style={{
                height: '100%', width: 'auto', maxWidth: '80vw',
                objectFit: 'contain',
                opacity: i === index ? 1 : 0.5,
                transition: 'opacity 480ms ease, transform 480ms ease',
                transform: i === index ? 'scale(1)' : 'scale(0.94)',
                boxShadow: i === index ? '0 30px 80px -20px rgba(0,0,0,0.6)' : 'none',
              }}
            />
          </figure>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { TVInteraction });
