/* global React, PH, MountainLayer, PeaksLayer */
const { useEffect, useRef, useState } = React;

/* ============ scroll reveal hook ============ */
function useReveal(){
  useEffect(() => {
    let raf = 0;
    const check = () => {
      const wh = window.innerHeight;
      document.querySelectorAll(".reveal:not(.in), .words:not(.in)").forEach(el => {
        const r = el.getBoundingClientRect();
        // visible when top is within 92% of viewport
        if (r.top < wh * 0.92){
          el.classList.add("in");
        }
      });
      raf = 0;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(check); };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    // initial pass + one delayed pass after layout settles
    check();
    const t1 = setTimeout(check, 80);
    const t2 = setTimeout(check, 320);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      cancelAnimationFrame(raf);
      clearTimeout(t1); clearTimeout(t2);
    };
  }, []);
}

/* ============ parallax hook ============ */
function useParallax(){
  useEffect(() => {
    let raf = 0;
    const tick = () => {
      const y = window.scrollY || 0;
      document.querySelectorAll("[data-parallax]").forEach(el => {
        const s = parseFloat(el.dataset.parallax);
        el.style.transform = `translate3d(0, ${y * s}px, 0)`;
      });
      raf = 0;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(tick); };
    window.addEventListener("scroll", onScroll, { passive: true });
    tick();
    return () => { window.removeEventListener("scroll", onScroll); cancelAnimationFrame(raf); };
  }, []);
}

/* ============ words splitter ============ */
function flattenText(n){
  if (n == null || typeof n === "boolean") return "";
  if (typeof n === "string" || typeof n === "number") return String(n);
  if (Array.isArray(n)) return n.map(flattenText).join("");
  if (n.props && n.props.children != null) return flattenText(n.props.children);
  return "";
}
function Words({ children, className = "" }){
  const text = flattenText(children);
  const words = text.split(/(\s+)/);
  return (
    <span className={`words ${className}`}>
      {words.map((w, i) => /\s+/.test(w) ? <React.Fragment key={i}>{w}</React.Fragment> : <span key={i} className="w">{w}</span>)}
    </span>
  );
}

/* ============ NAV ============ */
function Nav(){
  return (
    <nav className="nav">
      <div className="nav-l">
        <span className="mark">sansuri.</span>
      </div>
      <div className="nav-r">
        <a href="#stay">stay</a>
        <a href="#amenities">house</a>
        <a href="#workcation">workcation</a>
        <a href="#village">village</a>
        <a href="#book"><span className="dot"></span>book a pause</a>
      </div>
    </nav>
  );
}

/* ============ HERO ============ */
function Hero(){
  return (
    <section className="hero" id="top">
      <div className="layers">
        <div className="sun" data-parallax="0.18"></div>
        <PeaksLayer className="range-1" />
        <div data-parallax="0.06"><MountainLayer kind="far" fill="#9CA39C" opacity={.85} className="range-2" /></div>
        <div data-parallax="0.14"><MountainLayer kind="mid" fill="#5C6B57" opacity={.95} className="range-3" /></div>
        <div data-parallax="0.22"><MountainLayer kind="near" fill="#2A3528" className="range-4" /></div>
      </div>

      <div className="hero-content">
        <header className="hero-meta">
          <span>est. 2019 · pedong, kalimpong</span>
          <span>n 27.151° · e 88.601°</span>
          <span>elev. 5,400 ft</span>
        </header>

        <h1 className="hero-title">
          sansuri<span className="it">.</span>
        </h1>

        <div className="hero-bot">
          <div className="col">
            <h6>The brief</h6>
            <p>A small hill resort tucked into the eastern himalayan foothills — three rooms, one mountain view, slow days on tap.</p>
          </div>
          <div className="col">
            <h6>The view</h6>
            <p>Kanchenjunga, third-tallest mountain on earth, framed straight from your bed at 5:42 am sunrise.</p>
          </div>
          <div className="col">
            <h6>The promise</h6>
            <p>Stay a while. Take a story home. Pause here, breathe peace, live light.</p>
          </div>
        </div>
      </div>

      <div className="hero-scrollcue"><span>scroll</span><span className="l"></span><span>↓</span></div>
    </section>
  );
}

/* ============ MARQUEE ============ */
function Marquee(){
  const items = ["pause here", "breathe peace", "live light", "stay a while", "take a story home"];
  const Run = () => (
    <span>
      {items.map((t, i) => (
        <React.Fragment key={i}>
          <span>{t}</span>
          <span className="star">✦</span>
        </React.Fragment>
      ))}
    </span>
  );
  return (
    <div className="marquee">
      <div className="marquee-track">
        <Run /><Run />
      </div>
    </div>
  );
}

/* ============ PAUSE ============ */
function Pause(){
  return (
    <section className="section">
      <div className="pause">
        <div>
          <div className="eyebrow reveal">the place</div>
          <p className="lead reveal">
            <Words>Three hours from siliguri, past the last petrol pump, where the road bends into pine and prayer flags —</Words>
            <em> <Words>a slow house with a tin roof and a view that does most of the talking.</Words></em>
          </p>
        </div>
        <div className="stats">
          <div className="stat reveal"><div className="num">5,400<span className="u">ft</span></div><div className="lab">Elevation</div></div>
          <div className="stat reveal reveal-d2"><div className="num">3<span className="u">hrs</span></div><div className="lab">From Siliguri / NJP</div></div>
          <div className="stat reveal reveal-d3"><div className="num">8,586<span className="u">m</span></div><div className="lab">Kanchenjunga peak</div></div>
          <div className="stat reveal reveal-d4"><div className="num">3<span className="u">rooms</span></div><div className="lab">Sleeps 8 max</div></div>
        </div>
      </div>
    </section>
  );
}

/* ============ VIEW (sticky scale-up) ============ */
function ViewSection(){
  const stageRef = useRef(null);
  const frameRef = useRef(null);
  useEffect(() => {
    let raf = 0;
    const tick = () => {
      const stage = stageRef.current; const frame = frameRef.current;
      if (!stage || !frame) return;
      const r = stage.getBoundingClientRect();
      const total = r.height - window.innerHeight;
      const progressed = Math.min(1, Math.max(0, -r.top / total));
      // width grows from 56vw -> 100vw
      const w = 56 + progressed * 44;
      const radius = 6 - progressed * 6;
      frame.style.width = `${w}vw`;
      frame.style.borderRadius = `${radius}px`;
      raf = 0;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(tick); };
    window.addEventListener("scroll", onScroll, { passive: true });
    tick();
    return () => { window.removeEventListener("scroll", onScroll); cancelAnimationFrame(raf); };
  }, []);
  return (
    <section className="view">
      <div className="view-stage" ref={stageRef}>
        <div className="view-pin">
          <div className="view-frame" ref={frameRef}>
            <PH dark label="kanchenjunga · 5:42am · sunrise" src="assets/view-kanchenjunga-sunrise.png" alt="Kanchenjunga sunrise over layered Himalayan ridges" />
            <div className="view-overlay">
              <div className="top">
                <span>view 01 / 04</span>
                <span>27.151° n</span>
              </div>
              <div className="top">
                <span className="name">the third pole.</span>
              </div>
            </div>
          </div>
          <div className="view-caption">
            <span>scroll to widen</span>
            <span className="big">8,586 <em style={{fontStyle:'italic', color:'var(--terra)'}}>m</em></span>
            <span>khangchendzonga</span>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ AMENITIES ============ */
function Amenities(){
  const cards = [
    { n: "01", title: <>mountain <em>wifi.</em></>, desc: "Solid 50 mbps fibre. Yes, it works at 5,400 ft. Workcations welcome.", glyph: "✦", span: "span-5" },
    { n: "02", title: <><em>bonfire</em> nights.</>, desc: "Pine wood, stories, momos. The fire goes out when you say so.", glyph: "♨", span: "span-4" },
    { n: "03", title: <>games.</>, desc: "Carrom, scrabble, chess, an upright piano nobody plays well.", glyph: "◆", span: "span-3", noTv: false },
    { n: "04", title: <>NO TV.</>, desc: "Intentional. The window is the screen. Sunrise is the only thing on tonight.", glyph: "×", span: "span-4", noTv: true },
    { n: "05", title: <><em>home</em> kitchen.</>, desc: "Whatever ma made. Daal-bhaat, thukpa, momos, hot chai every two hours.", glyph: "❋", span: "span-4" },
    { n: "06", title: <>yoga deck.</>, desc: "An open-air platform facing east. Mats, a singing bowl, no instructors — you find it yourself.", glyph: "◯", span: "span-4" },
    { n: "07", title: <>birding <em>trails.</em></>, desc: "Sunbirds, niltavas, the occasional yellow-billed blue magpie if you're patient.", glyph: "↗", span: "span-6" },
    { n: "08", title: <>dog-friendly.</>, desc: "Two house dogs, Momo & Bhalu. Bring yours. They'll figure it out.", glyph: "🐾", span: "span-3" },
    { n: "09", title: <>sunrise <em>tea.</em></>, desc: "5:30 am, knock on door, hot kettle, two cups. No questions asked.", glyph: "☼", span: "span-3" },
  ];
  return (
    <section className="section amen" id="amenities">
      <div className="amen-head">
        <div>
          <div className="eyebrow reveal">the house</div>
          <h2 className="display reveal">
            <Words>nothing fancy.</Words><br/>
            <span className="it terra"><Words>just enough.</Words></span>
          </h2>
        </div>
        <p className="sub reveal reveal-d2">No infinity pool. No spa menu. A working fireplace, hot food, a slow afternoon — the kind of luxury you can't book a five-star for.</p>
      </div>

      <div className="amen-grid">
        {cards.map((c, i) => (
          <div key={i} className={`amen-card ${c.span} ${c.noTv ? "no-tv" : ""} reveal`} style={{ transitionDelay: `${(i % 3) * 0.08}s` }}>
            <div className="amen-num">{c.n} / 09</div>
            <div className="glyph">{c.glyph}</div>
            <div>
              <h3>{c.title}</h3>
              <p>{c.desc}</p>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ============ WORKCATION ============ */
function Workcation(){
  const items = [
    ["01", "Fibre wifi", "50 mbps. uncapped."],
    ["02", "Power", "battery backup all day. zero load shedding for you."],
    ["03", "Desk views", "writing tables face the kanchenjunga side."],
    ["04", "Long stays", "weekly + monthly tariffs. 20% off after 7 nights."],
    ["05", "Quiet hours", "10 pm – 8 am. respected by the dogs too, mostly."],
  ];
  return (
    <section className="work" id="workcation">
      <div className="work-grid">
        <div className="work-img reveal">
          <PH dark label="workcation · desk by the window" src="assets/workcation-desk-window.png" alt="Wooden work desk by a mountain-facing resort window" style={{height:'100%'}} />
        </div>
        <div className="work-copy">
          <div className="eyebrow reveal" style={{color: "var(--terra)"}}>workcation</div>
          <h2 className="reveal">work like<br/><em>nobody's</em><br/>watching.</h2>
          <p className="lede reveal reveal-d2">Because nobody actually is. The valley has signal, your laptop has battery, and the Kanchenjunga is a really, really good monitor wallpaper.</p>
          <ul className="work-bullets">
            {items.map(([n, k, v], i) => (
              <li key={i} className="reveal" style={{ transitionDelay: `${i * 0.06}s` }}>
                <span className="n">{n}</span>
                <span className="k">{k}</span>
                <span className="v">{v}</span>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

/* ============ GALLERY (horizontal scroll) ============ */
function Gallery(){
  const trackRef = useRef(null);
  const sectionRef = useRef(null);
  useEffect(() => {
    let raf = 0;
    const tick = () => {
      const sec = sectionRef.current; const track = trackRef.current;
      if (!sec || !track) return;
      const r = sec.getBoundingClientRect();
      const range = window.innerHeight + r.height;
      const p = Math.min(1, Math.max(0, (window.innerHeight - r.top) / range));
      const max = track.scrollWidth - window.innerWidth;
      track.style.transform = `translate3d(${-p * max * 0.7}px, 0, 0)`;
      raf = 0;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(tick); };
    window.addEventListener("scroll", onScroll, { passive: true });
    tick();
    return () => { window.removeEventListener("scroll", onScroll); cancelAnimationFrame(raf); };
  }, []);
  const cards = [
    { l: "the gazebo · red roof", k: "wide", src: "assets/gallery-gazebo-red-roof.png", alt: "Warmly lit red-roof gazebo in a pine hillside garden" },
    { l: "kanchenjunga · dawn", k: "tall", src: "assets/gallery-kanchenjunga-dawn.png", alt: "Kanchenjunga at dawn above misty Himalayan ridges" },
    { l: "common room · piano", k: "", src: "assets/gallery-common-room.png", alt: "Cozy wood common room with piano and fireplace" },
    { l: "kitchen · momo morning", k: "tall", src: "assets/gallery-kitchen-momos.png", alt: "Steaming momos and chai in a mountain homestay kitchen" },
    { l: "trail · pine + prayer flags", k: "wide", src: "assets/gallery-pine-trail.png", alt: "Pine forest trail with prayer flags and distant hills" },
    { l: "bonfire · night 03", k: "", src: "assets/gallery-bonfire-night.png", alt: "Evening bonfire seating in a pine garden" },
    { l: "deck · monsoon clouds", k: "tall", src: "assets/gallery-yoga-deck.png", alt: "Open wooden yoga deck facing monsoon clouds and green hills" },
    { l: "momo & bhalu · house dogs", k: "", src: "assets/gallery-house-dogs.png", alt: "Two friendly house dogs resting in the resort garden" },
  ];
  return (
    <section className="gallery" ref={sectionRef}>
      <div className="gallery-head">
        <div>
          <div className="eyebrow reveal">field notes</div>
          <h2 className="display reveal"><Words>moments,</Words> <span className="it terra"><Words>not posts.</Words></span></h2>
        </div>
        <div className="reveal" style={{fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--ink-soft)"}}>scroll → continues sideways</div>
      </div>
      <div className="gallery-track" ref={trackRef}>
        {cards.map((c, i) => (
          <div key={i} className={`gallery-card ${c.k}`}>
            <PH label={c.l} src={c.src} alt={c.alt} />
            <div className="meta">
              <span>frame {String(i+1).padStart(2, "0")} / {String(cards.length).padStart(2,"0")}</span>
              <span>kalimpong, wb</span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ============ STAY (rooms) ============ */
function Stay(){
  const rooms = [
    { name: <>the <em>gazebo</em> room</>, ph: "tin-roof room · valley facing", src: "assets/room-gazebo.png", alt: "Cozy wooden gazebo room with valley-facing window", specs: ["king bed", "valley view", "wifi", "writing desk"], price: "₹4,800", from: "/ night, double" },
    { name: <>the <em>pine</em> room</>, ph: "wood-panel · garden facing", src: "assets/room-pine.png", alt: "Wood-paneled pine room with balcony doors to the garden", specs: ["queen bed", "private balcony", "wifi", "fireplace"], price: "₹5,400", from: "/ night, double" },
    { name: <>the <em>peak</em> suite</>, ph: "top floor · kanchenjunga", src: "assets/room-peak-suite.png", alt: "Peak suite with bed and sunrise mountain view", specs: ["king bed", "kanchenjunga", "wifi", "tub"], price: "₹7,200", from: "/ night, double" },
  ];
  return (
    <section className="stay" id="stay">
      <div className="stay-head">
        <div>
          <div className="eyebrow reveal">three rooms.</div>
          <h2 className="display reveal" style={{color: "var(--paper)"}}><Words>pick a window,</Words> <span className="it terra"><Words>pick a story.</Words></span></h2>
        </div>
        <p style={{fontFamily:"var(--serif)", fontStyle:"italic", fontSize: 22, color: "rgba(236,228,210,.6)", maxWidth: 320}} className="reveal reveal-d2">Capacity capped at eight humans, two house dogs, one mountain.</p>
      </div>
      <div className="stay-grid">
        {rooms.map((r, i) => (
          <article key={i} className="room reveal" style={{ transitionDelay: `${i * 0.08}s` }}>
            <PH dark label={r.ph} src={r.src} alt={r.alt} />
            <h3>{r.name}</h3>
            <div className="specs">{r.specs.map((s, j) => <span key={j}>{s}</span>)}</div>
            <div className="price">
              <span>from</span>
              <span className="v">{r.price.slice(0,1)}<span className="terra">{r.price.slice(1,2)}</span>{r.price.slice(2)} <span style={{fontFamily:"var(--mono)", fontSize:11, opacity:.6}}>{r.from}</span></span>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

/* ============ QUOTE ============ */
function Quote(){
  return (
    <section className="quote">
      <p className="big reveal">
        <Words>"i came for two nights.</Words> <em><Words>i stayed eleven.</Words></em> <Words>nobody asked why."</Words>
      </p>
      <div className="credit reveal reveal-d2">— guest log, room 02 · march 2026</div>
    </section>
  );
}

/* ============ VILLAGE ============ */
function Village(){
  const rows = [
    ["3 hr", "From NJP / Siliguri", "drive"],
    ["1.5 hr", "From Kalimpong town", "shared cab"],
    ["20 min", "Damsang fort ruins", "walk"],
    ["45 min", "Silent monastery", "walk + climb"],
    ["1 hr", "Tinchuley orange orchards", "drive"],
  ];
  return (
    <section className="village" id="village">
      <div className="village-grid">
        <div className="map reveal">
          <PH label="hand-drawn map · pedong + around" src="assets/village-map-illustration.png" alt="Hand-drawn illustrated map of Pedong hill walks and nearby landmarks" style={{height:'100%'}} />
        </div>
        <div>
          <div className="eyebrow reveal">the village</div>
          <h2 className="display reveal"><Words>pedong is</Words> <span className="it terra"><Words>where the road</Words></span> <Words>thinks twice.</Words></h2>
          <p style={{fontFamily:"var(--serif)", fontStyle:"italic", fontSize: 22, color: "var(--ink-soft)", marginTop: 28, maxWidth: 460}} className="reveal reveal-d2">A two-street hamlet in kalimpong district, west bengal. Older than the road that finds it. Lepcha and bhutia neighbours, an old monastery on the hill, and a post office that still uses ink stamps.</p>
          <div className="village-pts">
            {rows.map(([km, place, from], i) => (
              <div key={i} className="row reveal" style={{ transitionDelay: `${i * 0.06}s` }}>
                <span className="km">{km}</span>
                <span className="place">{place}</span>
                <span className="from">{from}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ CTA / Book ============ */
function Cta(){
  return (
    <section className="cta" id="book">
      <div className="cta-grid">
        <div>
          <div className="eyebrow reveal" style={{color:"var(--paper)"}}>book a pause</div>
          <h2 className="reveal">stay<br/><em>a while.</em><br/>↗</h2>
        </div>
        <form className="cta-form reveal reveal-d2" onSubmit={(e) => { e.preventDefault(); alert("Booking request received. We'll write back within a day."); }}>
          <label>name <input defaultValue="" placeholder="your name" /></label>
          <label>email <input type="email" placeholder="you@somewhere" /></label>
          <div className="row">
            <label>arrival <input type="date" /></label>
            <label>nights <select><option>2</option><option>3</option><option>5</option><option>7</option><option>14+</option></select></label>
          </div>
          <label>room <select><option>any window</option><option>the gazebo</option><option>the pine</option><option>the peak</option></select></label>
          <button type="submit" className="cta-btn">request a stay <span className="arr">→</span></button>
        </form>
      </div>
    </section>
  );
}

/* ============ FOOTER ============ */
function Foot(){
  return (
    <footer className="foot">
      <div className="foot-mono">sansuri hill resort · pedong, kalimpong, west bengal · 734311</div>
      <div className="foot-mark">sans<em>uri.</em></div>
      <div className="foot-grid">
        <div>
          <h6>find us</h6>
          <p>upper pedong<br/>kalimpong, wb<br/>734311 · india</p>
        </div>
        <div>
          <h6>say hi</h6>
          <a href="mailto:hello@sansurihill.in">hello@sansurihill.in</a>
          <a href="tel:+919999999999">+91 99999 99999</a>
        </div>
        <div>
          <h6>follow</h6>
          <a href="#">@sansuri_hillresort</a>
          <a href="#">3 posts · 27 followers</a>
        </div>
        <div>
          <h6>hours</h6>
          <p>check in 14:00<br/>check out 11:00<br/>sunrise tea 5:30</p>
        </div>
      </div>
      <div className="foot-bot">
        <span>© 2026 sansuri hill resort</span>
        <span>built slow, in the hills.</span>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, Marquee, Pause, ViewSection, Amenities, Workcation, Gallery, Stay, Quote, Village, Cta, Foot, useReveal, useParallax });
