/* SalesLetter — full-width video section directly below the hero. */
const { useRef: useRefSL, useEffect: useEffectSL, useState: useStateSL } = React;

function SalesLetter({ src, title }) {
  const ref = useRefSL(null);
  const [unmuted, setUnmuted] = useStateSL(false);

  // Auto-pause when scrolled out of view, auto-play (muted) when in view
  useEffectSL(() => {
    if (!ref.current) return;
    const v = ref.current;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          if (v.paused) v.play().catch(() => {});
        } else {
          if (!v.paused) v.pause();
        }
      });
    }, { threshold: 0.25 });
    io.observe(v);
    return () => io.disconnect();
  }, []);

  const handleClickPlay = () => {
    const v = ref.current;
    if (!v) return;
    v.muted = false;
    v.currentTime = 0;
    v.play().catch(() => {});
    setUnmuted(true);
  };

  return (
    <section id="message" className="sales-letter">
      <div className="sales-letter-inner">
        <div className="sales-letter-eyebrow">A MESSAGE FROM ELEVATE</div>
        <h2 className="sales-letter-title">{title || 'Why Tampa Bay sellers trust us.'}</h2>
        <div className={`sales-letter-frame ${unmuted ? 'is-playing' : ''}`}>
          <video
            ref={ref}
            src={src}
            controls={unmuted}
            playsInline
            muted
            autoPlay
            loop={!unmuted}
            preload="metadata"
          />
          {!unmuted && (
            <button
              className="sales-letter-play"
              onClick={handleClickPlay}
              aria-label="Play with sound from beginning"
              type="button"
            >
              <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
                <path d="M10 6L25 16L10 26V6Z" fill="currentColor"/>
              </svg>
              <span className="sales-letter-play-label">Tap to play with sound</span>
            </button>
          )}
        </div>
      </div>
    </section>
  );
}

window.SalesLetter = SalesLetter;
