// home.jsx — Homepage view (AR Homes-inspired, real photos)

const { useEffect, useRef, useState } = React;

function HeroVideo() {
  const videoARef = useRef(null);
  const videoBRef = useRef(null);
  const heroRef = useRef(null);
  // topIsA: which video has higher z-index (the one we see)
  // aFading / bFading: when true, that video fades from 1 -> 0
  const [topIsA, setTopIsA] = useState(true);
  const [aFading, setAFading] = useState(false);
  const [bFading, setBFading] = useState(false);

  useEffect(() => {
    const a = videoARef.current;
    const b = videoBRef.current;
    const hero = heroRef.current;
    if (!a || !b || !hero) return;

    const RATE = 0.5;          // slow ambient playback
    const FADE_SEC = 1.5;      // fade length

    a.playbackRate = b.playbackRate = RATE;
    a.play().catch(() => {});

    let activeRef = a;
    let standbyRef = b;
    let aIsActive = true;
    let transitioning = false;

    const onTime = () => {
      if (transitioning || !activeRef.duration) return;
      const remaining = (activeRef.duration - activeRef.currentTime) / RATE;
      if (remaining <= FADE_SEC) {
        transitioning = true;
        // start the standby copy from 0 — it sits underneath at full opacity
        standbyRef.currentTime = 0;
        standbyRef.play().catch(() => {});
        // fade out the active (top) video — reveals standby underneath
        if (aIsActive) setAFading(true);
        else setBFading(true);

        setTimeout(() => {
          // swap which is on top
          aIsActive = !aIsActive;
          setTopIsA(aIsActive);
          // reset the now-hidden video's opacity (it's behind the new top now)
          setAFading(false);
          setBFading(false);
          // swap refs for next cycle
          const swap = activeRef;
          activeRef = standbyRef;
          standbyRef = swap;
          transitioning = false;
        }, FADE_SEC * 1000 + 50);
      }
    };

    a.addEventListener('timeupdate', onTime);
    b.addEventListener('timeupdate', onTime);

    // Pause both when hero is fully off-screen
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.intersectionRatio > 0) {
            activeRef.play().catch(() => {});
          } else {
            a.pause();
            b.pause();
          }
        });
      },
      { threshold: [0, 0.01] }
    );
    io.observe(hero);

    return () => {
      io.disconnect();
      a.removeEventListener('timeupdate', onTime);
      b.removeEventListener('timeupdate', onTime);
    };
  }, []);

  return (
    <section className="hero" ref={heroRef}>
      <div className="hero__placeholder" />
      <video
        ref={videoARef}
        className="hero__video hero__video--crossfade"
        src="assets/hero-video.mp4"
        muted
        playsInline
        preload="auto"
        style={{ opacity: aFading ? 0 : 1, zIndex: topIsA ? 2 : 1 }}
      />
      <video
        ref={videoBRef}
        className="hero__video hero__video--crossfade"
        src="assets/hero-video.mp4"
        muted
        playsInline
        preload="auto"
        style={{ opacity: bFading ? 0 : 1, zIndex: topIsA ? 1 : 2 }}
      />
      <div className="hero__overlay" />

      <div className="hero__content">
        <h1 className="hero__title">Your Home. Built Right.</h1>
        <div className="hero__divider">
          <span className="hero__divider-line" />
          <span className="hero__divider-dot" />
          <span className="hero__divider-line" />
        </div>
        <p className="hero__subtitle">
          Riggins Design + Build guides every detail from the first
          conversation to the final walkthrough.
        </p>
      </div>

      <div className="hero__scroll" aria-hidden="true">
        <span>Scroll</span>
        <span className="hero__scroll-line" />
      </div>
    </section>
  );
}

function Intro() {
  return (
    <section className="intro section--paper">
      <Reveal>
        <p className="eyebrow">Three Generations of Building</p>
        <div className="intro__rule" />
        <p className="intro__lead">
          Three generations of building experience. One team that handles
          everything from design to the final walkthrough. At Riggins, we
          believe the process should be as good as the result.
        </p>
      </Reveal>
    </section>
  );
}

// Custom Home Plans split (image right, card left) — like the AR "Our Custom Home Plans" panel
function PlansSplit({ onNavigate }) {
  return (
    <Reveal as="section" className="split--overlap split--right" style={{ background: 'var(--bone)' }}>
      <div className="split__inner">
        <div
          className="split__media"
          style={{ backgroundImage: 'url("assets/home2.png")' }}
        />
        <div className="split__copy">
          <div className="split__copy-inner">
            <p className="eyebrow">The Riggins Process</p>
            <h2 className="split__title">Your Vision, Designed Around You.</h2>
            <p className="split__body">
              Every Riggins home begins with a conversation, not a catalog.
              Our in-house team guides you through site selection, floor
              plans, and finishes — refining every choice until the home on
              paper is the home you imagined.
            </p>
            <button className="arrow-link" onClick={() => onNavigate('about')}>
              <span>Learn About Our Process</span>
            </button>
          </div>
        </div>
      </div>
    </Reveal>
  );
}

// Available now — navy panel with carousel of homes
function AvailableNow({ onOpenProject }) {
  const slides = [
    {
      img: 'assets/home1.png',
      title: 'Modern Estate at Wexford',
      body: 'A four-bedroom modern estate on a private circular drive, available now in Gainesville’s most established custom community. Move-in ready with designer-curated finishes throughout.'
    },
    {
      img: 'assets/home3.png',
      title: 'The Stucco at Tower Road',
      body: 'A timeless stucco one-story with paver entry, oversized double doors, and an open kitchen built around a 12-foot island. Coming soon — early 2026.'
    },
    {
      img: 'assets/home4.png',
      title: 'Coastal Modern at Spring House',
      body: 'A bright coastal modern home with a wrap of windows, lifted on piers, and a primary suite opening to the trees. Now under contract.'
    },
    {
      img: 'assets/home5.png',
      title: 'The Magnolia at Tioga',
      body: 'A craftsman-influenced custom home with deep front porch and brick paver walk. Selections complete — final walkthrough scheduled.'
    }
  ];
  const [idx, setIdx] = useState(0);
  const next = () => setIdx((i) => (i + 1) % slides.length);
  const prev = () => setIdx((i) => (i - 1 + slides.length) % slides.length);
  const s = slides[idx];

  // Big "R" pattern
  const pattern = Array.from({ length: 8 })
    .map(() => 'R    R    R    R    R    R    R    R')
    .join('\n');

  return (
    <section className="available">
      <div className="available__pattern">{pattern}</div>

      <div className="available__inner">
        <div className="available__panel">
          <p className="available__eyebrow">Available · Coming Soon</p>
          <h2 className="available__title">Luxury Custom Homes Available Now</h2>
          <p className="available__body">
            Explore move-in ready, near completion, and coming-soon custom
            homes from Riggins Design + Build. Every home pairs timeless
            Gainesville architecture with the materials and craftsmanship
            we’d put in our own.
          </p>
          <h3 style={{ fontFamily: 'var(--serif)', color: 'var(--navy)', margin: '0 0 8px', fontSize: '1.4rem' }}>
            {s.title}
          </h3>
          <button
            className="arrow-link"
            onClick={() => onOpenProject({
              id: 'available-' + idx,
              name: s.title,
              location: 'Gainesville, FL',
              sqft: '4,200',
              year: '2026',
              style: 'Custom',
              description: s.body,
              cover: s.img
            })}
          >
            <span>Find My New Home</span>
          </button>

          <div className="available__nav">
            <button onClick={prev} aria-label="Previous">‹</button>
            <span className="available__counter">
              <b>{String(idx + 1).padStart(2, '0')}</b>
              <span> / {String(slides.length).padStart(2, '0')}</span>
            </span>
            <button onClick={next} aria-label="Next">›</button>
          </div>
        </div>

        <div
          className="available__media"
          style={{ backgroundImage: `url("${s.img}")` }}
        />
      </div>
    </section>
  );
}

// Recent work — image left, copy right
function RecentWorkSplit({ onNavigate }) {
  return (
    <Reveal as="section" className="split--overlap" style={{ background: 'var(--paper)' }}>
      <div className="split__inner">
        <div
          className="split__copy"
          style={{ background: 'var(--bone)' }}
        >
          <div className="split__copy-inner">
            <p className="eyebrow">Recent Work</p>
            <h2 className="split__title">
              Homes built around the people who live in them.
            </h2>
            <p className="split__body">
              From modern farmhouses on five acres to courtyard villas in the
              heart of town — every Riggins project is a one-off, designed
              for the family who will call it home. Browse our portfolio to
              see what we’ve been building lately.
            </p>
            <button className="arrow-link" onClick={() => onNavigate('projects')}>
              <span>View All Projects</span>
            </button>
          </div>
        </div>
        <div
          className="split__media"
          style={{ backgroundImage: 'url("assets/home1.png")' }}
        />
      </div>
    </Reveal>
  );
}

function Testimonial() {
  return (
    <section className="quote">
      <Reveal>
        <div className="quote__panel">
          <p className="quote__mark">“</p>
          <p className="quote__text">
            We are very pleased with our home and appreciate all the expertise
            and attention to detail that was given to it. Tyson and his team
            built exactly what we imagined — and stood behind every piece of it.
          </p>
          <p className="quote__attr">— The Halverson Family · Gainesville</p>
        </div>
      </Reveal>
    </section>
  );
}

// One continuous parallax canvas — text cards + photos scattered down a single
// navy section, varied counts (1-3 photos per row), no per-screen breaks.

function DiffImage({ src, className, style, speed = 1 }) {
  const wrapRef = useRef(null);
  const imgRef = useRef(null);
  useEffect(() => {
    let raf = 0;
    const update = () => {
      raf = 0;
      const wrap = wrapRef.current;
      const img = imgRef.current;
      if (!wrap || !img) return;
      const r = wrap.getBoundingClientRect();
      const vh = window.innerHeight;
      const p = (vh - r.top) / (vh + r.height);
      const t = (p - 0.5) * 180 * speed;
      img.style.transform = `translate3d(0, ${t}px, 0) scale(1.18)`;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    update();
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, [speed]);
  return (
    <div ref={wrapRef} className={`diff-img ${className || ''}`} style={style}>
      <div
        ref={imgRef}
        className="diff-img__inner"
        style={{ backgroundImage: `url("${src}")` }}
      />
    </div>
  );
}

function DiffCard({ index, total, eyebrow, title, body, className, style }) {
  return (
    <Reveal as="div" className={`diff-card ${className || ''}`} style={style}>
      <p className="eyebrow">{eyebrow || 'The Riggins Difference'}</p>
      <h2 className="diff-card__title">{title}</h2>
      <div className="diff-card__rule" />
      <p className="diff-card__body">{body}</p>
    </Reveal>
  );
}

function Difference() {
  const total = 6;
  // Each "block" is a hand-tuned row of scattered cards + photos
  return (
    <section className="diff-flow">
      {/* Row 1 — TWO photos (big right, small bottom-left), card top-left over photo */}
      <div className="diff-row diff-row--1">
        <DiffImage src="assets/home1.png" className="diff-img--r1-a" speed={1.0} />
        <DiffImage src="assets/page1b.webp" className="diff-img--r1-b" speed={-0.9} />
        <DiffCard
          index={0} total={total}
          title="Designed Around You, From Day One."
          body="We don’t hand you a binder and wish you luck. Our in-house team guides every finish, material, and selection with curated options and clear direction — so the process feels as good as the result."
          className="diff-card--r1"
        />
      </div>

      {/* Row 2 — THREE photos clustered right, card on top of photo, left side */}
      <div className="diff-row diff-row--2">
        <DiffImage src="assets/home2.png" className="diff-img--r2-a" speed={1.0} />
        <DiffImage src="assets/page2b.webp" className="diff-img--r2-b" speed={-1.1} />
        <DiffCard
          index={1} total={total}
          title="Rooted in Gainesville"
          body="This is our home too. We know the land, the climate, and the character of this city — and we build with all of it in mind."
          className="diff-card--r2"
        />
      </div>

      {/* Row 3 — ONE photo, card overlapping top-right corner */}
      <div className="diff-row diff-row--3">
        <DiffImage src="assets/page3.webp?v=2" className="diff-img--r3-a" speed={0.9} />
        <DiffCard
          index={2} total={total}
          title="One Team, One Vision"
          body="With design and construction under the same roof, nothing gets lost in translation. Fewer delays, fewer miscommunications, and a home that’s built exactly as it was imagined."
          className="diff-card--r3"
        />
      </div>

      {/* Row 4 — TWO photos asymmetric, card overlapping bottom of left photo */}
      <div className="diff-row diff-row--4">
        <DiffImage src="assets/extra4.webp" className="diff-img--r4-a" speed={1.1} />
        <DiffImage src="assets/page4b.webp" className="diff-img--r4-b" speed={-0.8} />
        <DiffCard
          index={3} total={total}
          title="Built to Last"
          body="We don’t cut corners where it counts. Quality is built into every phase, not just the parts you can see."
          className="diff-card--r4"
        />
      </div>

      {/* Row 5 — side-by-side split: skinny card left, big photo right */}
      <div className="diff-row diff-row--5">
        <DiffImage src="assets/home5.png" className="diff-img--r5-a" speed={0.6} />
        <DiffCard
          index={4} total={total}
          title="Clear Communication"
          body="You’ll always know where your project stands. No chasing updates, no surprises — just a straight answer when you need it."
          className="diff-card--r5"
        />
      </div>

      {/* Row 6 — ONE big photo, card centered on top */}
      <div className="diff-row diff-row--6">
        <DiffImage src="assets/page6.webp" className="diff-img--r6-a" speed={0.85} />
        <DiffCard
          index={5} total={total}
          title="Your Vision, Realized"
          body="We listen before we build. Every decision flows from what matters to you, so the finished home actually feels like yours."
          className="diff-card--r6"
        />
      </div>
    </section>
  );
}

function CallToAction({ onContact }) {
  return (
    <section className="cta">
      <Reveal>
        <h2 className="cta__title">Ready to Build Your Dream Home?</h2>
        <p className="cta__subtitle">Let’s start the conversation.</p>
        <button className="btn" onClick={onContact}>Get In Touch</button>
      </Reveal>
    </section>
  );
}

function Home({ onNavigate, onOpenProject }) {
  return (
    <React.Fragment>
      <HeroVideo />
      <Difference />
      <CallToAction onContact={() => onNavigate('contact')} />
    </React.Fragment>
  );
}

Object.assign(window, {
  HeroVideo, Intro, PlansSplit, AvailableNow, RecentWorkSplit, Testimonial,
  DiffImage, DiffCard, Difference, CallToAction, Home,
});
