const HERO_BOOKING_URL = 'https://www.fresha.com/a/hayre-grooming-salon-abu-dhabi-hayre-grooming-salon-united-square-gwywnytl/booking';
const HERO_WHATSAPP_URL = 'https://wa.me/971563690151?text=Hi%20HAYRE%2C%20I%27d%20like%20to%20book%20an%20appointment.';
const HERO_IMAGE = {
  src: 'assets/hero/hayre-signature.webp',
  mobileSrc: 'assets/hero/hayre-signature-mobile.webp',
  alt: 'Three illuminated barber stations and signature gold chairs at HAYRE',
};
const HERO_SIGNATURE_VIDEO = {
  mp4: 'assets/hero/confidence-signature.mp4',
  webm: 'assets/hero/confidence-signature.webm',
};

const HeroSignatureVideo = ({ instanceKey, onError }) => {
  const videoRef = React.useRef(null);
  const canvasRef = React.useRef(null);
  const [state, setState] = React.useState('waiting');
  const [prefersReducedMotion, setPrefersReducedMotion] = React.useState(false);

  React.useEffect(() => {
    const motionPreference = window.matchMedia('(prefers-reduced-motion: reduce)');
    const applyPreference = (matches) => {
      setPrefersReducedMotion(matches);
    };

    applyPreference(motionPreference.matches);
    const handleChange = (event) => applyPreference(event.matches);
    motionPreference.addEventListener?.('change', handleChange);
    return () => {
      motionPreference.removeEventListener?.('change', handleChange);
    };
  }, []);

  React.useEffect(() => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (!video || !canvas) return undefined;
    const context = canvas.getContext('2d', { alpha: true, willReadFrequently: true });
    if (!context) {
      onError?.();
      return undefined;
    }

    let cancelled = false;
    let rafId = 0;

    const keyFrame = () => {
      if (!video.videoWidth || !video.videoHeight) return;
      if (canvas.width !== video.videoWidth || canvas.height !== video.videoHeight) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
      }

      context.clearRect(0, 0, canvas.width, canvas.height);
      context.drawImage(video, 0, 0, canvas.width, canvas.height);

      const frame = context.getImageData(0, 0, canvas.width, canvas.height);
      const { data } = frame;

      for (let index = 0; index < data.length; index += 4) {
        const r = data[index];
        const g = data[index + 1];
        const b = data[index + 2];
        const peak = Math.max(r, g, b);

        if (peak <= 10) {
          data[index + 3] = 0;
          continue;
        }

        if (peak < 64) {
          const alpha = Math.pow((peak - 10) / 54, 1.45) * 255;
          data[index + 3] = Math.max(0, Math.min(255, Math.round(alpha)));
        } else {
          data[index + 3] = 255;
        }
      }

      context.putImageData(frame, 0, 0);
    };

    const stopLoop = () => {
      window.cancelAnimationFrame(rafId);
    };

    const renderLoop = () => {
      if (cancelled) return;
      keyFrame();
      if (!video.paused && !video.ended) {
        rafId = window.requestAnimationFrame(renderLoop);
      }
    };

    const holdFinalFrame = () => {
      if (!video.duration || !Number.isFinite(video.duration)) return;
      try {
        video.currentTime = Math.max(video.duration - 0.05, 0);
      } catch (error) {
        // Safari can reject seeking before metadata settles; ignore and keep poster/final frame.
      }
    };

    const syncPlayback = () => {
      if (cancelled) return;
      stopLoop();
      video.pause();
      video.currentTime = 0;

      if (prefersReducedMotion) {
        holdFinalFrame();
        return;
      }

      setState('ready');
      const playPromise = video.play();
      if (playPromise && typeof playPromise.catch === 'function') {
        playPromise
          .then(() => {
            if (!cancelled) {
              setState('playing');
              renderLoop();
            }
          })
          .catch(() => {
            if (!cancelled) onError?.();
          });
      }
    };

    const handleLoadedMetadata = () => syncPlayback();
    const handleSeeked = () => {
      keyFrame();
      if (prefersReducedMotion || video.ended) {
        setState('complete');
      }
    };
    const handleEnded = () => {
      stopLoop();
      keyFrame();
      holdFinalFrame();
      setState('complete');
    };

    video.addEventListener('loadedmetadata', handleLoadedMetadata);
    video.addEventListener('seeked', handleSeeked);
    video.addEventListener('ended', handleEnded);

    if (video.readyState >= 1) {
      syncPlayback();
    }

    return () => {
      cancelled = true;
      stopLoop();
      video.pause();
      video.removeEventListener('loadedmetadata', handleLoadedMetadata);
      video.removeEventListener('seeked', handleSeeked);
      video.removeEventListener('ended', handleEnded);
    };
  }, [instanceKey, onError, prefersReducedMotion]);

  return (
    <span
      className={`hero-signature-video-shell hero-signature-video-shell-${state}`}
      data-signature-state={state}
    >
      <canvas className="hero-signature-canvas" ref={canvasRef} aria-hidden="true" />
      <video
        ref={videoRef}
        className="hero-signature-video-source"
        aria-hidden="true"
        muted
        playsInline
        preload="auto"
        onError={() => onError?.()}
      >
        <source src={HERO_SIGNATURE_VIDEO.webm} type="video/webm" />
        <source src={HERO_SIGNATURE_VIDEO.mp4} type="video/mp4" />
      </video>
    </span>
  );
};

const Hero = () => {
  return (
    <section
      className="hero"
      id="home"
      data-screen-label="01 Hero"
      aria-label="HAYRE introduction"
    >
      <div className="hero-media" aria-live="off">
        <picture className="hero-slide is-active">
          <source media="(max-width: 700px)" srcSet={HERO_IMAGE.mobileSrc} />
          <img
            src={HERO_IMAGE.src}
            alt={HERO_IMAGE.alt}
            loading="eager"
            fetchPriority="high"
            decoding="async"
          />
        </picture>
        <div className="hero-scrim" aria-hidden="true"></div>
        <div className="hero-grain" aria-hidden="true"></div>
      </div>

      <div className="hero-copy">
        <p className="hero-eyebrow fadein">United Square Mall · Abu Dhabi</p>
        <span className="hero-logo-anchor" aria-hidden="true"></span>
        <h1 className="hero-title fadein d1">
          <span className="hero-title-static">Crafting</span>
          <span className="sr-only"> Confidence.</span>
          <span className="hero-signature" aria-hidden="true">
            <HeroSignatureVideo instanceKey="hero" />
          </span>
        </h1>
        <p className="hero-sub fadein d2">
          Specialist men's grooming, shaped around the way you look, live, and carry yourself.
        </p>
        <div className="hero-actions fadein d3">
          <a
            href={HERO_BOOKING_URL}
            target="_blank"
            rel="noopener noreferrer"
            className="hero-cta"
          >
            <span>Book appointment</span>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden="true">
              <path d="M5 12h14M13 6l6 6-6 6" />
            </svg>
          </a>
          <a
            href={HERO_WHATSAPP_URL}
            target="_blank"
            rel="noopener noreferrer"
            className="hero-secondary-link"
          >
            Prefer to speak first? Chat on WhatsApp
          </a>
        </div>
      </div>

      <div className="hero-rail hero-rail-single">
        <a className="hero-scroll" href="#experience">
          <span>Discover HAYRE</span>
          <span className="hero-scroll-line" aria-hidden="true"></span>
        </a>
      </div>
    </section>
  );
};

window.Hero = Hero;
