/* global React, Icon, CtaBand, FaqItem */
const { useState, useRef, useEffect, useMemo } = React;

// ─── Home ───
// Video hero, then three scroll-driven set pieces: the "How it works" card
// deck, the "time" statement and the "chapters" polaroid reel. One rAF loop
// per pinned section writes transform/opacity directly to elements.
// Reduced motion: no autoplay, no pinning; sections render as static stacks.

const HOME_SIGNUP = 'https://my.everlasting-memory.com/signup';
const HOME_CTA = 'Start your free trial';
const HOME_ASSETS = 'assets/home/';

// Shown only once real content exists, so nothing placeholder ships live.
const HOME_OFFER = '7 days free · No card needed';
const HOME_TRIAL_TERMS = "You get 7 days to try every tool, from the recorder to your family tree, and you don't need a card. Messages you record during the trial aren't saved or sent, so it's a chance to see how everything works before you make the real thing. Subscribe and your family tree and profile carry straight over. If you don't, your trial account is deleted after 7 days.";
const HOME_PROOF_HEADING = 'Trusted by 30,219 families'; // verify the number before enabling
const HOME_TESTIMONIALS = [];     // { quote, name, detail }: real customers, with written consent
const HOME_SHOW_TIME = false;     // the pinned "Some messages arrive…" time statement; code kept, set true to bring it back

const HOME_STEPS = [
  { title: 'Record', body: 'Press record on your phone or laptop. Pause when you need to, re-record as often as you like, and keep only the take you save.' },
  { title: 'Choose who', body: "Name the people who should receive it. They're verified before any video is unlocked, and they never pay a penny." },
  { title: 'Choose when', body: 'Send it now, on a date or every birthday, up to a year ahead. Add Legacy for milestones further off, like their 18th or their wedding day. Change it any time.' },
  { title: 'They receive it', body: "When the day comes, a gentle email with a private link. They open it when they're ready. Nothing auto-plays." },
];

const HOME_DECK = [
  { img: 'phone-together', pos: '52% 40%', ui: 'record',
    alt: 'A young mother sits on a cream sofa with her baby on her lap under a green knitted blanket, both looking at the phone in her hand.' },
  { img: 'three-generations', pos: '50% 40%', ui: 'who',
    alt: 'A grandmother laughs as she and a grandfather hold their granddaughter close, her hand resting on theirs.' },
  { video: 'candles-960', ui: 'when',
    alt: 'Close-up of a hand lighting a ring of thin candles on a layered birthday cake.' },
  { img: 'golden-hour-phone', pos: '50% 40%', ui: 'delivered',
    alt: 'A young woman with long hair, backlit by low golden sun, smiles down at the phone in her hands.' },
];

const HOME_TIMES = [
  'Some messages arrive next week.',
  'Some arrive on their 18th.',
  'Some arrive on their wedding day.',
  'Some wait for the generations to come.',
];

const HOME_CHAPTERS = [
  { tab: 'New parents', title: 'For new parents', img: 'new-parents', rot: -3,
    body: 'Write the letter your child will open on their 18th birthday. Add Legacy and it can wait as many years as it needs.',
    alt: 'A smiling couple curl up together on a sofa, looking down at the positive pregnancy test in his hand.' },
  { tab: 'Working away', title: 'For those who work away', img: 'work-away', rot: 2.5,
    body: "Away on their birthday? Your message won't be. For the armed forces, offshore crews, pilots and anyone whose work takes them far from home.",
    alt: 'A father in a camouflage cap and army T-shirt holds his grinning toddler son on his lap.' },
  { tab: 'Grandparents', title: 'For grandparents', img: 'grandma-reading', rot: -1.5,
    body: "Tell the stories only you can tell, in your own voice, for the grandchildren who'll love hearing them.",
    alt: 'A grandmother in glasses reads a picture book in bed with her two young grandchildren tucked in either side of her.' },
  { tab: 'Every family', title: 'For every family', img: 'family-sofa', rot: 3,
    body: "Give every name on your family tree a face and a story, so the next generation knows who's who.",
    alt: 'A mother, father and two children laugh together on a sofa, the children leaning into their parents.' },
];

const HOME_TRUST = [
  { icon: 'lock', title: 'Protected & private',
    body: "From the moment you make it, every message is locked away. Only the loved ones you've chosen will ever be able to open it." },
  { icon: 'users', title: 'Only your chosen recipients',
    body: 'You name who receives what. Each person is verified before any message is unlocked.' },
  { icon: 'shield', title: 'You stay in control',
    body: "Edit, reschedule or delete a message at any time. As long as you're here, every decision is yours." },
  { icon: 'heart', title: 'Your legacy, preserved',
    body: 'Generations from now, your family will still be able to look you in the eye and hear your voice, exactly as you chose to be remembered. On the Legacy plan, two Guardians you name make sure it arrives.' },
];

const HOME_FAQS = [
  HOME_TRIAL_TERMS && { q: 'How does the free trial work?', a: HOME_TRIAL_TERMS },
  { q: 'Can I send a message now, rather than years from now?', a: 'Yes. You can send right away or schedule for later. Both work the same way.' },
  { q: 'Can I change a message after it is scheduled?', a: 'Yes. Edit, reschedule or delete any message at any time, and add or remove recipients whenever you like.' },
  { q: 'What happens to my messages if I pass away?', a: "With the Legacy plan, you name two Guardians who'll let us know when the time comes. Nothing is released until both have confirmed. Then your messages arrive exactly as you planned, by a quiet email rather than a pop-up." },
  { q: 'What happens to my messages if I stop paying?', a: "Messages you've already scheduled are still sent, exactly as you planned. They're never cancelled or paused. On a monthly or yearly plan, that's everything in the next 12 months; with Legacy, it's every date, however far ahead. You just won't be able to add, edit or remove messages until you subscribe again." },
  { q: 'Do the people I send messages to have to pay?', a: 'Never. The people you send messages to will never pay a penny.' },
].filter(Boolean);

const homeClamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v));
const homeEase = (t) => 1 - Math.pow(1 - t, 3); // ease-out cubic for scrubbed entrances

// Phone-only progress bar (CSS hides it on wider screens): one segment per step. Segment 1 is
// full from the start; each later one fills as its step scrolls in, so all four are full at the end.
// Scrubbed from the scroll loop (transform only, no CSS transition).
function HomeSegments({ count, refs, className = '' }) {
  return (
    <div className={'home-progress ' + className} aria-hidden="true">
      {Array.from({ length: count }, (_, i) => <span key={i}><i ref={el => (refs.current[i] = el)} /></span>)}
    </div>
  );
}
const homeFillSegments = (els, p) => els.forEach((el, i) => {
  if (el) el.style.transform = `scaleX(${i === 0 ? 1 : homeClamp(p - (i - 1))})`;
});
const homeReducedMotion = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;

// In-page scroll that respects <base href="/"> and moves focus with it
function homeScrollTo(id, e) {
  if (e) e.preventDefault();
  const el = document.getElementById(id);
  if (!el) return;
  el.scrollIntoView({ behavior: homeReducedMotion() ? 'auto' : 'smooth', block: 'start' });
  el.focus({ preventScroll: true });
}

// Responsive photo: AVIF → WebP → JPEG, explicit size, lazy by default
function HomePhoto({ name, alt, sizes = '100vw', className = '', style }) {
  const set = (ext) => [480, 800, 1200, 1800].map(w => `${HOME_ASSETS}${name}-${w}.${ext} ${w}w`).join(', ');
  return (
    <div className={'home-photo ' + className} style={style}>
      <picture>
        <source type="image/avif" srcSet={set('avif')} sizes={sizes} />
        <source type="image/webp" srcSet={set('webp')} sizes={sizes} />
        <img src={`${HOME_ASSETS}${name}-1200.jpg`} srcSet={`${HOME_ASSETS}${name}-800.jpg 800w, ${HOME_ASSETS}${name}-1200.jpg 1200w`}
             sizes={sizes} width="1200" height="800" alt={alt} loading="lazy" decoding="async" />
      </picture>
    </div>
  );
}

// Square polaroid photo (480 / 800 only)
function HomePolaroidImg({ name, alt }) {
  const set = (ext) => `${HOME_ASSETS}${name}-480.${ext} 480w, ${HOME_ASSETS}${name}-800.${ext} 800w`;
  return (
    <picture>
      <source type="image/avif" srcSet={set('avif')} sizes="(max-width: 600px) 70vw, 400px" />
      <source type="image/webp" srcSet={set('webp')} sizes="(max-width: 600px) 70vw, 400px" />
      <img src={`${HOME_ASSETS}${name}-800.jpg`} srcSet={set('jpg')} sizes="(max-width: 600px) 70vw, 400px"
           width="800" height="800" alt={alt} loading="lazy" decoding="async" />
    </picture>
  );
}

// Muted looping video that only plays while on screen, never under reduced
// motion or Save-Data. A user pause (data-user-paused) is respected.
function HomeVideo({ src, poster, label, className = '', videoRef, onPlayingChange, eager = false }) {
  const local = useRef(null);
  const ref = videoRef || local;
  useEffect(() => {
    const v = ref.current;
    if (!v) return;
    const allow = !homeReducedMotion() && !(navigator.connection && navigator.connection.saveData);
    if (!allow) { onPlayingChange && onPlayingChange(false); return; }
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !v.dataset.userPaused) v.play().then(() => onPlayingChange && onPlayingChange(true)).catch(() => {});
      else if (!e.isIntersecting) v.pause();
    }, { threshold: 0.15 });
    io.observe(v);
    return () => io.disconnect();
  }, [src]);
  return (
    <video ref={ref} className={className} muted loop playsInline preload={eager ? 'auto' : 'none'}
           poster={poster} aria-label={label} src={src} />
  );
}

// Product UI laid over each deck card
function HomeDeckUI({ kind }) {
  if (kind === 'record') return (
    <div className="home-ui home-ui--pill"><span className="home-ui__dot" /> Recording for Maya · 02:34</div>
  );
  if (kind === 'who') return (
    <div className="home-ui home-ui--card">
      <p className="home-ui__label">Who should receive it?</p>
      {[['M', 'Maya', 'Daughter', true], ['L', 'Lila', 'Daughter', true], ['S', 'Sam', 'Son', false]].map(([i, n, r, on]) => (
        <div key={n} className={'home-ui__row' + (on ? ' is-on' : '')}>
          <span className="home-ui__avatar">{i}</span><span>{n} <small>{r}</small></span>
          <span className="home-ui__check">{on && <Icon name="check" size={12} />}</span>
        </div>
      ))}
    </div>
  );
  if (kind === 'when') return (
    <div className="home-ui home-ui--card">
      <p className="home-ui__label">Delivery</p>
      <div className="home-ui__when"><strong>12 May, 8:00am</strong><span>Maya's 30th birthday</span></div>
      <div className="home-ui__chips"><span>Send now</span><span className="is-on">On a date</span><span>Every birthday</span></div>
    </div>
  );
  return (
    <div className="home-ui home-ui--note">
      <span className="home-ui__mark"><Icon name="play" size={16} /></span>
      <div><p className="home-ui__title">A message from Dad is waiting for you</p><p className="home-ui__meta">Open when you're ready</p></div>
    </div>
  );
}

// "For every chapter of life": pinned keepsake pile. Each chapter owns an
// equal slice of the pin; crossing a threshold drops that chapter's polaroid
// onto the pile (CSS transition on data-state), scrolling back lifts it off.
// The meter's fill and dot are scrubbed directly from scroll.
const HOME_PILE_OFFSETS = [[-18, 12], [22, -8], [-6, 20], [14, 2]];

function HomeChapters() {
  const N = HOME_CHAPTERS.length;
  const reduce = useMemo(homeReducedMotion, []);
  const ref = useRef(null), fillRef = useRef(null), dotRef = useRef(null), trackRef = useRef(null), activeRef = useRef(0);
  const [active, setActive] = useState(0);

  useEffect(() => {
    if (reduce) return;
    let raf = 0;
    const update = () => {
      raf = 0;
      const el = ref.current;
      if (!el) return;
      const r = el.getBoundingClientRect();
      const p = homeClamp(-r.top / (r.height - window.innerHeight)) * N;
      const idx = Math.min(N - 1, Math.floor(p));
      if (idx !== activeRef.current) { activeRef.current = idx; setActive(idx); }
      const f = homeClamp(p / N);
      if (fillRef.current) fillRef.current.style.transform = `scaleY(${f})`;
      if (dotRef.current && trackRef.current) dotRef.current.style.transform = `translateY(${f * trackRef.current.offsetHeight}px)`;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    update();
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); cancelAnimationFrame(raf); };
  }, [reduce]);

  const intro = (
    <div className="home-chapters__intro">
      <h2 id="home-chapters" className="home-h2">For every chapter of life</h2>
      <p className="home-lede">Whoever you are and wherever life takes you, there's someone who'd treasure hearing from you.</p>
    </div>
  );

  if (reduce) return (
    <section className="home-section home-chapters home-chapters--static" aria-labelledby="home-chapters">
      <div className="home-wrap">
        {intro}
        <div className="home-chapters__list">
          {HOME_CHAPTERS.map((c) => (
            <article key={c.img} className="home-chapters__item">
              <figure className="home-polaroid home-polaroid--flat" style={{ '--r': `${c.rot}deg` }}>
                <HomePolaroidImg name={c.img} alt={c.alt} />
                <figcaption>{c.title}</figcaption>
              </figure>
              <div><h3 className="home-h3">{c.title}</h3><p className="home-body">{c.body}</p></div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );

  const ch = HOME_CHAPTERS[active];
  return (
    <section ref={ref} className="home-chapters" aria-labelledby="home-chapters">
      <div className="home-chapters__stage">
        <div className="home-wrap home-chapters__layout">
          {intro}
          <div className="home-chapters__body">
            <div className="home-chapters__pile">
              {HOME_CHAPTERS.map((c, i) => (
                <figure key={c.img} className="home-polaroid home-chapters__card" data-state={i <= active ? 'down' : 'up'}
                        style={{ '--r': `${c.rot}deg`, '--x': `${HOME_PILE_OFFSETS[i][0]}px`, '--y': `${HOME_PILE_OFFSETS[i][1]}px`, zIndex: i + 1 }}
                        aria-hidden={i !== active}>
                  <HomePolaroidImg name={c.img} alt={i === active ? c.alt : ''} />
                  <figcaption>{c.title}</figcaption>
                </figure>
              ))}
            </div>
            <div className="home-chapters__text" aria-live="polite">
              <div key={active} className="home-chapters__fade">
                <p className="home-step">{String(active + 1).padStart(2, '0')} / 0{N}</p>
                <h3 className="home-h2 home-chapters__title">{ch.title}</h3>
                <p className="home-body">{ch.body}</p>
              </div>
            </div>
          </div>
        </div>
        <div className="home-chapters__meter" aria-hidden="true">
          <span ref={trackRef} className="home-chapters__track"><i ref={fillRef} /></span>
          <span ref={dotRef} className="home-chapters__dot" />
        </div>
      </div>
    </section>
  );
}

// Lock whose shackle drops shut once its trust point is revealed
function HomeLockIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"
         strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
      <path className="home-trust__shackle" d="M8 11V7a4 4 0 0 1 8 0v4" />
      <rect x="4" y="11" width="16" height="10" rx="2" />
    </svg>
  );
}

function HomeTrust({ navigate }) {
  return (
    <section className="home-section home-light home-paper home-trust" aria-labelledby="home-trust">
      <div className="home-wrap home-trust__grid">
        <div className="home-trust__head" data-reveal>
          <h2 id="home-trust" className="home-h2">Built on trust. Your story stays yours.</h2>
          <p className="home-lede">Your messages are stored securely and kept private, from the moment you record them until the day they arrive.</p>
          <a className="home-link" href="/features/" onClick={(e) => { e.preventDefault(); navigate('features'); }}>How we protect your messages</a>
        </div>
        <ul className="home-trust__items">
          {HOME_TRUST.map((t, i) => (
            <li key={t.title} className="home-trust__item" data-reveal style={{ '--delay': `${i * 60}ms` }}>
              <span className="home-trust__icon">{t.icon === 'lock' ? <HomeLockIcon /> : <Icon name={t.icon} size={16} />}</span>
              <div>
                <h3>{t.title}</h3>
                <p className="home-body">{t.body}</p>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

function HomePage({ navigate }) {
  const heroRef = useRef(null), heroMedia = useRef(null), heroCopy = useRef(null), heroVideo = useRef(null);
  const deckRef = useRef(null), cardRefs = useRef([]), dimRefs = useRef([]), capRefs = useRef([]), countRef = useRef(null);
  const timeRef = useRef(null), phraseRefs = useRef([]), floatRefs = useRef([]);
  const deckSegRefs = useRef([]), timeSegRefs = useRef([]);
  const deckStageRef = useRef(null), deckFrameRef = useRef(null);
  const [heroPlaying, setHeroPlaying] = useState(false);
  const [reduce] = useState(homeReducedMotion);

  // Pick the hero file once, by viewport width. The montage is four clips, about 3s each with
  // crossfades, edited into one seamless 12s loop (scripts/hero-montage.sh). The single-clip
  // hero-1920/1280/mobile files are kept in assets/home as a fallback.
  const heroSrc = useMemo(() => {
    const w = window.innerWidth;
    return w <= 860 ? 'hero-montage-mobile' : w <= 1440 ? 'hero-montage-1280' : 'hero-montage-1920';
  }, []);

  useEffect(() => {
    if (reduce) return;
    let raf = 0;
    const N = HOME_DECK.length;
    const update = () => {
      raf = 0;
      const vh = window.innerHeight;

      // Hero settles into a rounded card as it leaves
      if (heroRef.current) {
        const h = homeClamp(-heroRef.current.getBoundingClientRect().top / (vh * 0.9));
        heroMedia.current.style.transform = `scale(${1 - 0.06 * h})`;
        heroMedia.current.style.borderRadius = `${Math.round(28 * h)}px`;
        heroCopy.current.style.opacity = String(1 - homeClamp(h * 1.6));
        heroCopy.current.style.transform = `translateY(${-40 * h}px)`;
      }

      // Card deck: card 0 grows in, the rest rise and stack
      if (deckRef.current) {
        const r = deckRef.current.getBoundingClientRect();
        const enter = homeEase(homeClamp(1 - r.top / vh));
        const p = homeClamp(-r.top / (r.height - vh)) * (N - 1 + 0.6); // 0 … N-1 while pinned, plus a short hold
        homeFillSegments(deckSegRefs.current, p);
        // Incoming cards start fully below the stage (off canvas), however much room the layout
        // leaves under the card: 112% on desktop, more on phones where the card is centred
        const sr = deckStageRef.current.getBoundingClientRect(), fr = deckFrameRef.current.getBoundingClientRect();
        const start = Math.max(112, ((sr.bottom - fr.top) / fr.height) * 100 + 4);
        cardRefs.current.forEach((el, i) => {
          if (!el) return;
          const inT = i === 0 ? 1 : homeEase(homeClamp(p - (i - 1)));
          const behind = i === N - 1 ? 0 : homeClamp(p - i); // the last card stays lit through the hold
          const base = i === 0 ? 0.84 + 0.16 * enter : 1;
          el.style.transform = `translateY(${(1 - inT) * start}%) translateY(${-3 * behind}%) scale(${base * (1 - 0.06 * behind)})`;
          if (dimRefs.current[i]) dimRefs.current[i].style.opacity = String(0.55 * behind);
        });
        capRefs.current.forEach((el, i) => {
          if (!el) return;
          const d = i === N - 1 ? Math.min(0, p - i) : p - i;
          // Full strength for most of its step; a quick hand-over (old out, then new in)
          const o = homeClamp(1 - (Math.abs(d) - 0.3) * 5);
          el.style.opacity = String(o);
          el.style.transform = `translateY(${-d * 28}px)`;
          el.setAttribute('aria-hidden', o === 1 ? 'false' : 'true'); // only the settled caption is "current"
        });
        if (countRef.current) countRef.current.textContent = `0${Math.min(N, Math.round(p) + 1)} / 0${N}`;
      }

      // Time statement + drifting collage
      if (timeRef.current) {
        const r = timeRef.current.getBoundingClientRect();
        const p = homeClamp(-r.top / (r.height - vh)) * (HOME_TIMES.length - 1 + 0.5);
        homeFillSegments(timeSegRefs.current, p);
        phraseRefs.current.forEach((el, i) => {
          if (!el) return;
          const d = i === HOME_TIMES.length - 1 ? Math.max(0, i - p) : i - p; // the last phrase holds
          el.style.opacity = String(homeClamp(1 - Math.abs(d) * 2.2));
          el.style.transform = `translateY(${d * 56}px)`;
        });
        const travel = homeClamp((vh - r.top) / (r.height + vh));
        // Phones drift far less, so the photos stay in their top and bottom bands, clear of the words
        const drift = window.innerWidth <= 768 ? 150 : 520;
        floatRefs.current.forEach((el) => {
          if (el) el.style.transform = `translate3d(0, ${(0.5 - travel) * parseFloat(el.dataset.depth) * drift}px, 0)`;
        });
      }
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    update();
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); cancelAnimationFrame(raf); };
  }, [reduce]);

  const toggleHero = () => {
    const v = heroVideo.current;
    if (!v) return;
    if (v.paused) { delete v.dataset.userPaused; v.play().then(() => setHeroPlaying(true)).catch(() => {}); }
    else { v.dataset.userPaused = '1'; v.pause(); setHeroPlaying(false); }
  };

  const float = (i, depth, child) => (
    <div ref={el => (floatRefs.current[i] = el)} data-depth={depth} className={`home-float__item home-float__item--${i + 1}`}>{child}</div>
  );

  return (
    <div className={'home' + (reduce ? ' home--static' : '')} data-em-surface="ink">
      {/* HERO */}
      <section ref={heroRef} className="home-hero" aria-labelledby="home-title">
        <div ref={heroMedia} className="home-hero__media">
          <HomeVideo videoRef={heroVideo} eager src={`${HOME_ASSETS}${heroSrc}.mp4`}
                     poster={`${HOME_ASSETS}${heroSrc === 'hero-montage-mobile' ? 'hero-montage-poster-mobile' : 'hero-montage-poster'}.jpg`}
                     label="Short clips in turn: a mother and father laughing with their young daughter, a woman smiling at her phone at sunset, two people holding hands in evening light, and low sun through a field."
                     className="home-hero__video" onPlayingChange={setHeroPlaying} />
          <div className="home-hero__scrim" />
        </div>
        <div ref={heroCopy} className="home-hero__copy">
          <h1 id="home-title" className="home-hero__title">Your voice, on the day it matters.</h1>
          <p className="home-lede">
            Record a video, voice note or letter for someone you love, and we'll deliver it on the day you
            choose, whether that's a birthday you'll miss or a milestone years from now. Your family's photos
            and stories are kept in the same private place.
          </p>
          <div className="home-ctabar">
            <a className="btn btn--gold" href={HOME_SIGNUP}>{HOME_CTA}</a>
            <a className="btn btn--ghost-light" href="/#how" onClick={(e) => homeScrollTo('how', e)}>See how it works</a>
          </div>
          {HOME_OFFER && <p className="home-offer">{HOME_OFFER}</p>}
        </div>
        <button type="button" className="home-hero__pause" onClick={toggleHero} style={{ display: 'none' }}
                aria-label={heroPlaying ? 'Pause background video' : 'Play background video'}>
          {heroPlaying
            ? <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="6" y="4" width="4" height="16" rx="1" /><rect x="14" y="4" width="4" height="16" rx="1" /></svg>
            : <Icon name="play" size={14} />}
        </button>
      </section>

      {/* WHAT IF */}
      <section className="home-section home-whatif" aria-labelledby="home-whatif">
        <div className="home-wrap">
          <div className="home-head home-head--center" data-reveal>
            <h2 id="home-whatif" className="home-h2">What if you could still be there, even when you can't be?</h2>
          </div>
          <div className="home-story" data-reveal>
            <p className="home-lede">
              Our co-founder has one recording of his dad: a voicemail, thirty-four seconds long, left on a
              Tuesday just to say he'd been thinking about him. We built Everlasting Memory so your family has
              more than that.
            </p>
            <a className="home-link" href="/about/" onClick={(e) => { e.preventDefault(); navigate('about'); }}>Read our story</a>
          </div>
          <div className="home-whatif__cols">
            <div className="home-whatif__col" data-reveal>
              <span className="home-icon"><Icon name="mail" size={16} /></span>
              <h3 className="home-h3">Messages that arrive on the day</h3>
              <p className="home-body">
                Pick the day each message arrives. The birthday you'll miss on
                deployment, the anniversary you'll spend offshore, or, with Legacy, a wedding years from now.
              </p>
            </div>
            <div className="home-whatif__col" data-reveal style={{ '--delay': '100ms' }}>
              <span className="home-icon"><Icon name="users" size={16} /></span>
              <h3 className="home-h3">A home for your family tree</h3>
              <p className="home-body">
                Build your family tree, give every name a photo and the stories behind it, and keep your family's
                albums, memories and milestones together. So the people who came before you, and those still to
                come, are never forgotten.
              </p>
            </div>
          </div>
        </div>
      </section>

      {/* HOW IT WORKS — pinned card deck */}
      <section id="how" tabIndex={-1} ref={deckRef} className="home-deck" aria-labelledby="home-how">
        <div ref={deckStageRef} className="home-deck__stage">
          <div className="home-deck__head">
            <h2 id="home-how" className="home-h2">How it works</h2>
            <p ref={countRef} className="home-deck__count" aria-hidden="true">01 / 04</p>
            <HomeSegments count={HOME_DECK.length} refs={deckSegRefs} />
          </div>
          <div ref={deckFrameRef} className="home-deck__frame">
            {HOME_DECK.map((c, i) => (
              <div key={i} ref={el => (cardRefs.current[i] = el)} className="home-card" style={{ zIndex: i + 1 }}>
                {c.video
                  ? <HomeVideo src={`${HOME_ASSETS}${c.video}.mp4`} poster={`${HOME_ASSETS}candles-poster.jpg`} label={c.alt} className="home-card__media" />
                  : <HomePhoto name={c.img} alt={c.alt} sizes="(max-width: 860px) 92vw, 720px" className="home-card__media" style={{ '--pos': c.pos }} />}
                <div className="home-card__shade" />
                <div className="home-card__ui"><HomeDeckUI kind={c.ui} /></div>
                <div ref={el => (dimRefs.current[i] = el)} className="home-card__dim" />
              </div>
            ))}
          </div>
          <ol className="home-caps">
            {HOME_STEPS.map((s, i) => (
              <li key={s.title} ref={el => (capRefs.current[i] = el)} className={'home-cap home-cap--' + (i % 2 ? 'right' : 'left')}>
                <span className="home-step">Step {i + 1}</span>
                <h3 className="home-h3">{s.title}</h3>
                <p className="home-body">{s.body}</p>
              </li>
            ))}
          </ol>
        </div>
      </section>

      {/* TIME STATEMENT — pinned, with drifting collage (off: HOME_SHOW_TIME) */}
      {HOME_SHOW_TIME && (
      <section ref={timeRef} className="home-time" aria-labelledby="home-time">
        <div className="home-time__stage">
          <h2 id="home-time" className="sr-only">{HOME_TIMES.join(' ')}</h2>
          <div className="home-float" aria-hidden="true">
            {float(0, 0.9, <HomePhoto name="family-meadow" alt="" sizes="260px" />)}
            {float(1, 0.5, <div className="viz-schedule__row"><div className="viz-schedule__date">Next week</div><div className="viz-schedule__title">Happy birthday, love</div></div>)}
            {float(2, 1.3, <HomePhoto name="beach-dance" alt="" sizes="220px" />)}
            {float(3, 0.7, <HomePhoto name="sunset-field" alt="" sizes="280px" />)}
            {float(4, 1.1, <div className="viz-schedule__row"><div className="viz-schedule__date">On her 18th</div><div className="viz-schedule__title">What I learned at your age</div></div>)}
            {float(5, 0.6, <HomePhoto name="old-photographs" alt="" sizes="200px" />)}
          </div>
          <HomeSegments count={HOME_TIMES.length} refs={timeSegRefs} className="home-progress--time" />
          <div className="home-phrases" aria-hidden="true">
            {HOME_TIMES.map((t, i) => (
              <p key={t} ref={el => (phraseRefs.current[i] = el)} className="home-phrase home-h2" style={{ opacity: i === 0 ? 1 : 0 }}>{t}</p>
            ))}
          </div>
        </div>
      </section>
      )}

      {/* CHAPTERS — pinned polaroid reel */}
      <HomeChapters />

      {/* TRUST */}
      <HomeTrust navigate={navigate} />

      {/* PROOF — renders once real testimonials are added */}
      {HOME_TESTIMONIALS.length > 0 && (
        <section className="home-section" aria-labelledby="home-proof">
          <div className="home-wrap">
            <div className="home-head home-head--center" data-reveal>
              <h2 id="home-proof" className="home-h2">{HOME_PROOF_HEADING}</h2>
            </div>
            <div className="home-quotes">
              {HOME_TESTIMONIALS.map((t) => (
                <figure key={t.name} className="home-quote" data-reveal>
                  <blockquote className="home-quote__text">“{t.quote}”</blockquote>
                  <figcaption className="home-quote__who">{t.name} · {t.detail}</figcaption>
                </figure>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* FAQ */}
      <section className="home-section" aria-labelledby="home-faq">
        <div className="home-wrap home-wrap--narrow">
          <div className="home-head" data-reveal><h2 id="home-faq" className="home-h2">Questions people ask first.</h2></div>
          <div className="faq home-faq">
            {HOME_FAQS.map(f => <FaqItem key={f.q} q={f.q} a={f.a} />)}
          </div>
        </div>
      </section>

      <CtaBand
        title="One day, your family will press play and hear you. Start your family's story today."
        cta={HOME_CTA}
        note="7 days free · No card needed to try"
      />
    </div>
  );
}

Object.assign(window, { HomePage });
