/* ============ HERO — Illustrated Forest Scene (Cozy Hollow style) ============ */

/* LCG for deterministic tree placement */
function lcg(seed) {
  let s = seed >>> 0;
  return () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 4294967296; };
}

/* PROPER multi-tier pine tree silhouette — trunk + 3 stacked triangular tiers */
function pineTree(cx, base, h, hw) {
  const tw = Math.max(3, hw * 0.1);
  const th = base - h * 0.15;   // where trunk meets lowest tier
  const r  = (x, y) => `${Math.round(x)},${Math.round(y)}`;
  // left side going up, right side mirrored going down
  return [
    `M${r(cx - tw, base)}`,
    `L${r(cx - tw, th)}`,                             // trunk top-left
    `L${r(cx - hw, th)}`,                             // tier 3 base-left (widest)
    `L${r(cx - hw * 0.40, base - h * 0.47)}`,         // tier 3 peak → notch in
    `L${r(cx - hw * 0.66, base - h * 0.41)}`,         // tier 2 base-left (step out = overlap)
    `L${r(cx - hw * 0.27, base - h * 0.69)}`,         // tier 2 peak → notch in
    `L${r(cx - hw * 0.45, base - h * 0.64)}`,         // tier 1 base-left (step out)
    `L${r(cx,             base - h)}`,                // apex
    `L${r(cx + hw * 0.45, base - h * 0.64)}`,
    `L${r(cx + hw * 0.27, base - h * 0.69)}`,
    `L${r(cx + hw * 0.66, base - h * 0.41)}`,
    `L${r(cx + hw * 0.40, base - h * 0.47)}`,
    `L${r(cx + hw, th)}`,
    `L${r(cx + tw, th)}`,
    `L${r(cx + tw, base)} Z`,
  ].join(' ');
}

/* Simple triangle rows for distant/mid background trees */
function genTrees(seed, baseY, count, minH, maxH, hw) {
  const rand = lcg(seed);
  const step = (1440 + 160) / count;
  let d = `M-80,${baseY + 80}`;
  for (let i = 0; i < count; i++) {
    const cx = -40 + i * step + (rand() - 0.5) * step * 0.4;
    const h  = minH + rand() * (maxH - minH);
    const w  = hw   * (0.55 + rand() * 0.9);
    d += ` L${Math.round(cx - w)},${baseY} L${Math.round(cx)},${Math.round(baseY - h)} L${Math.round(cx + w)},${baseY}`;
  }
  return d + ` L1520,${baseY + 80} L1520,700 L-80,700 Z`;
}

/* Left and right curtain trees — LARGE, viewBox 460×780 */
const LEFT_TREES  = [
  pineTree(260, 780, 700, 155),   // tallest: wide trunk, deep tiers
  pineTree( 60, 780, 540, 118),   // secondary, half off-screen left
  pineTree(390, 780, 360,  82),   // inward accent
];
const RIGHT_TREES = [             // mirrored layout
  pineTree(200, 780, 700, 155),
  pineTree(400, 780, 540, 118),
  pineTree( 70, 780, 360,  82),
];

function Hero() {
  const S = window.SITE;
  const contentRef = useRef(null);
  const bgRef      = useRef(null);
  const fgLRef     = useRef(null);
  const fgRRef     = useRef(null);

  useEffect(() => {
    let raf;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const y = window.scrollY;
        if (contentRef.current) {
          contentRef.current.style.transform = `translateY(${y * 0.18}px)`;
          contentRef.current.style.opacity   = Math.max(0, 1 - y / 560).toString();
        }
        if (bgRef.current) bgRef.current.style.transform = `translateY(${y * 0.10}px)`;
        // Left trees slide OUT to the left + fade
        const slideX = y * 0.55;
        const treeOp = Math.max(0, 1 - y / 340).toFixed(3);
        if (fgLRef.current) {
          fgLRef.current.style.transform = `translateX(-${slideX}px) translateY(${y * 0.12}px)`;
          fgLRef.current.style.opacity   = treeOp;
        }
        // Right trees slide OUT to the right + fade
        if (fgRRef.current) {
          fgRRef.current.style.transform = `translateX(${slideX}px) translateY(${y * 0.12}px)`;
          fgRRef.current.style.opacity   = treeOp;
        }
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => { window.removeEventListener("scroll", onScroll); cancelAnimationFrame(raf); };
  }, []);

  const waLink   = `https://wa.me/${S.contact.whatsapp}?text=${encodeURIComponent("Hi! I'd love to know about availability at The Last Stop Backpackers Hostel.")}`;
  const scrollTo = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 76, behavior: "smooth" });
  };

  /* Distant/mid background tree rows */
  const t1 = genTrees(7,  335, 34, 22,  58, 15);
  const t2 = genTrees(17, 362, 26, 40,  92, 25);
  const t3 = genTrees(31, 386, 20, 64, 138, 37);

  /* Clouds — 4 layers, different sizes and speeds */
  const clouds = [
    { w: 140, top: "48%", delay: "0s",   dur: "64s" },
    { w: 110, top: "54%", delay: "-26s", dur: "80s" },
    { w: 170, top: "44%", delay: "-46s", dur: "98s" },
    { w: 120, top: "58%", delay: "-16s", dur: "72s" },
  ];

  return (
    <section id="hero" className="fhero">

      {/* ── Sky ── */}
      <div className="fh-sky" />

      {/* ── Stars (dark) ── */}
      <div className="fh-stars">
        {Array.from({ length: 80 }).map((_, i) => (
          <span key={i} style={{
            left: `${(i * 37 + 9) % 100}%`, top: `${(i * 53 + 5) % 60}%`,
            animationDelay: `${(i % 9) * 0.42}s`,
            width: `${1.4 + (i % 3) * 0.8}px`, height: `${1.4 + (i % 3) * 0.8}px`,
          }} />
        ))}
      </div>

      {/* ── Aurora (dark) ── */}
      <div className="fh-aurora fh-a1" /><div className="fh-aurora fh-a2" />

      {/* ── Sun / Moon ── */}
      <div className="fh-celestial">
        <div className="fh-body" />
        <svg className="fh-rays" viewBox="0 0 240 240" aria-hidden="true">
          {Array.from({ length: 12 }).map((_, i) => {
            const a = (i * 30 - 90) * Math.PI / 180;
            return <line key={i} x1="120" y1="120"
              x2={120 + 96 * Math.cos(a)} y2={120 + 96 * Math.sin(a)}
              stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" opacity="0.32" />;
          })}
        </svg>
      </div>

      {/* ── Full illustrated clouds (overflow visible = no clipping) ── */}
      {clouds.map((c, i) => {
        const H = Math.round(c.w * 0.58);
        return (
          <div key={i} className="fh-cloud" style={{ top: c.top, width: c.w, animationDelay: c.delay, animationDuration: c.dur }}>
            <svg viewBox={`0 0 ${c.w} ${H}`} width="100%" overflow="visible" aria-hidden="true">
              {/* bottom base — full width flat ellipse */}
              <ellipse cx={c.w * .50} cy={H * .84} rx={c.w * .47} ry={H * .18} fill="currentColor"/>
              {/* left puff */}
              <ellipse cx={c.w * .17} cy={H * .62} rx={c.w * .15} ry={H * .28} fill="currentColor"/>
              {/* left-center puff */}
              <ellipse cx={c.w * .35} cy={H * .48} rx={c.w * .19} ry={H * .35} fill="currentColor"/>
              {/* center puff — tallest */}
              <ellipse cx={c.w * .54} cy={H * .42} rx={c.w * .21} ry={H * .40} fill="currentColor"/>
              {/* right-center */}
              <ellipse cx={c.w * .72} cy={H * .50} rx={c.w * .18} ry={H * .33} fill="currentColor"/>
              {/* right puff */}
              <ellipse cx={c.w * .88} cy={H * .62} rx={c.w * .14} ry={H * .25} fill="currentColor"/>
            </svg>
          </div>
        );
      })}

      {/* ── Birds (light) ── */}
      {[{l:"12%",t:"24%"},{l:"23%",t:"18%"},{l:"38%",t:"27%"},{l:"56%",t:"20%"},{l:"71%",t:"14%"}].map((b, i) => (
        <svg key={i} className="fh-bird" viewBox="0 0 30 14" width="26" height="12" aria-hidden="true"
          style={{ left: b.l, top: b.t, animationDelay: `${i * 0.85}s` }}>
          <path d="M1,7 Q6,1 12,5 Q15,7 18,5 Q24,1 29,7" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
        </svg>
      ))}

      {/* ── Background forest: mountains + distant/mid rows ── */}
      <svg ref={bgRef} className="fh-bg" viewBox="0 0 1440 500" preserveAspectRatio="xMidYMax slice" aria-hidden="true">
        <path d="M0,500 C180,305 440,355 720,270 C1000,185 1265,255 1440,215 L1440,500 Z" className="fh-mt" />
        <path d={t1} className="fh-tr fh-t1" />
        <path d={t2} className="fh-tr fh-t2" />
        <path d={t3} className="fh-tr fh-t3" />
      </svg>

      {/* ── Left forest curtain — large multi-tier pine trees ── */}
      <svg ref={fgLRef} className="fh-curtain fh-cl" viewBox="0 0 460 780" preserveAspectRatio="xMinYMax meet" aria-hidden="true">
        {LEFT_TREES.map((d, i) => <path key={i} d={d} className="fh-tr fh-t4" />)}
      </svg>

      {/* ── Right forest curtain — mirrored ── */}
      <svg ref={fgRRef} className="fh-curtain fh-cr" viewBox="0 0 460 780" preserveAspectRatio="xMaxYMax meet" aria-hidden="true">
        {RIGHT_TREES.map((d, i) => <path key={i} d={d} className="fh-tr fh-t4" />)}
      </svg>

      {/* ── Fireflies (dark) ── */}
      <div className="fh-flies">
        {Array.from({ length: 18 }).map((_, i) => (
          <span key={i} className="fh-fly" style={{
            left: `${(i * 43 + 8) % 88}%`, bottom: `${8 + (i * 19) % 36}%`,
            animationDelay: `${i * 0.55}s`, animationDuration: `${2.4 + (i % 5) * 0.65}s`,
          }} />
        ))}
      </div>

      {/* ── Content ── */}
      <div className="fh-content container" ref={contentRef}>
        <Reveal as="span" className="eyebrow" style={{ justifyContent: "center" }}>{S.location}</Reveal>
        <Reveal as="h1" className="display hero-title" delay={80}>
          The Last Stop<br />before your <em className="muted-em">next adventure.</em>
        </Reveal>
        <Reveal as="p" className="hero-sub" delay={200}>
          Stay. Explore. Connect. Immerse in Auroville&rsquo;s spiritual energy, rooftop café evenings, and a community of seekers, nomads and adventurers.
        </Reveal>
        <Reveal className="hero-cta" delay={320}>
          <a href="#contact" onClick={scrollTo("contact")} className="btn btn-primary"><Icon name="calendar-check" /> Book Now</a>
          <a href="#rooms" onClick={scrollTo("rooms")} className="btn btn-ghost"><Icon name="bed" /> Explore Rooms</a>
          <a href={waLink} target="_blank" rel="noreferrer" className="btn btn-wa"><Icon name="whatsapp" /> WhatsApp Us</a>
        </Reveal>
      </div>

      <a href="#about" onClick={scrollTo("about")} className="scroll-ind" aria-label="Scroll down">
        <span className="mouse"><span className="dot" /></span>
        <span className="scroll-txt">scroll</span>
      </a>

      <style>{`
        /* ── HERO ── */
        .fhero { position: relative; height: 100vh; max-height: 100vh; overflow: hidden; display: flex; align-items: center; justify-content: center; }

        /* SKY */
        .fh-sky { position: absolute; inset: 0; z-index: 0; transition: background .9s var(--ease); }
        html[data-theme="light"] .fh-sky { background: linear-gradient(180deg,#4DA6D4 0%,#7EC4E8 16%,#B4DCED 34%,#F5C87A 58%,#F9E0A8 75%,var(--bg) 100%); }
        html[data-theme="dark"]  .fh-sky { background: linear-gradient(180deg,#030214 0%,#060428 28%,#0C0840 58%,#150B4E 76%,var(--bg) 100%); }

        /* STARS */
        .fh-stars { position: absolute; inset: 0; z-index: 1; opacity: 0; transition: opacity .8s; pointer-events: none; }
        html[data-theme="dark"] .fh-stars { opacity: 1; }
        .fh-stars span { position: absolute; border-radius: 50%; background:#fff; box-shadow:0 0 5px #b0ccff; animation: fhTwink 3s ease-in-out infinite; }
        @keyframes fhTwink { 0%,100%{ opacity:.15 } 50%{ opacity:1 } }

        /* AURORA */
        .fh-aurora { position: absolute; top:-6%; left:-10%; right:-10%; height:55vh; z-index:1; filter:blur(62px); opacity:0; transition:opacity .8s; pointer-events:none; }
        html[data-theme="dark"] .fh-aurora { opacity:.5; }
        .fh-a1 { background: radial-gradient(50% 80% at 28% 0%, rgba(54,230,236,.58), transparent 68%); animation: fhDrift 18s ease-in-out infinite; }
        .fh-a2 { background: radial-gradient(46% 80% at 74% 8%, rgba(255,95,180,.52), transparent 68%); animation: fhDrift 24s ease-in-out infinite reverse; }
        @keyframes fhDrift { 0%,100%{ transform:translateX(0) } 50%{ transform:translateX(55px) } }

        /* SUN / MOON */
        .fh-celestial { position: absolute; top:10%; left:50%; transform:translateX(-50%); z-index:2; }
        .fh-body { border-radius:50%; transition:all .9s var(--ease); }
        html[data-theme="light"] .fh-body { width:120px; height:120px; background:radial-gradient(circle at 42% 40%,#fffce4,#FFD05E 52%,rgba(255,180,20,0) 72%); box-shadow:0 0 0 24px rgba(255,218,70,.1),0 0 0 60px rgba(255,200,40,.04),0 0 140px 50px rgba(255,210,55,.4); }
        html[data-theme="dark"]  .fh-body { width:82px; height:82px; background:radial-gradient(circle at 36% 35%,#fefcff,#d4d4f8 54%,rgba(80,80,190,0) 72%); box-shadow:0 0 0 12px rgba(148,148,255,.1),0 0 80px 24px rgba(140,140,255,.3); }
        .fh-rays { position:absolute; inset:-60px; width:240px; height:240px; color:#FFD060; opacity:0; transition:opacity .9s; pointer-events:none; }
        html[data-theme="light"] .fh-rays { opacity:1; }

        /* CLOUDS — full puff, overflow visible so nothing clips */
        .fh-cloud { position:absolute; left:-420px; z-index:3; color:rgba(255,255,255,.95); animation:fhCloud linear infinite; transition:color .9s; }
        html[data-theme="dark"] .fh-cloud { color:rgba(48,32,80,.38); }
        @keyframes fhCloud { from{ transform:translateX(0) } to{ transform:translateX(calc(100vw + 480px)) } }

        /* BIRDS */
        .fh-bird { position:absolute; z-index:4; color:rgba(42,36,20,.44); opacity:0; transition:opacity .8s; animation:fhBird 4s ease-in-out infinite; }
        html[data-theme="light"] .fh-bird { opacity:1; }
        @keyframes fhBird { 0%,100%{ transform:translateY(0) } 50%{ transform:translateY(-9px) } }

        /* BACKGROUND FOREST — mountains + distant rows */
        .fh-bg { position:absolute; bottom:0; left:0; right:0; width:100%; height:clamp(140px,32vh,360px); z-index:5; will-change:transform; }
        html[data-theme="light"] .fh-mt { fill:#bcd6b4; opacity:.52; }
        html[data-theme="dark"]  .fh-mt { fill:#120D40; opacity:.88; }
        html[data-theme="light"] .fh-t1 { fill:#b2cc9e; }
        html[data-theme="light"] .fh-t2 { fill:#78a86a; }
        html[data-theme="light"] .fh-t3 { fill:#47744c; }
        html[data-theme="dark"]  .fh-t1 { fill:#0b0930; }
        html[data-theme="dark"]  .fh-t2 { fill:#0e0b34; filter:drop-shadow(0 -2px 12px rgba(54,230,236,.5)); }
        html[data-theme="dark"]  .fh-t3 { fill:#090820; filter:drop-shadow(0 -3px 18px rgba(155,107,255,.65)); }

        /* FOREGROUND CURTAIN TREES — large multi-tier silhouettes */
        .fh-curtain { position:absolute; bottom:0; z-index:7; will-change:transform,opacity; height:clamp(260px,58vh,640px); transition:opacity .05s linear; }
        .fh-cl { left:-2%;  width:clamp(160px,28vw,420px); }
        .fh-cr { right:-2%; width:clamp(160px,28vw,420px); }
        html[data-theme="light"] .fh-t4 { fill:#1C3A24; }
        html[data-theme="dark"]  .fh-t4 { fill:#04050E; filter:drop-shadow(0 -3px 16px rgba(54,230,236,.32)); }

        /* FIREFLIES */
        .fh-flies { position:absolute; inset:0; z-index:8; opacity:0; transition:opacity .8s; pointer-events:none; }
        html[data-theme="dark"] .fh-flies { opacity:1; }
        .fh-fly { position:absolute; width:4px; height:4px; border-radius:50%; background:#80f6c4; box-shadow:0 0 8px #44e2a8,0 0 18px rgba(110,240,155,.5); animation:fhFly ease-in-out infinite; }
        @keyframes fhFly { 0%{ transform:translate(0,0);opacity:0 } 20%{ opacity:1 } 50%{ transform:translate(15px,-22px);opacity:.85 } 80%{ opacity:1 } 100%{ transform:translate(-10px,12px);opacity:0 } }

        /* CONTENT */
        .fh-content { position:relative; z-index:10; text-align:center; padding-top:82px; padding-bottom:clamp(140px,30vh,360px); will-change:transform,opacity; width:100%; }
        .hero-title { font-size:clamp(2rem,5vw,4.8rem); color:var(--text); margin:16px auto 0; max-width:16ch; }
        html[data-theme="dark"] .hero-title { text-shadow:0 0 60px rgba(54,230,236,.2); }
        .hero-sub { color:var(--text-2); font-size:clamp(.92rem,1.4vw,1.15rem); max-width:520px; margin:18px auto 0; line-height:1.65; }
        .hero-cta { display:flex; gap:12px; justify-content:center; flex-wrap:wrap; margin-top:28px; }

        /* SCROLL INDICATOR */
        .scroll-ind { position:absolute; bottom:24px; left:50%; transform:translateX(-50%); z-index:10; display:flex; flex-direction:column; align-items:center; gap:8px; color:var(--text-2); }
        .mouse { width:24px; height:38px; border:2px solid var(--text-2); border-radius:14px; display:flex; justify-content:center; padding-top:6px; }
        .dot { width:4px; height:8px; border-radius:4px; background:var(--primary); animation:mscroll 1.6s var(--ease) infinite; }
        @keyframes mscroll { 0%{ transform:translateY(0);opacity:1 } 70%{ transform:translateY(12px);opacity:0 } 100%{ opacity:0 } }
        .scroll-txt { font-size:10px; letter-spacing:.25em; text-transform:uppercase; }
        /* ── Mobile: tablet ── */
        @media(max-width:900px){
          .fh-curtain { height:clamp(200px,44vh,480px); }
          .fh-cl,.fh-cr { width:clamp(130px,24vw,320px); }
          .fh-bg { height:clamp(120px,28vh,300px); }
          .hero-title { font-size:clamp(1.9rem,5.5vw,3.6rem); }
        }
        /* ── Mobile: phone ── */
        @media(max-width:600px){
          .fh-curtain { height:clamp(160px,36vh,340px); }
          .fh-cl,.fh-cr { width:clamp(100px,26vw,220px); }
          .fh-bg { height:clamp(100px,24vh,240px); }
          .fh-content { padding-top:86px; padding-bottom:clamp(130px,28vh,300px); }
          .hero-title { font-size:clamp(1.7rem,7vw,2.8rem); }
          .hero-sub { font-size:.9rem; padding:0 8px; }
          .hero-cta { gap:10px; }
          .hero-cta .btn { padding:12px 18px; font-size:13.5px; }
        }
        /* ── Mobile: small phone ── */
        @media(max-width:420px){
          .fh-cl,.fh-cr { width:clamp(88px,28vw,180px); }
          .fh-curtain { height:clamp(140px,32vh,280px); }
          .hero-title { font-size:clamp(1.55rem,8vw,2.2rem); }
          .hero-cta { flex-direction:column; align-items:center; }
          .hero-cta .btn { width:min(280px,88vw); justify-content:center; }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { Hero });
