// Homepage — scroll-driven sticky hero, v20

const STATS = [
  { n: 2400, suffix: "+", label: "Verified long-stay homes", icon: "home" },
  { n: 38,   suffix: "",  label: "Cities across Sweden",     icon: "pin" },
  { n: 180,  suffix: "+", label: "Partner companies",        icon: "briefcase" },
  { n: 4.92, suffix: "",  label: "Average guest rating",     icon: "star", decimal: true },
];

const HeroStats = () => {
  const wrapRef = React.useRef(null);
  const numRefs = React.useRef([]);

  React.useEffect(() => {
    const duration = 1600;
    const ease = t => 1 - Math.pow(1 - t, 3);

    const animateOne = (el, stat, delay) => {
      setTimeout(() => {
        const start = performance.now();
        const tick = now => {
          const p = Math.min(1, (now - start) / duration);
          const val = stat.n * ease(p);
          el.textContent = stat.decimal
            ? val.toFixed(2)
            : Math.round(val).toLocaleString('sv');
          if (p < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
      }, delay);
    };

    const obs = new IntersectionObserver(entries => {
      if (!entries[0].isIntersecting) return;
      numRefs.current.forEach((el, i) => {
        if (el) animateOne(el, STATS[i], i * 150);
      });
      obs.disconnect();
    }, { threshold: 0.4 });

    if (wrapRef.current) obs.observe(wrapRef.current);
    return () => obs.disconnect();
  }, []);

  return (
    <div className="hero-stats" ref={wrapRef}>
      {STATS.map((s, i) => (
        <div key={i} className="hero-stat" style={{ animationDelay: `${i * 80}ms` }}>
          <div className="hs-icon"><Icon name={s.icon} size={36} stroke={1.2} /></div>
          <div className="hs-n">
            <span ref={el => numRefs.current[i] = el}>0</span>{s.suffix}
          </div>
          <div className="hs-l">{s.label}</div>
        </div>
      ))}
    </div>
  );
};

const HERO_SLIDES = [
  {
    h1sv: (<>Bo längre.<br/>Bo som hemma.</>),
    h1en: (<>Stay longer.<br/>Feel at home.</>),
    psv: "Möblerade bostäder i hela Sverige från en månad och uppåt – för konsulter, familjer och företag på uppdrag.",
    pen: "Furnished homes across Sweden from one month and up — for consultants, families, and teams on assignment.",
    video: "https://pub-d5c4c3f89bc945d49f689043f519043c.r2.dev/hero1-web.mp4",
  },
  {
    h1sv: (<>Vi äger.<br/>Du sparar.</>),
    h1en: (<>We own.<br/>You save.</>),
    psv: "Alla fastigheter ägs av Sweden Longstay – inga mellanhänder, inga dolda avgifter. Bara schysst pris.",
    pen: "All properties owned by Sweden Longstay. No middlemen, no hidden fees. Just fair pricing.",
    video: "https://pub-d5c4c3f89bc945d49f689043f519043c.r2.dev/hero2-web.mp4",
  },
  {
    h1sv: (<>Flytta in.<br/>Var du vill.</>),
    h1en: (<>Move in.<br/>Wherever.</>),
    psv: "Från Malmö till Boden – vi finns där uppdraget tar dig. Allt inkluderat från dag ett.",
    pen: "From Malmö to Boden — we're where your assignment takes you. Everything included.",
    video: "https://pub-d5c4c3f89bc945d49f689043f519043c.r2.dev/hero3-web.mp4",
  }
];

const Home = () => {
  const t = useTweaks();
  const [search, setSearch] = React.useState({
    where: "", checkIn: "", checkOut: "", length: "", type: "any", guests: 0, children: 0, company: ""
  });
  const [stickyVisible, setStickyVisible] = React.useState(false);
  const [heroSlide, setHeroSlide] = React.useState(0);
  const [heroVideo, setHeroVideo] = React.useState(0);
  const [heroFrac, setHeroFrac] = React.useState(0);
  const videoRefs = React.useRef([]);

  const SLIDE_SCALE = 1.5;

  // Play/pause videos when active index changes
  React.useEffect(() => {
    videoRefs.current.forEach((v, i) => {
      if (!v) return;
      if (i === heroVideo) v.play().catch(() => {});
      else v.pause();
    });
  }, [heroVideo]);

  React.useEffect(() => {
    let raf;
    const update = () => {
      const isDesktop = window.innerWidth >= 900;
      const vh = window.innerHeight;
      const nSlides = isDesktop ? HERO_SLIDES.length : 1;
      if (isDesktop) {
        const progress = Math.max(0, window.scrollY / (vh * SLIDE_SCALE));
        const slide = Math.min(Math.floor(progress), nSlides - 1);
        const frac = Math.min(1, progress - slide);
        setHeroSlide(slide);
        setHeroFrac(frac);
        // video switches when incoming text begins (~frac 0.45)
        const vid = (frac > 0.45 && slide < nSlides - 1) ? slide + 1 : slide;
        setHeroVideo(vid);
      }
      setStickyVisible(window.scrollY > (nSlides * SLIDE_SCALE + 0.6) * vh - 80);
    };
    // Mobile: auto-cycle slides every 5s
    const mobileTimer = setInterval(() => {
      if (window.innerWidth < 900) {
        setHeroSlide(s => {
          const next = (s + 1) % HERO_SLIDES.length;
          setHeroVideo(next);
          return next;
        });
      }
    }, 5000);
    const onScroll = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(update); };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", update, { passive: true });
    update();
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", update);
      cancelAnimationFrame(raf);
      clearInterval(mobileTimer);
    };
  }, []);

  const topCities = React.useMemo(() => {
    const map = {};
    window.SLS_DATA.properties.forEach(p => { (map[p.city] = map[p.city] || []).push(p); });
    return Object.entries(map)
      .sort((a, b) => b[1].length - a[1].length)
      .slice(0, 4);
  }, []);

  const go = (p) => { window.location.href = "property.html?id=" + p.id; };

  const gotoSearch = () => {
    const params = new URLSearchParams();
    if (search.where) params.set("city", search.where);
    if (search.type && search.type !== "any") params.set("type", search.type);
    if (search.guests) params.set("guests", search.guests);
    if (search.checkIn) params.set("in", search.checkIn);
    if (search.checkOut) params.set("out", search.checkOut);
    window.location.href = "search.html?" + params.toString();
  };

  return (
    <>
      <Nav activePage="home" navSolid={stickyVisible} {...t} tweaksOpen={t.open} setTweaksOpen={t.setOpen}
        searchState={search} setSearchState={setSearch} onSearch={gotoSearch} />

      {/* Scroll-driven hero — outer div is 3×150vh tall, inner sticky stays in viewport */}
      <div className="hero-scroll-root" data-screen-label="Home Hero">
        <div className="hero-sticky">
          {/* Video backgrounds — crossfade on slide change */}
          <div className="hero-videos">
            {HERO_SLIDES.map((s, i) => (
              <video key={i}
                ref={el => videoRefs.current[i] = el}
                className={"hero-video" + (i === heroVideo ? " active" : "")}
                muted loop playsInline
                preload={i === 0 ? "auto" : "metadata"}
                aria-hidden="true">
                <source src={s.video} type="video/mp4"/>
              </video>
            ))}
          </div>
          <div className="hero-overlay"/>

          <div className="hero-full-inner">
            {/* Text slides — stack on same grid cell, translate + fade on scroll */}
            <div className="hero-slides-wrap">
              {HERO_SLIDES.map((s, i) => {
                let op = 0, ty = 60;
                if (i === heroSlide) {
                  const hasNext = heroSlide < HERO_SLIDES.length - 1;
                  op = hasNext ? Math.max(0, 1 - heroFrac * 1.4) : 1;
                  ty = hasNext ? -heroFrac * 80 : 0;
                } else if (i === heroSlide + 1) {
                  op = Math.max(0, heroFrac * 1.8 - 0.8);
                  ty = (1 - heroFrac) * 70;
                } else if (i < heroSlide) {
                  op = 0; ty = -70;
                }
                return (
                  <div key={i} className="hero-slide" style={{
                    opacity: op,
                    transform: `translateY(${ty}px)`,
                    pointerEvents: i === heroSlide ? "auto" : "none"
                  }}>
                    <h1>{t.lang === "sv" ? s.h1sv : s.h1en}</h1>
                    <p>{t.lang === "sv" ? s.psv : s.pen}</p>
                  </div>
                );
              })}
            </div>

            <div className="hero-search-col">
              <a
                className="google-review-badge"
                href="https://www.google.com/search?sca_esv=33295543d8b8cd1e&rlz=1C5CHFA_enSE958SE958&sxsrf=ANbL-n70mVqLfxjwcg5Llj7MTkwvntbcdQ:1776960801202&q=Sweden+Longstay&si=AL3DRZGNtcdgKOqVhotcr-UG2kkYpwR2WO4qu3O00NmpwBmLndMFT7OjWJJKDknAKcKuJAbr_zoB89UjhfBG7jXiKmxq4ADKuS0JJuF0rlg-lH_sy0kY0nV2RQ2qjEQccnza9SUqiBYC&sa=X&ved=2ahUKEwiSjNfqroSUAxU9FxAIHUd9KWgQ_coHegQIMBAB&biw=1439&bih=669&dpr=2"
                target="_blank"
                rel="noopener noreferrer"
              >
                <span className="grb-logo">G</span>
                <span className="grb-stars">★★★★★</span>
                <span className="grb-text">5,0 · 15 recensioner på Google</span>
              </a>
              <SearchPanel
                state={search}
                setState={setSearch}
                onSearch={gotoSearch}
                lang={t.lang}
              />
            </div>
          </div>
          <div className="hero-dots-wrap">
            {HERO_SLIDES.map((_, i) => (
              <div key={i} className={"hero-dot" + (i === heroSlide ? " active" : "")} />
            ))}
          </div>
        </div>
      </div>

      <HeroStats />

      <div className="container" style={{ paddingTop: 0 }}>
        {topCities.map(([city, props]) => (
          <section key={city}>
            <div className="section-head">
              <h2>Boenden i {city}</h2>
              <a className="more" onClick={() => { window.location.href = "search.html?city=" + encodeURIComponent(city); }}>
                Visa alla {props.length > 1 ? props.length : ""} ›
              </a>
            </div>
            <PropertyCarousel properties={props} onOpen={go} />
          </section>
        ))}
        <B2BStrip />
      </div>

      <Footer />
      <FloatingContact />
      <TweaksPanel open={t.open} {...t} />
    </>
  );
};

const _mountHome = () => ReactDOM.createRoot(document.getElementById("root")).render(<Home />);
if (window.SLS_DATA) _mountHome();
else window.addEventListener("sls:ready", _mountHome, { once: true });
