// VideoWall, a tilted, full-bleed wall of Knowaa work clips with the
// "Creative learning agency." statement floating over it.
// Rendered inside the purple Capabilities section (via its topSlot prop),
// so the section's curved top edge cuts the wall.

const { useEffect: useEffectWall, useRef: useRefWall } = React;

const WALL_ROWS = [
  ['01_appsflyer_ai-therapy', '05_animation_2d-office', '13_interactive_fire-hotspots', '19_ai_drive-mode', '09_animation_classroom', '22_ai_southwest-flight'],
  ['10_signature_real-pain', '14_ai-practice-module', '06_animation_headset-call', '20_ai_zim-appreciation', '03_appsflyer_hug-legpress', '17_monday_office-safety'],
  ['21_ai_factory-presenter', '07_animation_hangar', '12_monday_compliance-game', '02_appsflyer_limo', '18_growth-mindset_whiteboard', '08_animation_cube-mascot'],
  ['16_sap_cyber-security', '24_ai_coach', '11_signature_real-work', '04_amdocs_data-privacy', '23_ai_factory-workers', '25_signature_ergonomics_full'],
];
// Extra rows used only by the taller hero wall (same clips, reshuffled so neighbours differ).
const WALL_ROWS_HERO_EXTRA = [
  ['12_monday_compliance-game', '20_ai_zim-appreciation', '08_animation_cube-mascot', '22_ai_southwest-flight', '13_interactive_fire-hotspots', '03_appsflyer_hug-legpress'],
  ['24_ai_coach', '09_animation_classroom', '19_ai_drive-mode', '06_animation_headset-call', '11_signature_real-work', '01_appsflyer_ai-therapy'],
];

const WALL_FORMATS = ['3D animation', 'AI video', 'Gamification', 'Interactive eLearning', 'Live action', '2D animation', 'Campaigns'];

function VideoWall({ hero = false, sub = '', ctaPrimary = '', ctaSecondary = '' } = {}) {
  const rootRef = useRefWall(null);

  // Play only the clips that are on screen; pause the rest.
  useEffectWall(() => {
    const root = rootRef.current;
    if (!root || !('IntersectionObserver' in window)) return;
    const vids = Array.from(root.querySelectorAll('video'));
    vids.forEach((v) => { v.muted = true; v.defaultMuted = true; });
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        const v = e.target;
        if (e.isIntersecting) {
          if (v.preload === 'none') v.preload = 'auto';
          const p = v.play();
          if (p && p.catch) p.catch(() => {});
        } else {
          v.pause();
        }
      });
    }, { rootMargin: '120px' });
    vids.forEach((v) => io.observe(v));
    const onVis = () => { if (document.hidden) vids.forEach((v) => v.pause()); };

    // Cursor effects (hero only, mouse/trackpad only, never with reduced motion):
    // 1) the whole wall tilts toward the cursor, 2) tiles near the cursor swell in a soft wave.
    // The wave fades out over the headline and button so the message stays calm.
    const mq = (q) => window.matchMedia && window.matchMedia(q).matches;
    let stopCursor = () => {};
    if (hero && mq('(hover: hover) and (pointer: fine)') && !mq('(prefers-reduced-motion: reduce)')) {
      const tiles = Array.from(root.querySelectorAll('.kw-wall__tile'));
      const copy = root.querySelector('.kw-wall__copy');
      const RADIUS = 230;           // px, size of the wave
      const MAX_SCALE = 0.16;       // tile grows up to +16%
      const TILT_X = 4, TILT_Y = 6; // degrees
      let px = 0, py = 0, inside = false;
      let mx = 0, my = 0, tmx = 0, tmy = 0; // smoothed tilt
      let strength = 0, tStrength = 0;      // smoothed wave strength
      let raf = 0;
      const lastK = new Map();
      const calmRects = () => {
        const out = [];
        copy.querySelectorAll('.kw-wall__eyebrow, .kw-wall__title, .kw-wall__proof').forEach((el) => {
          const rg = document.createRange(); rg.selectNodeContents(el); out.push(rg.getBoundingClientRect());
        });
        copy.querySelectorAll('.kw-wall__btn').forEach((el) => out.push(el.getBoundingClientRect()));
        return out;
      };

      const frame = () => {
        raf = 0;
        mx += (tmx - mx) * 0.08; my += (tmy - my) * 0.08;
        strength += (tStrength - strength) * 0.12;
        root.style.setProperty('--kw-mx', mx.toFixed(4));
        root.style.setProperty('--kw-my', my.toFixed(4));

        // calm zone over the headline + button
        // measured on the actual words and button, not the full-width text box
        let calm = 1;
        if (copy && inside) {
          for (const c of calmRects()) {
            const dx = Math.max(c.left - px, 0, px - c.right);
            const dy = Math.max(c.top - py, 0, py - c.bottom);
            calm = Math.min(calm, Math.hypot(dx, dy) / 90);
          }
        }
        const amp = strength * calm;

        for (const t of tiles) {
          let k = 0;
          if (amp > 0.002) {
            const r = t.getBoundingClientRect();
            if (r.width) {
              const d = Math.hypot(r.left + r.width / 2 - px, r.top + r.height / 2 - py);
              k = amp * Math.exp(-(d * d) / (2 * RADIUS * RADIUS));
            }
          }
          const prev = lastK.get(t) || 0;
          if (Math.abs(k - prev) > 0.002 || (k === 0 && prev !== 0)) {
            lastK.set(t, k);
            if (k < 0.004) { t.style.transform = ''; t.style.zIndex = ''; t.style.boxShadow = ''; }
            else {
              t.style.transform = `translateY(${(-k * 10).toFixed(2)}px) scale(${(1 + k * MAX_SCALE).toFixed(4)})`;
              t.style.zIndex = String(Math.round(k * 10) + 1);
              t.style.boxShadow = `0 ${18 + k * 22}px ${40 + k * 30}px rgba(10, 4, 40, ${0.45 + k * 0.2})`;
            }
          }
        }
        const settling = Math.abs(tmx - mx) > 0.001 || Math.abs(tmy - my) > 0.001 || Math.abs(tStrength - strength) > 0.002;
        if (inside || settling) raf = requestAnimationFrame(frame);
      };
      const kick = () => { if (!raf) raf = requestAnimationFrame(frame); };

      const onMove = (e) => {
        const b = root.getBoundingClientRect();
        px = e.clientX; py = e.clientY; inside = true;
        tmx = ((px - b.left) / b.width - 0.5) * 2;   // -1..1
        tmy = ((py - b.top) / b.height - 0.5) * 2;   // -1..1
        tStrength = 1;
        kick();
      };
      const onLeave = () => { inside = false; tmx = 0; tmy = 0; tStrength = 0; kick(); };
      root.addEventListener('pointermove', onMove, { passive: true });
      root.addEventListener('pointerleave', onLeave, { passive: true });
      root.style.setProperty('--kw-tilt-x', TILT_X + 'deg');
      root.style.setProperty('--kw-tilt-y', TILT_Y + 'deg');
      stopCursor = () => {
        root.removeEventListener('pointermove', onMove);
        root.removeEventListener('pointerleave', onLeave);
        if (raf) cancelAnimationFrame(raf);
      };
    }
    document.addEventListener('visibilitychange', onVis);
    return () => { io.disconnect(); document.removeEventListener('visibilitychange', onVis); stopCursor(); };
  }, [hero]);

  return (
    <div className={'kw-wall' + (hero ? ' kw-wall--hero' : '')} ref={rootRef}>
      <div className="kw-wall__stage" aria-hidden="true">
        <div className="kw-wall__plane">
          {(hero ? [WALL_ROWS_HERO_EXTRA[0], ...WALL_ROWS, WALL_ROWS_HERO_EXTRA[1]] : WALL_ROWS).map((row, r) => (
            <div className={`kw-wall__row kw-wall__row--${(r % 4) + 1}` + (hero && r === 0 ? ' kw-wall__row--extra' : '')} key={r}>
              <div className="kw-wall__track">
                {[0, 1].map((copy) => (
                  <div className="kw-wall__set" key={copy}>
                    {row.map((name) => (
                      <div className="kw-wall__tile" key={name + copy}>
                        <video
                          src={`assets/wall/${name}.mp4`}
                          poster={`assets/wall/${name}.jpg`}
                          muted loop playsInline preload="none"
                          tabIndex={-1}
                        />
                      </div>
                    ))}
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="kw-wall__veil" aria-hidden="true" />

      <div className="kw-wall__copy">
        <p className="kw-wall__eyebrow">Knowaa is a</p>
        {hero
          ? <h1 className="kw-wall__title">Creative learning agency<span className="kw-wall__dot">.</span></h1>
          : <h2 className="kw-wall__title">Creative learning agency<span className="kw-wall__dot">.</span></h2>}
        {hero ? (
          <p className="kw-wall__proof">
            <span className="kw-wall__line kw-wall__line--one">that brings together learning experts and creative professionals to create</span>{' '}
            <span className="kw-wall__line"><strong>custom learning experiences</strong>.</span>
          </p>
        ) : (
          <ul className="kw-wall__formats" aria-label="Formats we produce">
            {WALL_FORMATS.map((f) => <li key={f}>{f}</li>)}
          </ul>
        )}
        {hero ? (
          <div className="kw-wall__ctas">
            {ctaPrimary ? (
              <a className="kw-wall__btn kw-wall__btn--primary" href="Knowaa Contact.html" data-cta="hero_primary">
                {ctaPrimary}
                <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M2 7 H12 M8 3 L12 7 L8 11" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </a>
            ) : null}
            {ctaSecondary ? (
              <a className="kw-wall__btn kw-wall__btn--ghost" href="Knowaa Resources.html?type=case" data-cta="hero_secondary">{ctaSecondary}</a>
            ) : null}
          </div>
        ) : null}
      </div>

      <style>{`
        .kw-wall {
          position: relative; z-index: 2;
          height: clamp(560px, 46vw, 760px);
          margin: -150px -24px 104px;
          overflow: hidden;
          isolation: isolate;
        }
        .kw-wall__stage {
          position: absolute; inset: 0;
          perspective: 1400px;
          perspective-origin: 50% 40%;
        }
        .kw-wall__plane {
          position: absolute;
          left: 50%; top: 50%;
          width: 150%;
          transform: translate(-50%, -50%) rotateX(18deg) rotateZ(-7deg) scale(1.08);
          transform-style: preserve-3d;
          display: flex; flex-direction: column; gap: 16px;
        }
        .kw-wall__row { overflow: visible; }
        .kw-wall__track { display: flex; width: max-content; will-change: transform; }
        .kw-wall__set { display: flex; gap: 16px; padding-right: 16px; }
        .kw-wall__row--1 .kw-wall__track { animation: kw-wall-left 95s linear infinite; }
        .kw-wall__row--2 .kw-wall__track { animation: kw-wall-right 115s linear infinite; }
        .kw-wall__row--3 .kw-wall__track { animation: kw-wall-left 105s linear infinite; }
        .kw-wall__row--4 .kw-wall__track { animation: kw-wall-right 125s linear infinite; }
        .kw-wall__row--2 .kw-wall__track, .kw-wall__row--4 .kw-wall__track { margin-left: -180px; }
        @keyframes kw-wall-left  { from { transform: translateX(0); }    to { transform: translateX(-50%); } }
        @keyframes kw-wall-right { from { transform: translateX(-50%); } to { transform: translateX(0); } }

        .kw-wall__tile {
          position: relative; flex: 0 0 auto;
          width: 320px; aspect-ratio: 16 / 9;
          border-radius: 14px; overflow: hidden;
          background: #2A1A66;
          box-shadow: 0 18px 40px rgba(10, 4, 40, 0.45);
        }
        .kw-wall__tile video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; display: block; }

        /* Purple veil: blends the wall into the section and lifts the headline. */
        .kw-wall__veil {
          position: absolute; inset: 0; pointer-events: none;
          background:
            radial-gradient(ellipse 46% 40% at 50% 54%, rgba(38, 18, 96, 0.92) 0%, rgba(38, 18, 96, 0.70) 45%, rgba(38, 18, 96, 0) 100%),
            linear-gradient(180deg, rgba(80, 53, 148, 0.85) 0%, rgba(80, 53, 148, 0) 22%, rgba(80, 53, 148, 0) 72%, #503594 100%),
            linear-gradient(90deg, rgba(80, 53, 148, 0.9) 0%, rgba(80, 53, 148, 0) 14%, rgba(80, 53, 148, 0) 86%, rgba(80, 53, 148, 0.9) 100%),
            rgba(52, 28, 120, 0.22);
        }

        .kw-wall__copy {
          position: absolute; left: 50%; top: 54%;
          transform: translate(-50%, -50%);
          width: min(92%, 1100px);
          text-align: center; color: #FFFFFF;
          pointer-events: none;
        }
        .kw-wall__eyebrow {
          margin: 0 0 14px;
          font-family: 'Poppins', sans-serif;
          font-size: 13px; font-weight: 700;
          letter-spacing: 0.28em; text-transform: uppercase;
          color: rgba(255, 255, 255, 0.85);
        }
        .kw-wall__title {
          margin: 0;
          font-family: 'Poppins', sans-serif;
          font-weight: 900;
          font-size: clamp(40px, 5.6vw, 92px);
          line-height: 1;
          white-space: nowrap;
          letter-spacing: -0.035em;
          color: #FFFFFF;
          text-shadow: 0 2px 4px rgba(20, 6, 70, 0.35), 0 8px 48px rgba(20, 6, 70, 0.6);
        }
        .kw-wall__dot { color: #ED1F80; }
        .kw-wall__formats {
          list-style: none; padding: 0; margin: 26px auto 0;
          display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;
          max-width: 860px;
        }
        .kw-wall__formats li {
          font-family: 'Poppins', sans-serif;
          font-size: 13px; font-weight: 600; letter-spacing: 0.01em;
          color: #FFFFFF;
          padding: 8px 16px;
          border-radius: 999px;
          background: rgba(255, 255, 255, 0.12);
          border: 1px solid rgba(255, 255, 255, 0.28);
          -webkit-backdrop-filter: blur(8px);
                  backdrop-filter: blur(8px);
        }

        /* Hero variant: the wall is the page header. */
        .kw-wall--hero {
          height: clamp(680px, 86vh, 960px);
          margin: 0;
          background: #503594 !important;
        }
        .kw-wall--hero .kw-wall__plane {
          transform: translate(-50%, -50%)
            rotateX(calc(18deg - var(--kw-my, 0) * var(--kw-tilt-x, 0deg)))
            rotateY(calc(var(--kw-mx, 0) * var(--kw-tilt-y, 0deg)))
            rotateZ(-7deg) scale(1.14);
        }
        .kw-wall--hero .kw-wall__tile { will-change: transform; }
        .kw-wall--hero .kw-wall__copy { top: 55%; }
        .kw-wall--hero .kw-wall__veil {
          background:
            radial-gradient(ellipse 52% 46% at 50% 55%, rgba(34, 14, 92, 0.94) 0%, rgba(38, 18, 96, 0.80) 45%, rgba(38, 18, 96, 0) 100%),
            linear-gradient(180deg, rgba(80, 53, 148, 0.85) 0%, rgba(80, 53, 148, 0) 22%, rgba(80, 53, 148, 0) 72%, #503594 100%),
            linear-gradient(90deg, rgba(80, 53, 148, 0.9) 0%, rgba(80, 53, 148, 0) 14%, rgba(80, 53, 148, 0) 86%, rgba(80, 53, 148, 0.9) 100%),
            rgba(52, 28, 120, 0.30);
        }
        .kw-wall__proof {
          margin: 20px auto 0;
          max-width: none;
          text-wrap: balance;
          text-shadow: 0 1px 2px rgba(20, 6, 70, 0.5), 0 4px 24px rgba(20, 6, 70, 0.65);
          font-family: 'Poppins', sans-serif;
          font-size: clamp(14px, 2.1vw, 24px);
          font-weight: 500;
          line-height: 1.4;
          letter-spacing: -0.005em;
          color: rgba(255, 255, 255, 0.92);
        }
        .kw-wall__line { display: block; }
        .kw-wall__line--one { white-space: nowrap; }
        .kw-wall__proof strong { font-weight: 700; color: #FFFFFF; font-size: 1.15em; }
        .kw-wall__sub {
          margin: 22px auto 0;
          max-width: 640px;
          font-family: 'Poppins', sans-serif;
          font-size: clamp(15px, 1.25vw, 18px);
          line-height: 1.55;
          color: rgba(255, 255, 255, 0.88);
        }
        .kw-wall__ctas {
          margin-top: 30px;
          display: flex; flex-wrap: wrap; justify-content: center; gap: 14px;
          pointer-events: auto;
        }
        .kw-wall__btn {
          display: inline-flex; align-items: center; gap: 12px;
          padding: 17px 28px; border-radius: 999px;
          font-family: 'Poppins', sans-serif; font-size: 15px; font-weight: 600;
          text-decoration: none;
          transition: transform 0.25s ease, box-shadow 0.25s ease, background 0.25s ease;
        }
        .kw-wall__btn--primary { background: #FFFFFF; color: #0D0959; }
        .kw-wall__btn--primary:hover { transform: translateY(-2px); box-shadow: 0 14px 30px -10px rgba(0, 0, 0, 0.45); }
        .kw-wall__btn--ghost { color: #FFFFFF; border: 1px solid rgba(255, 255, 255, 0.55); background: rgba(255, 255, 255, 0.08); -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); }
        .kw-wall__btn--ghost:hover { background: rgba(255, 255, 255, 0.18); transform: translateY(-2px); }

        @media (prefers-reduced-motion: reduce) {
          .kw-wall__track { animation: none !important; }
        }
        @media (max-width: 960px) {
          .kw-wall { height: 520px; margin: -72px -20px 64px; }
          .kw-wall__plane { width: 220%; gap: 12px; transform: translate(-50%, -50%) rotateX(14deg) rotateZ(-6deg) scale(1); }
          .kw-wall__set { gap: 12px; padding-right: 12px; }
          .kw-wall__tile { width: 220px; border-radius: 10px; }
          .kw-wall__formats li { font-size: 12px; padding: 6px 12px; }
        }
        @media (max-width: 960px) {
          .kw-wall--hero { height: 82vh; min-height: 600px; max-height: 760px; margin: 0; }
          .kw-wall__row--extra { display: none; }
        }
        @media (max-width: 640px) {
          .kw-wall { height: 460px; margin: -56px -20px 56px; }
          .kw-wall--hero { height: 86vh; min-height: 600px; max-height: 760px; margin: 0; }
          .kw-wall__sub { font-size: 14px; }
          .kw-wall__line:not(:last-child) { display: inline; }
          .kw-wall__line--one { white-space: normal; }
          .kw-wall__title { white-space: normal; text-wrap: balance; }
          .kw-wall__proof { max-width: 340px; font-size: 15px; }
          .kw-wall__formats li:nth-child(n+5) { display: none; }
          .kw-wall__btn { padding: 15px 22px; font-size: 14px; }
          .kw-wall__tile { width: 180px; }
          .kw-wall__eyebrow { font-size: 11px; }
          .kw-wall__formats { gap: 8px; }
        }
      `}</style>
    </div>
  );
}

window.VideoWall = VideoWall;
