/* global React, PhoneMock, useReveal, AylaRouter, AYLA_WAITLIST, InsightCard, MealLogCard, POSTS, formatPostTags */
const { useEffect, useRef } = React;

const HERO_VIDEO_SRC = window.AYLA_HERO_VIDEO || 'assets/waves-hero-1080.mp4';

const HOME_BLOG_SLUGS = [
  'why-your-healthy-routine-might-be-hurting-your-hormones',
  'the-3-pm-energy-crash-a-biological-explanation',
  'chronic-stress-cortisol-and-the-hidden-link-to-hormonal-disorders',
];

function Home({ setRoute }) {
  const heroVideoRef = useRef(null);
  const heroSectionRef = useRef(null);
  const featuresSectionRef = useRef(null);

  useReveal();

  // Removed scroll-snap logic for smooth, uninterrupted scrolling


  useEffect(() => {
    const section = featuresSectionRef.current;
    if (!section) return undefined;
    const targets = section.querySelectorAll('.features-reveal:not(.in)');
    if (!targets.length) return undefined;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.2, rootMargin: '0px 0px -8% 0px' });
    targets.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);

  useEffect(() => {
    const video = heroVideoRef.current;
    if (!video) return undefined;

    const early = window.__aylaHeroVideoPreload;
    if (early && early !== video && early.readyState >= 2) {
      video.src = HERO_VIDEO_SRC;
      video.currentTime = early.currentTime || 0;
    }

    video.loop = true;
    video.muted = true;

    const play = () => {
      const attempt = video.play();
      if (attempt && typeof attempt.catch === 'function') {
        attempt.catch(() => {});
      }
    };

    const restart = () => {
      video.currentTime = 0;
      play();
    };

    const onEnded = () => restart();
    const onStall = () => play();
    const onVisibility = () => {
      if (!document.hidden) play();
    };

    const dropEarlyPreload = () => {
      const early = window.__aylaHeroVideoPreload;
      if (early && early.parentNode) early.parentNode.removeChild(early);
      window.__aylaHeroVideoPreload = null;
    };

    play();
    video.addEventListener('loadeddata', dropEarlyPreload, { once: true });
    video.addEventListener('ended', onEnded);
    video.addEventListener('stalled', onStall);
    video.addEventListener('suspend', onStall);
    document.addEventListener('visibilitychange', onVisibility);

    return () => {
      video.removeEventListener('loadeddata', dropEarlyPreload);
      video.removeEventListener('ended', onEnded);
      video.removeEventListener('stalled', onStall);
      video.removeEventListener('suspend', onStall);
      document.removeEventListener('visibilitychange', onVisibility);
    };
  }, []);

  return (
    <div className="page page-home">
      {/* HERO */}
      <section className="hero" ref={heroSectionRef}>
        <div className="hero-media" aria-hidden="true">
          <video
            ref={heroVideoRef}
            autoPlay
            loop
            muted
            playsInline
            preload="auto"
            fetchPriority="high"
            className="hero-bg-video"
            src={HERO_VIDEO_SRC}
          />
        </div>
        <div className="hero-overlay shell">
          <div className="hero-content">
            <h1>
              Gentle, intelligent care for every <em>phase</em> of you.
            </h1>
            <p className="hero-lede">
              <span className="hero-lede-full">
                Ayla is your companion for hormonal health. Each day, you&apos;ll receive a short note on nutrition, movement, and rest, tailored to your cycle phase and the patterns you log. Grounded in science and delivered with warmth, Ayla helps you understand and support your body through every phase.
              </span>
              <span className="hero-lede-short">
                Daily note on nutrition, movement, and rest, written for the phase you&apos;re in.
              </span>
            </p>
            <div className="hero-actions">
              <a className="btn" href={AylaRouter.pathFor('waitlist')} onClick={(e) => {e.preventDefault();setRoute('waitlist');}}>
                Get the Cycle Guide
                <span className="arr">→</span>
              </a>
              <a className="btn btn-ghost" href={AylaRouter.pathFor('about')} onClick={(e) => {e.preventDefault();setRoute('about');}}>
                Read the philosophy
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* FEATURES */}
      <section className="section shell features-section" ref={featuresSectionRef}>
        <div className="section-head">
          <h2 className="features-reveal">The body keeps its own time. <span className="it">Ayla learns to read it.</span></h2>
          <p className="features-reveal">Three small habits, repeated through a cycle, become something you can feel. Ayla makes them effortless and turns the noise of your data into one quiet daily note.</p>
        </div>
        <div className="features">
          <div className="feature reveal">
            <h3>A daily note, written for your phase.</h3>
            <p>Curated based on your phase, your logged patterns, the condition you're managing, and the research that ties them together. Maybe today you front-load the harder meetings. Maybe you ease off caffeine, or eat for the luteal dip.</p>
            <div className="vis insight-vis">
              <InsightCard />
            </div>
          </div>
          <div className="feature reveal" style={{ transitionDelay: '.08s' }}>
            <h3>Nutrition that moves with your cycle.</h3>
            <p>What your body needs from a meal shifts across the month. Ayla tracks what you eat alongside your phase and condition, with more iron, protein, and fibre when your cycle calls for it.</p>
            <div className="vis meal-vis">
              <MealLogCard />
            </div>
          </div>
          <div className="feature reveal" style={{ transitionDelay: '.16s' }}>
            <h3>Movement & recovery, written into the calendar.</h3>
            <p>Cycle-aware movement and rest targets that shift with your phase. Quieter mornings in luteal, strength when energy returns, recovery built in.</p>
            <div className="vis movement-vis">
              <MovementCard />
            </div>
          </div>
        </div>
      </section>

      {/* PHASES */}
      <section className="section shell">
        <div className="section-head reveal">
          <h2>Four phases. <span className="it">One thoughtful guide.</span></h2>
          <p>Ayla speaks differently to each part of your cycle. Energy in the follicular weeks,
             clarity at ovulation, kindness in luteal, permission to slow down at the start.</p>
        </div>
        <div className="phases reveal">
          <div className="phase">
            <div className="phase-body">
              <div className="lbl">Menstrual</div>
              <h4>Soft start</h4>
              <p>Iron-forward meals, fewer alarms, permission to do less.</p>
            </div>
            <div className="phase-fruit">
              <img src="assets/menstrual.jpg" alt="" />
            </div>
          </div>
          <div className="phase">
            <div className="phase-body">
              <div className="lbl">Follicular</div>
              <h4>The bright climb</h4>
              <p>Strength training, new ideas, the bigger conversation.</p>
            </div>
            <div className="phase-fruit">
              <img src="assets/follicular.jpg" alt="" />
            </div>
          </div>
          <div className="phase">
            <div className="phase-body">
              <div className="lbl">Ovulatory</div>
              <h4>Peak window</h4>
              <p>Connection, clarity, the day to send the email.</p>
            </div>
            <div className="phase-fruit">
              <img src="assets/ovulatory.jpg" alt="" />
            </div>
          </div>
          <div className="phase">
            <div className="phase-body">
              <div className="lbl">Luteal</div>
              <h4>Quieter weeks</h4>
              <p>Protein and fibre at every meal. Earlier bedtimes. Long walks.</p>
            </div>
            <div className="phase-fruit">
              <img src="assets/luteal.jpg" alt="" />
            </div>
          </div>
        </div>
      </section>

      {/* SPLIT — PMOS */}
      <section className="section shell">
        <div className="split">
          <div className="copy reveal">
            <span className="eyebrow">Built for the irregular</span>
            <h2 style={{ marginTop: 18 }}>Especially considered for women with <span className="it">PMOS.</span></h2>
            <p>Up to 70% of women with PMOS remain undiagnosed worldwide often dismissed because their cycles fall outside the textbook 28-day window most apps were built around. Ayla doesn't need a regular cycle. It learns yours.

            </p>
            <div className="stats">
              <div className="stat"><div className="n">1 in 10</div><div className="l">women live with PMOS</div></div>
              <div className="stat"><div className="n">7yr</div><div className="l">avg. time to diagnosis</div></div>
              <div className="stat"><div className="n">21–45</div><div className="l">days in a healthy cycle</div></div>
            </div>
          </div>
      <div className="reveal cycle-graph-wrapper" style={{ position: 'relative' }}>
        <div className="cycle-graph-box">
          <CycleGraph />
        </div>
        <div className="card did-you-know-card" style={{ position: 'absolute', left: -52, bottom: -48, maxWidth: 260, zIndex: 10, background: 'var(--ivory)', boxShadow: '0 20px 60px -30px rgba(34,31,26,.25)', transition: 'opacity 0.3s ease, transform 0.3s ease' }}>
          <span className="eyebrow">No two PMOS cycles look exactly alike</span>
          <p className="serif italic" style={{ fontSize: 20, lineHeight: 1.3, margin: '10px 0 14px', letterSpacing: '-0.01em' }}>
          Hormonal patterns can shift significantly, making personalized tracking more meaningful.
          </p>
          {/* <p style={{ fontSize: 12, color: 'var(--ink-2)', margin: 0, letterSpacing: '.06em' }}>— Clinical Endocrinology</p> */}
        </div>
      </div>
        </div>
      </section>

      {/* JOURNAL */}
      <section className="section shell">
        <div className="section-head reveal">
          <h2>From the <span className="it">blog</span>.</h2>
          <p>Science-backed guidance on hormones, nutrition, sleep, movement, and everything in between.
          </p>
        </div>
        <div className="journal">
          {HOME_BLOG_SLUGS.map((slug) => (POSTS || []).find((p) => p.slug === slug)).filter(Boolean).map((p, i) => (
            <article key={p.slug} className="j-card reveal" role="link" tabIndex={0}
              onClick={() => setRoute('journal-post:' + p.slug)}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setRoute('journal-post:' + p.slug); } }}
              style={{ cursor: 'pointer', transitionDelay: i ? `${i * 0.08}s` : undefined }}>
              <div className={'j-thumb' + (p.image ? '' : ' ph ' + (p.tone || ''))}>
                {p.image
                  ? <img src={p.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'inherit', display: 'block' }} />
                  : <span className="ph-tag">blog image</span>}
              </div>
              <div className="j-meta"><span>{formatPostTags(p)}</span><span>· {p.read}</span></div>
              <h3>{p.title}</h3>
              <p>{p.dek}</p>
            </article>
          ))}
        </div>
      </section>

      {/* SIGNUP */}
      <section className="section shell">
        <div className="signup reveal">
          <div>
            <span className="eyebrow">The Cycle Guide</span>
            <h2 style={{ marginTop: 18 }}>A practical guide to understanding your <span className="it">cycle.</span></h2>
            <p>A curated read on what your body is doing in each phase, what to eat, when to move, and how to ask a doctor for what you need.
            </p>
          </div>
          <div className="signup-action">
            <a className="btn" href={AylaRouter.pathFor('waitlist')} onClick={(e) => { e.preventDefault(); setRoute('waitlist'); }}>
              Get the Cycle Guide <span className="arr">→</span>
            </a>
            <p className="signup-fine">
              {window.AYLA_WAITLIST?.FINE_PRINT}
            </p>
          </div>
        </div>
      </section>
    </div>);

}

window.Home = Home;