// home.jsx — homepage

// Shared scroll progress hook — returns pixels scrolled past the element's top
// (max(0, -rect.top)). Works for both top-of-page heroes (start at scrollY=0)
// and mid-page sections (engages once the element reaches the viewport top).
const useParallax = (ref) => {
  const [offset, setOffset] = React.useState(0);
  React.useEffect(() => {
    let ticking = false;
    const update = () => {
      ticking = false;
      if (!ref.current) return;
      const rect = ref.current.getBoundingClientRect();
      // Distance the element has been scrolled UP past viewport top.
      // 0 while element is below or at top of viewport.
      setOffset(Math.max(0, -rect.top));
    };
    const onScroll = () => { if (!ticking) { ticking = true; requestAnimationFrame(update); } };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', update);
    update();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', update);
    };
  }, [ref]);
  return offset;
};

// Hook variant for sections mid-page — returns viewport-relative rect.top.
// Useful for "as the section moves through viewport, glide the image" effect.
const useViewportTop = (ref) => {
  const [top, setTop] = React.useState(9999);
  React.useEffect(() => {
    let ticking = false;
    const update = () => {
      ticking = false;
      if (!ref.current) return;
      setTop(ref.current.getBoundingClientRect().top);
    };
    const onScroll = () => { if (!ticking) { ticking = true; requestAnimationFrame(update); } };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', update);
    update();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', update);
    };
  }, [ref]);
  return top;
};

const Reveal = ({ children, as: As = 'div', delay = 0, className = '', ...rest }) => {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          setTimeout(() => setShown(true), delay);
          io.disconnect();
        }
      });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return (
    <As ref={ref} className={`reveal ${shown ? 'reveal--in' : ''} ${className}`} {...rest}>
      {children}
    </As>
  );
};

const Hero = ({ variant, image }) => {
  const [loaded, setLoaded] = React.useState(false);
  const ref = React.useRef(null);
  const y = useParallax(ref);
  React.useEffect(() => { const t = setTimeout(() => setLoaded(true), 60); return () => clearTimeout(t); }, []);

  const enableGlide = variant !== 'split';
  const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
  const offset = enableGlide ? y : 0;

  // Image lags more (deeper plate), text lags less (closer plate)
  const mediaTransform = `translate3d(0, ${offset * 0.38}px, 0) scale(${loaded ? 1 + offset * 0.00015 : 1.08})`;
  const contentTransform = `translate3d(0, ${offset * 0.18}px, 0)`;
  const metaTransform = `translate3d(0, ${offset * 0.10}px, 0)`;
  const scrollCueTransform = `translate3d(-50%, ${offset * 0.05}px, 0)`;
  const contentOpacity = Math.max(0, 1 - offset / (vh * 0.85));
  const veilOpacity = Math.min(1, 1 + offset * 0.0006);

  if (variant === 'split') {
    return (
      <section className={`hero hero--split ${loaded ? 'hero--loaded' : ''}`}>
        <div className="hero__media">
          <img src={image} alt="" />
        </div>
        <div className="hero__content">
          <div className="hero__eyebrow">Sri Lanka · Est. 2014</div>
          <h1 className="hero__title">Luxury journeys <em>through</em> Sri Lanka.</h1>
          <p className="hero__sub">An island of leopards, lost kingdoms and barefoot reefs — crafted into private journeys for those who travel slowly and notice everything.</p>
          <div className="hero__actions">
            <button className="btn btn--gold btn--lg" onClick={() => window.__nav('contact')}>
              Plan Your Journey <span className="btn__arrow">→</span>
            </button>
            <button className="btn btn--lg" onClick={() => window.__nav('tours')}>View Journeys</button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section ref={ref} className={`hero ${variant === 'still' ? 'hero--still' : ''} ${loaded ? 'hero--loaded' : ''}`}>
      <div className="hero__media" style={{ transform: mediaTransform, willChange: 'transform' }}>
        <img src={image} alt="Sri Lanka tea country at dawn" />
      </div>
      <div className="hero__veil" style={{ opacity: veilOpacity }}></div>
      <div className="hero__meta" style={{ transform: metaTransform, willChange: 'transform' }}>
        <span><i>N° 01</i></span>
        <span>06° 56' N · 79° 51' E</span>
        <span>Featured · The Highland Passage</span>
      </div>
      <div className="wrap hero__content" style={{ transform: contentTransform, opacity: contentOpacity, willChange: 'transform, opacity' }}>
        <div className="hero__eyebrow">A Private Travel Company · Colombo</div>
        <h1 className="hero__title">Luxury journeys <em>through</em> Sri Lanka.</h1>
        <p className="hero__sub">An island of leopards, lost kingdoms and barefoot reefs — crafted into private journeys for those who travel slowly and notice everything.</p>
        <div className="hero__actions">
          <button className="btn btn--gold btn--lg" onClick={() => window.__nav('contact')}>
            Plan Your Journey <span className="btn__arrow">→</span>
          </button>
          <button className="btn btn--lg" onClick={() => window.__nav('tours')}>View Journeys</button>
        </div>
      </div>
      <div className="hero__scroll" style={{ transform: scrollCueTransform, opacity: Math.max(0, 1 - offset / 240) }}>Scroll</div>
    </section>
  );
};

const Intro = () => (
  <section className="intro wrap">
    <Reveal>
      <div className="intro__rule"></div>
      <p className="intro__quote">We craft <em>tailor-made</em> journeys, designed around how you travel — not where the rest of the world goes.</p>
      <p className="intro__sig">— The Studio, Colombo</p>
    </Reveal>
  </section>
);

const ExperienceCard = ({ x, num }) => (
  <Reveal as="article" className="xcard" delay={num * 80}
    style={{ cursor: 'pointer' }}
    onClick={() => x.articleId && window.__nav('article', x.articleId)}>
    <img className="xcard__img" src={x.img} alt={x.title} loading="lazy" />
    <div className="xcard__veil"></div>
    <div className="xcard__body">
      <span className="xcard__num">N° {x.num}</span>
      <h3 className="xcard__title">{x.title}</h3>
      <span className="xcard__sub">{x.sub}</span>
      <span className="xcard__cta">Discover →</span>
    </div>
  </Reveal>
);

const Experiences = ({ layout = 'grid' }) => {
  const cls = layout === 'mosaic' ? 'experiences experiences--mosaic'
            : layout === 'two-up' ? 'experiences experiences--two-up'
            : 'experiences';
  return (
    <section className="section">
      <div className="wrap">
        <Reveal>
          <div className="sec-head">
            <div className="sec-head__left">
              <span className="sec-head__num">N° 02 — Experiences</span>
              <h2 className="sec-head__title">Four worlds, <em>one island.</em></h2>
            </div>
            <p className="sec-head__right">From the leopards of Yala to the cloud-line bungalows of the Hill Country — Sri Lanka fits a continent's worth of variety into its compact shores. These are the four we return to most.</p>
          </div>
        </Reveal>
        <div className={cls}>
          {EXPERIENCES.map((x, i) => <ExperienceCard key={x.num} x={x} num={i} />)}
        </div>
      </div>
    </section>
  );
};

const ItineraryRow = ({ it, idx }) => (
  <Reveal as="article" className={`itinerary ${idx % 2 === 1 ? 'itinerary--reverse' : ''}`}>
    <div className="itinerary__media">
      <img src={it.img} alt={it.title} loading="lazy" />
      <span className="itinerary__tag">{it.tag}</span>
    </div>
    <div className="itinerary__body">
      <div className="itinerary__no">N° {it.no}</div>
      <h3 className="itinerary__title">{it.title}</h3>
      <p className="itinerary__lede">{it.poetic}</p>
      <div className="itinerary__meta">
        <div className="itinerary__meta-row">
          <span className="itinerary__meta-lbl">Duration</span>
          <span className="itinerary__meta-val">{it.duration}</span>
        </div>
        {it.highlights && (
          <div className="itinerary__meta-row">
            <span className="itinerary__meta-lbl">Highlights</span>
            <span className="itinerary__meta-val itinerary__highlights">{it.highlights}</span>
          </div>
        )}
      </div>
      <button className="ulink" onClick={() => window.__nav('detail', it.id)}>
        View this Journey →
      </button>
    </div>
  </Reveal>
);

const SignatureItineraries = () => (
  <section className="section section--tight">
    <div className="wrap">
      <Reveal>
        <div className="sec-head">
          <div className="sec-head__left">
            <span className="sec-head__num">N° 03 — Signature</span>
            <h2 className="sec-head__title">Signature <em>itineraries.</em></h2>
          </div>
          <p className="sec-head__right">A small collection of journeys we have refined over a decade. Each is a starting point — to be edited, lengthened, reshaped entirely. None of our guests travels exactly the same route.</p>
        </div>
      </Reveal>
      {ITINERARIES.map((it, i) => <ItineraryRow key={it.id} it={it} idx={i} />)}
    </div>
  </section>
);

const WhyIcon = ({ kind }) => {
  // Minimal line glyphs only — no illustrative SVG
  const paths = {
    car: <><circle cx="12" cy="12" r="11" /><path d="M6 14h12M9 14v3M15 14v3M7 14l2-5h6l2 5" /></>,
    bed: <><circle cx="12" cy="12" r="11" /><path d="M5 16V9M19 16V9M5 13h14M5 16h14" /></>,
    map: <><circle cx="12" cy="12" r="11" /><path d="M9 7v10M15 9v10M9 7l6 2M15 17l-6-2M15 9l4-2v10l-4 2M9 7L5 9v10l4-2" /></>,
    bell: <><circle cx="12" cy="12" r="11" /><path d="M9 14V11a3 3 0 016 0v3l1 2H8l1-2zM11 17h2" /></>,
  };
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
      {paths[kind]}
    </svg>
  );
};

const Why = () => {
  const icons = ['car', 'bed', 'map', 'bell'];
  return (
    <section className="why">
      <div className="wrap">
        <Reveal>
          <div className="sec-head">
            <div className="sec-head__left">
              <span className="sec-head__num">N° 04 — Why Serendria</span>
              <h2 className="sec-head__title">The quiet <em>details.</em></h2>
            </div>
            <p className="sec-head__right">Luxury, to us, is not a thread count. It is the chauffeur who knows the back road. The estate manager who remembers your morning coffee from yesterday. The detail you didn't have to ask for.</p>
          </div>
        </Reveal>
        <div className="why__grid">
          {WHY.map((w, i) => (
            <Reveal key={w.num} as="div" className="why__item" delay={i * 80}>
              <div className="why__icon"><WhyIcon kind={icons[i]} /></div>
              <span className="why__num">N° {w.num}</span>
              <h3 className="why__title">{w.title}</h3>
              <p className="why__copy">{w.body}</p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
};

const Testimonials = () => {
  const [i, setI] = React.useState(0);
  const t = TESTIMONIALS[i];
  React.useEffect(() => {
    const id = setInterval(() => setI(x => (x + 1) % TESTIMONIALS.length), 7500);
    return () => clearInterval(id);
  }, []);
  return (
    <section className="testimonials">
      <div className="wrap">
        <Reveal>
          <div className="sec-head" style={{marginBottom: 56}}>
            <div className="sec-head__left">
              <span className="sec-head__num">N° 05 — Guests</span>
              <h2 className="sec-head__title">In their <em>own words.</em></h2>
            </div>
          </div>
        </Reveal>
        <Reveal>
          <div className="testimonial">
            <p className="testimonial__quote" key={i}>"{t.quote}"</p>
            <div className="testimonial__rule"></div>
            <div className="testimonial__name">{t.name}</div>
            <div className="testimonial__meta">{t.meta}</div>
            <div className="testimonial__dots">
              {TESTIMONIALS.map((_, idx) => (
                <button key={idx} className={`testimonial__dot ${idx === i ? 'testimonial__dot--active' : ''}`} onClick={() => setI(idx)} aria-label={`Testimonial ${idx + 1}`}></button>
              ))}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
};

const FinalCTA = () => {
  const ref = React.useRef(null);
  const top = useViewportTop(ref);
  const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
  // Drive parallax by the section's progress through viewport.
  // When the section first enters (top = vh), progress = 0.
  // When the section top hits viewport top, progress = 1.
  // When top is -h (scrolled past), progress > 1.
  const progress = Math.max(-0.5, Math.min(1.5, 1 - top / vh));
  // Image moves slower than scroll — glides upward as section passes through
  const mediaY = progress * 80;
  const contentY = progress * 30;

  return (
    <section ref={ref} className="final-cta">
      <div className="final-cta__media" style={{ transform: `translate3d(0, ${mediaY}px, 0) scale(1.08)`, willChange: 'transform' }}>
        <img src={IMG.cta} alt="" loading="lazy" />
      </div>
      <div className="final-cta__veil"></div>
      <div className="final-cta__content" style={{ transform: `translate3d(0, ${contentY}px, 0)`, willChange: 'transform' }}>
        <span className="eyebrow" style={{color: '#C6A96B'}}>N° 06 — Begin</span>
        <h2 className="final-cta__title">Start planning <em>your journey.</em></h2>
        <p className="final-cta__sub">A single conversation, then a private proposal within five days. There is no fee to enquire — and no obligation to travel.</p>
        <div style={{display:'flex', gap:16, justifyContent:'center', flexWrap:'wrap'}}>
          <button className="btn btn--gold btn--lg" onClick={() => window.__nav('contact')}>
            Design My Journey <span className="btn__arrow">→</span>
          </button>
          <button className="btn btn--lg" onClick={() => window.__nav('tours')}>Browse Journeys</button>
        </div>
      </div>
    </section>
  );
};

const HomePage = ({ tweaks }) => {
  const heroImage = tweaks.heroImage || IMG.hero;
  return (
    <>
      <Hero variant={tweaks.heroVariant} image={heroImage} />
      <Intro />
      <Experiences layout={tweaks.experienceLayout} />
      <SignatureItineraries />
      <Why />
      <Testimonials />
      <FinalCTA />
    </>
  );
};

Object.assign(window, { HomePage, Reveal, useParallax, useViewportTop, FinalCTA });
