/* Hero — ported from src/components/Hero.jsx */
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH, useCallback: useCallbackH } = React;
const { motion: motionH, AnimatePresence: AnimatePresenceH, useReducedMotion } = window.Motion;

const HBLUE = '#02528A';

const SLIDES = [
  { room: 'images/room2-blue.jpg', roomMobile: 'images/room2-blue-mobile.jpg', img: 'images/slide-pencil-pen-trim-sm.png', tag: 'Pencils & Pens',  rgb: [2, 82, 138],   link: 'products.html#cat/pens-writing-instruments' },
  { room: 'images/room2-gold.jpg', roomMobile: 'images/room2-gold-mobile.jpg', img: 'images/slide-design-trim-sm.png',     tag: 'Art & Design',    rgb: [253, 195, 39], link: 'products.html#cat/drawing-colouring' },
  { room: 'images/room2-red.jpg',  roomMobile: 'images/room2-red-mobile.jpg',  img: 'images/slide-range-trim-sm.png',      tag: 'Full Collection', rgb: [232, 25, 44],  link: 'products.html#all' },
];

const LINE1 = ['Every', 'Ambition'];
const LINE2 = ['Needs', 'Preparation'];
const EASE  = [0.22, 1, 0.36, 1];
const SPR   = { type: 'spring', stiffness: 300, damping: 26 };
const rgba  = (rgb, a) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${a})`;

/* Room image is 2752x1536 (16:9). Niche box centred at 50%. Floor line ~74%.
   Product images are content-trimmed, so 50% centring is visually exact. */
const ROOM_RATIO = '2752 / 1536';
const ROOM_RATIO_M = '1 / 1';     // mobile room — square, top-cropped so empty floor is trimmed & it fits the screen
const NICHE = { cx: 50, w: 68 };  // product width, % of stage
const NICHE_M = { cx: 50, w: 92 }; // mobile product width — big, fills the niche
const FLOOR = 77;                 // product base sits on the floor line (% of stage)
const FLOOR_M = 62;               // mobile floor line within the full-height room

function WordLine({ words, lineDelay, exiting }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', gap: '0 0.26em' }}>
      {words.map((w, i) => (
        <motionH.span
          key={w}
          initial={{ y: '0.5em', opacity: 0 }}
          animate={exiting
            ? { y: '-0.4em', opacity: 0, transition: { duration: 0.22, delay: i * 0.04, ease: [0.4,0,1,1] } }
            : { y: 0,       opacity: 1, transition: { duration: 0.55, delay: lineDelay + i * 0.1, ease: EASE } }
          }
          style={{
            display: 'inline-block',
            fontFamily: "'Barlow Condensed', sans-serif",
            fontSize: 'clamp(44px, 12vw, 64px)',
            fontWeight: 800, color: '#fff', letterSpacing: '-0.4px', lineHeight: 1.1,
            textShadow: '0 2px 26px rgba(0,0,0,0.40), 0 1px 3px rgba(0,0,0,0.28)',
          }}
        >
          {w}
        </motionH.span>
      ))}
    </div>
  );
}

function Hero() {
  const prefersReduced = useReducedMotion();
  const [cur,     setCur    ] = useStateH(0);
  const [exiting, setExiting] = useStateH(false);
  const busy   = useRefH(false);
  const paused = useRefH(false);
  const [isMobile, setIsMobile] = useStateH(typeof window !== 'undefined' && window.innerWidth <= 768);

  useEffectH(() => {
    const onR = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);

  const goTo = useCallbackH((n) => {
    if (busy.current || n === cur) return;
    busy.current = true;
    if (prefersReduced) { setCur(n); busy.current = false; return; }
    setExiting(true);
    setTimeout(() => {
      setCur(n); setExiting(false);
      setTimeout(() => { busy.current = false; }, 900);
    }, 300);
  }, [cur, prefersReduced]);

  // stable refs so the single auto-advance interval always sees the latest values
  const curRef  = useRefH(0);  curRef.current  = cur;
  const goToRef = useRefH(goTo); goToRef.current = goTo;

  useEffectH(() => {
    const id = setInterval(() => {
      if (!paused.current && !busy.current) goToRef.current((curRef.current + 1) % SLIDES.length);
    }, 4000);  // 4s between slides
    return () => clearInterval(id);
  }, []);

  const s = SLIDES[cur];

  /* broadcast the active room colour so the nav can invert itself over the hero */
  useEffectH(() => {
    const r = SLIDES[cur].rgb;
    const lum = 0.299 * r[0] + 0.587 * r[1] + 0.114 * r[2];
    window.dispatchEvent(new CustomEvent('doms-hero-color', { detail: { rgb: r, light: lum > 140 } }));
  }, [cur]);

  return (
    <section
      style={{
        width: '100%', position: 'relative', userSelect: 'none', overflow: 'hidden',
        height: isMobile ? '100svh' : '100vh', minHeight: isMobile ? 600 : 560,
      }}
      onMouseEnter={() => { paused.current = true;  }}
      onMouseLeave={() => { paused.current = false; }}
    >
      <div style={isMobile ? {
        position: 'absolute', inset: 0, width: '100%', height: '100%', zIndex: 0,
      } : {
        position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
        aspectRatio: ROOM_RATIO, minWidth: '100%', minHeight: '100%', zIndex: 0,
      }}>
        <AnimatePresenceH>
          <motionH.img
            key={`room-${cur}`}
            src={isMobile ? s.roomMobile : s.room} alt="DOMS display room" aria-hidden="true" decoding="async"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.9, ease: 'easeInOut' }}
            style={{
              position: 'absolute', inset: 0,
              width: '100%', height: '100%',
              objectFit: 'cover', objectPosition: isMobile ? 'center top' : 'center',
              zIndex: 0,
            }}
          />
        </AnimatePresenceH>

        {/* product + floor reflection — bottom-anchored to the box floor, slides in */}
        <div style={{
          position: 'absolute', left: `${(isMobile ? NICHE_M : NICHE).cx}%`, bottom: `${100 - (isMobile ? FLOOR_M : FLOOR)}%`,
          transform: 'translateX(-50%)', width: `${(isMobile ? NICHE_M : NICHE).w}%`,
          maxWidth: isMobile ? '96vw' : 'none',
          zIndex: 41, pointerEvents: 'none',
        }}>
          <motionH.div
            key={`prod-${cur}`}
            initial={{ opacity: 0, x: 230 }}
            animate={exiting
              ? { opacity: 0, x: -230, transition: { duration: 0.28, ease: [0.4, 0, 1, 1] } }
              : { opacity: 1, x: 0,    transition: { duration: 0.55, ease: EASE } }
            }
            style={{ width: '100%', position: 'relative' }}
          >
            {/* floor contact shadow — pools on the floor just below the products so they read as grounded */}
            <motionH.div
              animate={{ scaleX: [1, 0.92, 1], opacity: [0.6, 0.42, 0.6] }}
              transition={{ duration: 4.4, repeat: Infinity, ease: 'easeInOut', repeatDelay: 0.4 }}
              style={{
                position: 'absolute', left: '50%', bottom: -22, x: '-50%',
                width: '88%', height: 60, borderRadius: '50%', transformOrigin: 'center',
                background: 'radial-gradient(ellipse at center, rgba(1,12,28,0.62) 0%, rgba(1,12,28,0.34) 38%, rgba(1,12,28,0.12) 60%, transparent 74%)',
                filter: 'blur(13px)', zIndex: 0, pointerEvents: 'none',
              }}
            />
            <motionH.div
              animate={{ y: [0, -9, 0] }}
              transition={{ duration: 4.4, repeat: Infinity, ease: 'easeInOut', repeatDelay: 0.4 }}
              style={{ width: '100%', position: 'relative', zIndex: 1 }}
            >
              <img
                src={s.img} alt="DOMS Products" decoding="async"
                style={{
                  width: '100%', height: 'auto', display: 'block',
                  maxHeight: isMobile ? '44vh' : '47vh', objectFit: 'contain', marginInline: 'auto',
                  filter: 'drop-shadow(0 14px 22px rgba(0,0,0,0.3))',
                }}
              />
            </motionH.div>
          </motionH.div>
        </div>
      </div>

      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, zIndex: 6,
        paddingTop: isMobile ? 150 : 'clamp(124px, 14vh, 160px)',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        pointerEvents: 'none',
      }}>
        <motionH.a
          key={`tag-${cur}`}
          href={s.link}
          initial={{ opacity: 0, y: 14 }}
          animate={exiting
            ? { opacity: 0, y: -10, transition: { duration: 0.18 } }
            : { opacity: 1, y: 0,   transition: { duration: 0.5, delay: 0.05, ease: EASE } }
          }
          whileHover={{ y: -2, boxShadow: '0 10px 26px rgba(0,0,0,0.22)' }}
          whileTap={{ scale: 0.96 }}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer', textDecoration: 'none',
            padding: '6px 12px 6px 12px', borderRadius: 40, marginBottom: 12,
            background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(10px)',
            border: '1.5px solid rgba(255,255,255,0.6)',
            boxShadow: '0 4px 14px rgba(0,0,0,0.12)', pointerEvents: 'auto',
          }}
        >
          <motionH.span
            animate={{ scale: [1, 1.35, 1], opacity: [0.8, 1, 0.8] }}
            transition={{ duration: 2, repeat: Infinity, ease: 'easeInOut' }}
            style={{
              width: 8, height: 8, borderRadius: '50%', background: rgba(s.rgb, 1),
              display: 'inline-block', boxShadow: `0 0 0 3px ${rgba(s.rgb, 0.28)}`,
            }}
          />
          <span style={{
            fontFamily: "'Barlow Condensed', sans-serif",
            fontSize: 11, fontWeight: 700,
            color: HBLUE, letterSpacing: '2px', textTransform: 'uppercase',
          }}>
            {s.tag}
          </span>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={HBLUE} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 1 }}><path d="M5 12h14M13 6l6 6-6 6"/></svg>
        </motionH.a>

        <div style={{ textAlign: 'center' }}>
          <WordLine key={`l1-${cur}`} words={LINE1} lineDelay={0.1}  exiting={exiting} />
          <WordLine key={`l2-${cur}`} words={LINE2} lineDelay={0.22} exiting={exiting} />
        </div>
      </div>

      <div style={{
        position: 'absolute', bottom: 22, left: 0, right: 0,
        zIndex: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      }}>
        {SLIDES.map((sl, i) => (
          <motionH.button
            key={i}
            onClick={() => goTo(i)}
            animate={{
              width:      i === cur ? 30 : 8,
              background: i === cur ? '#fff' : 'rgba(255,255,255,0.4)',
              boxShadow:  i === cur ? '0 0 0 3px rgba(255,255,255,0.25)' : 'none',
            }}
            transition={SPR}
            style={{ height: 8, borderRadius: 4, border: 'none', cursor: 'pointer', padding: 0, flexShrink: 0 }}
            aria-label={`Slide ${i + 1}`}
          />
        ))}
        <span style={{
          fontFamily: "'Barlow Condensed', sans-serif",
          fontSize: 12, fontWeight: 600, letterSpacing: '1.2px',
          color: 'rgba(255,255,255,0.75)', marginLeft: 8,
        }}>
          {String(cur + 1).padStart(2, '0')} / {String(SLIDES.length).padStart(2, '0')}
        </span>
      </div>

      {[-1, 1].map(dir => (
        <motionH.button
          key={dir}
          onClick={() => goTo((cur + dir + SLIDES.length) % SLIDES.length)}
          whileHover={{ scale: 1.1, background: 'rgba(255,255,255,0.9)' }}
          whileTap={{ scale: 0.88 }}
          style={{
            position: 'absolute', top: '50%',
            ...(dir === -1 ? { left: 26 } : { right: 26 }),
            transform: 'translateY(-50%)',
            width: 46, height: 46, borderRadius: '50%',
            background: 'rgba(255,255,255,0.75)',
            backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
            border: '1px solid rgba(2,82,138,0.16)',
            color: HBLUE, fontSize: 26, fontWeight: 400,
            cursor: 'pointer', zIndex: 14,
            display: 'flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1,
          }}
          aria-label={dir === -1 ? 'Previous' : 'Next'}
        >
          {dir === -1 ? '‹' : '›'}
        </motionH.button>
      ))}
    </section>
  );
}

window.Hero = Hero;
