// Hero with video background, scroll fade-ins, and tilt interactions
const { useEffect, useRef, useState, useMemo } = React;

const EVENT_DATE = new Date('2026-08-18T08:00:00-04:00');

function useCountdown(target) {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, target - now);
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor((diff % 86400000) / 3600000);
  const mins = Math.floor((diff % 3600000) / 60000);
  const secs = Math.floor((diff % 60000) / 1000);
  return { days, hours, mins, secs };
}

// Hook: in-view trigger for scroll reveals
function useInView(opts = { threshold: 0.15, once: true }) {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setInView(true);
        if (opts.once) obs.disconnect();
      } else if (!opts.once) {
        setInView(false);
      }
    }, { threshold: opts.threshold || 0.15, rootMargin: opts.rootMargin || '0px 0px -60px 0px' });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return [ref, inView];
}

// RevealText: splits a string into words and fades each in with stagger when in view.
// Children should be a string. For mixed inline content use Reveal.
function RevealText({ children, delay = 0, stagger = 0.05, y = 14, as: Tag = 'span', className = '', style = {} }) {
  const [ref, inView] = useInView();
  const words = (typeof children === 'string' ? children : '').split(/(\s+)/);
  return (
    <Tag ref={ref} className={className} style={{ ...style, display: 'inline' }}>
      {words.map((w, i) => {
        if (/^\s+$/.test(w)) return w;
        const d = delay + (i * stagger) / 2;
        return (
          <span key={i} style={{
            display: 'inline-block',
            opacity: inView ? 1 : 0,
            transform: inView ? 'translate3d(0,0,0)' : `translate3d(0, ${y}px, 0)`,
            transition: `opacity 0.7s cubic-bezier(0.2,0.7,0.2,1) ${d}s, transform 0.8s cubic-bezier(0.2,0.7,0.2,1) ${d}s`,
            willChange: 'opacity, transform',
          }}>{w}</span>
        );
      })}
    </Tag>
  );
}

// Reveal wrapper — fades & slides up when scrolled into view
function Reveal({ children, delay = 0, y = 24, as: Tag = 'div', className = '', style = {} }) {
  const [ref, inView] = useInView();
  return (
    <Tag
      ref={ref}
      className={className}
      style={{
        ...style,
        opacity: inView ? 1 : 0,
        transform: inView ? 'translate3d(0,0,0)' : `translate3d(0, ${y}px, 0)`,
        transition: `opacity 1s cubic-bezier(0.2,0.7,0.2,1) ${delay}s, transform 1.1s cubic-bezier(0.2,0.7,0.2,1) ${delay}s`,
        willChange: 'opacity, transform',
      }}
    >
      {children}
    </Tag>
  );
}

// Tilt wrapper — interactive 3D mouse-follow tilt
function Tilt({ children, max = 8, scale = 1.01, className = '', style = {} }) {
  const ref = useRef(null);
  const [t, setT] = useState({ rx: 0, ry: 0, on: false });
  return (
    <div
      ref={ref}
      className={className}
      onMouseMove={(e) => {
        const r = ref.current.getBoundingClientRect();
        const x = (e.clientX - r.left) / r.width - 0.5;
        const y = (e.clientY - r.top) / r.height - 0.5;
        setT({ rx: -y * max, ry: x * max, on: true });
      }}
      onMouseLeave={() => setT({ rx: 0, ry: 0, on: false })}
      style={{
        ...style,
        transformStyle: 'preserve-3d',
        transform: `perspective(1200px) rotateX(${t.rx}deg) rotateY(${t.ry}deg) scale(${t.on ? scale : 1})`,
        transition: t.on ? 'transform 0.1s linear' : 'transform 0.5s cubic-bezier(0.2,0.7,0.2,1)',
      }}
    >
      {children}
    </div>
  );
}

function HeroMetaRow() {
  return (
    <div className="hero-meta-row">
      <span>August 18, 2026</span>
      <span className="dot"></span>
      <span>Royal Ashburn Golf Club</span>
      <span className="dot"></span>
      <span>Whitby, Ontario</span>
    </div>
  );
}

function HeroTitle({ animate }) {
  const words = ["The", "Estate", "Planning", "Summit", "&", <em key="g">Golf Social</em>];
  if (!animate) {
    return (
      <h1 className="hero-title">
        The Estate Planning Summit & <em>Golf Social</em>
      </h1>
    );
  }
  return (
    <h1 className="hero-title">
      {words.map((w, i) => (
        <React.Fragment key={i}>
          <span className="word" style={{ animationDelay: `${0.1 + i * 0.08}s` }}>{w}</span>
          {i < words.length - 1 && ' '}
        </React.Fragment>
      ))}
    </h1>
  );
}

function CollabRow() {
  const partners = ['Tamil Bar Association', 'Tamils in Finance', 'Tamil Golfers Association', 'Wealth Bridge Advisory'];
  // duplicate for seamless loop
  const loop = [...partners, ...partners, ...partners];
  return (
    <div className="hero-collab">
      <div className="hero-collab-label">In collaboration with</div>
      <div className="collab-marquee">
        <div className="collab-track">
          {loop.map((p, i) => (
            <div className="collab-item" key={i}>{p}</div>
          ))}
        </div>
      </div>
    </div>
  );
}

function CountdownStrip() {
  const { days, hours, mins, secs } = useCountdown(EVENT_DATE);
  const cells = [
    { n: days, l: 'Days' },
    { n: hours, l: 'Hours' },
    { n: mins, l: 'Minutes' },
    { n: String(secs).padStart(2, '0'), l: 'Seconds' },
  ];
  return (
    <div className="countdown">
      {cells.map((c) => (
        <div className="countdown-cell" key={c.l}>
          <div className="countdown-num">{c.n}</div>
          <div className="countdown-label">{c.l}</div>
        </div>
      ))}
    </div>
  );
}

// Scroll-driven hero parallax: video subtly zooms/dims as you scroll
function HeroVideo() {
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const max = window.innerHeight * 0.9;
      setProgress(Math.min(1, window.scrollY / max));
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <div className="hero-video-wrap" style={{ transform: `scale(${1 + progress * 0.06})` }}>
      <video
        className="hero-video"
        autoPlay muted loop playsInline preload="auto"
        poster="assets/clubhouse.webp"
      >
        <source src="assets/hero-video.mp4" type="video/mp4" />
      </video>
      <div className="hero-video-veil" style={{ opacity: 0.55 + progress * 0.25 }}></div>
    </div>
  );
}

function Hero({ tweaks, onRsvpScroll, rsvpCard }) {
  return (
    <section className="hero hero-cinematic" id="top">
      <HeroVideo />
      <div className="hero-inner">
        <div>
          <Reveal delay={0.1}><HeroMetaRow /></Reveal>
          <Reveal delay={0.2} y={36}>
            <h1 className="hero-title">
              The Estate Planning Summit & <em>Golf Social</em>
            </h1>
          </Reveal>
          <Reveal delay={0.5}>
            <p className="hero-sub">
              A curated day of education, golf, and meaningful relationship building for business owners and the professionals who advise them.
            </p>
          </Reveal>
          <Reveal delay={0.65}>
            <div className="hero-cta-row">
              <a href="#rsvp-anchor" className="hero-cta-primary" onClick={(e) => { e.preventDefault(); onRsvpScroll && onRsvpScroll(); }}>
                Reserve your seat <span className="arrow">→</span>
              </a>
              <a href="#sponsors" className="hero-cta-secondary">Sponsorship opportunities</a>
            </div>
          </Reveal>
        </div>
        <Reveal delay={0.35} y={48}>
          <Tilt max={4} scale={1.005}>
            {rsvpCard}
          </Tilt>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, CountdownStrip, EVENT_DATE, useCountdown, useInView, Reveal, RevealText, Tilt });
