// Navbar + Hero + Floating Telegram button
const { useState, useEffect, useRef, useMemo } = React;

// ---------- Navbar ----------
function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <header className={`fixed top-0 inset-x-0 z-40 transition-all duration-300 ${scrolled ? "bg-ink-950/80 backdrop-blur-xl border-b border-ink-600/60" : "bg-transparent border-b border-transparent"}`}>
      <div className="max-w-[1240px] mx-auto px-5 lg:px-8 h-16 flex items-center gap-6">
        <a href={swResolve("/")} className="flex items-center gap-2.5 shrink-0">
          <Icon.Logo className="w-7 h-7" />
          <span className="font-display font-semibold text-[17px] tracking-tight">
            Stake<span className="text-teal">Worldwide</span>
          </span>
        </a>

        <nav className="hidden lg:flex items-center gap-1 mx-auto">
          {[
            { label: "Guides", slug: "/guides" },
            { label: "Countries", slug: "/countries" },
            { label: "VPN Reviews", slug: "/vpn" },
            { label: "About", slug: "/about" },
          ].map((l) => (
            <a key={l.label} href={swResolve(l.slug)} className="px-3.5 py-2 rounded-lg text-[14px] text-fg-muted hover:text-fg hover:bg-white/5 transition">
              {l.label}
            </a>
          ))}
        </nav>

        <div className="hidden lg:flex items-center gap-3 ml-auto">
          <a href="#search" className="w-9 h-9 grid place-items-center rounded-lg text-fg-muted hover:text-fg hover:bg-white/5 transition" aria-label="Search">
            <Icon.Search className="w-4 h-4" />
          </a>
          <a
            href={SW_DATA.TG_LINK} target="_blank" rel="noopener"
            className="group flex items-center gap-2 pl-3 pr-3.5 py-2 rounded-full border border-teal/40 text-teal hover:bg-teal hover:text-ink-950 transition-all text-[13.5px] font-medium"
          >
            <Icon.Telegram className="w-4 h-4" />
            <span>Get Help</span>
          </a>
        </div>

        <button className="lg:hidden ml-auto p-2 text-fg" onClick={() => setMobileOpen(v => !v)}>
          <Icon.Menu />
        </button>
      </div>

      {mobileOpen && (
        <div className="lg:hidden border-t border-ink-600 bg-ink-950/95 backdrop-blur-xl">
          <div className="px-5 py-4 flex flex-col gap-1">
            {[
              { label: "Guides", slug: "/guides" },
              { label: "Countries", slug: "/countries" },
              { label: "VPN Reviews", slug: "/vpn" },
              { label: "About", slug: "/about" },
            ].map((l) => (
              <a key={l.label} href={swResolve(l.slug)} className="px-3 py-2.5 rounded-lg text-fg-muted hover:text-fg hover:bg-white/5">{l.label}</a>
            ))}
            <a href={SW_DATA.TG_LINK} target="_blank" rel="noopener"
               className="mt-2 flex items-center justify-center gap-2 py-3 rounded-lg border border-teal/40 text-teal">
              <Icon.Telegram className="w-4 h-4" /> Get Help on Telegram
            </a>
          </div>
        </div>
      )}
    </header>
  );
}

// ---------- Counter animation ----------
function useCounter(to, { duration = 1600, enabled = true } = {}) {
  const [v, setV] = useState(0);
  useEffect(() => {
    if (!enabled) return;
    let start = null; let raf = 0;
    const step = (t) => {
      if (start === null) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(Math.round(to * eased));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [to, duration, enabled]);
  return v;
}

function Stat({ value, suffix = "", label, enabled }) {
  const n = useCounter(value, { enabled });
  return (
    <div className="flex flex-col">
      <div className="font-display text-3xl md:text-[38px] font-semibold tracking-tight text-fg">
        {n.toLocaleString()}{suffix}
      </div>
      <div className="text-[13px] text-fg-dim mt-1">{label}</div>
    </div>
  );
}

// ---------- Hero ----------
function Hero() {
  const [q, setQ] = useState("");
  const [focus, setFocus] = useState(false);
  const heroRef = useRef(null);
  const [ready, setReady] = useState(false);
  useEffect(() => {
    const io = new IntersectionObserver(([e]) => e.isIntersecting && setReady(true), { threshold: 0.2 });
    if (heroRef.current) io.observe(heroRef.current);
    return () => io.disconnect();
  }, []);

  const suggestions = useMemo(() => {
    if (!q.trim()) return [];
    const pool = [
      ...SW_DATA.GUIDES.map(g => ({ kind: "Guide", label: g.title, slug: g.slug })),
      ...SW_DATA.COUNTRIES.map(c => ({ kind: "Country", label: `Stake in ${c.name}`, slug: c.slug })),
      { kind: "Topic", label: "Level 2 KYC requirements", slug: "/guides/kyc-levels" },
      { kind: "Topic", label: "Crypto deposits on Stake", slug: "/guides/deposits" },
      { kind: "Topic", label: "Rakeback and VIP tiers", slug: "/guides/rakeback" },
      { kind: "Topic", label: "Best VPN for Stake", slug: "/vpn/best-for-stake" },
      { kind: "Topic", label: "Stake in the US", slug: "/countries/united-states" },
    ];
    const s = q.toLowerCase();
    return pool.filter(p => p.label.toLowerCase().includes(s)).slice(0, 6);
  }, [q]);

  const doSearch = () => {
    const first = suggestions[0];
    if (first) {
      window.location.href = swResolve(first.slug);
      return;
    }
    // Fallback: try to match against routes by keyword
    const s = q.trim().toLowerCase();
    if (!s) return;
    window.location.href = "coming-soon.html?path=/search?q=" + encodeURIComponent(q);
  };

  return (
    <section ref={heroRef} className="relative pt-28 pb-20 md:pt-36 md:pb-28 overflow-hidden">
      {/* Background */}
      <div className="absolute inset-0 mesh-bg opacity-80 pointer-events-none" />
      <div className="absolute inset-x-0 top-0 h-[520px] bg-gradient-to-b from-transparent via-transparent to-ink-950 pointer-events-none" />
      <div className="absolute -top-32 left-1/2 -translate-x-1/2 w-[900px] h-[520px] rounded-full pointer-events-none"
           style={{ background: "radial-gradient(ellipse at center, rgba(16,185,129,0.18), transparent 60%)" }} />

      <div className="relative max-w-[1100px] mx-auto px-5 lg:px-8 text-center">
        {/* Eyebrow */}
        <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full border border-ink-600 bg-ink-800/70 backdrop-blur text-[12px] text-fg-muted mb-7">
          <span className="live-dot" />
          <span>Independent knowledge hub · Updated weekly</span>
        </div>

        <h1 className="font-display font-semibold text-[40px] leading-[1.08] sm:text-[56px] md:text-[68px] md:leading-[1.05] tracking-[-0.02em] max-w-[980px] mx-auto">
          <span className="grad-text">Your complete guide to Stake.com</span><br/>
          <span className="text-fg-muted font-light">Access, play & win from anywhere.</span>
        </h1>

        <p className="mt-6 text-[17px] md:text-[18px] text-fg-muted max-w-[680px] mx-auto leading-relaxed">
          Expert guides, country-by-country analysis, verification walkthroughs and strategies —
          distilled from years of testing. Updated weekly.
        </p>

        {/* Search bar */}
        <div id="search" className="relative mt-9 max-w-[640px] mx-auto">
          <div className={`ring-focus flex items-center gap-3 rounded-2xl border border-ink-600 bg-ink-800/80 backdrop-blur pl-5 pr-2 py-2 shadow-[0_20px_60px_-20px_rgba(0,0,0,0.6)]`}>
            <Icon.Search className="w-5 h-5 text-fg-dim" />
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              onFocus={() => setFocus(true)}
              onBlur={() => setTimeout(() => setFocus(false), 150)}
              onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); doSearch(); } }}
              placeholder="Search guides... (e.g., 'Stake in the US', 'Level 2 KYC')"
              className="flex-1 bg-transparent text-fg placeholder:text-fg-dim text-[15px] py-2.5 w-full"
            />
            <button onClick={doSearch} className="shrink-0 px-4 py-2.5 rounded-xl bg-teal text-ink-950 font-semibold text-[13.5px] hover:bg-teal/90 transition flex items-center gap-1.5">
              Search <Icon.ArrowRight className="w-4 h-4" />
            </button>
          </div>

          {/* Suggestions */}
          {focus && suggestions.length > 0 && (
            <div className="absolute left-0 right-0 mt-2 rounded-2xl border border-ink-600 bg-ink-800/95 backdrop-blur-xl shadow-2xl z-10 overflow-hidden text-left">
              {suggestions.map((s, i) => (
                <button key={i} onMouseDown={(e) => { e.preventDefault(); window.location.href = swResolve(s.slug); }} className="w-full flex items-center gap-3 px-5 py-3 hover:bg-white/5 border-b border-ink-700 last:border-0 text-left">
                  <span className="text-[10px] uppercase tracking-wider text-fg-dim w-16 shrink-0 font-mono">{s.kind}</span>
                  <span className="text-fg text-[14px] flex-1">{s.label}</span>
                  <Icon.ArrowRight className="w-3.5 h-3.5 text-fg-dim" />
                </button>
              ))}
            </div>
          )}

          {!focus && !q && (
            <div className="mt-4 flex flex-wrap justify-center gap-2 text-[12.5px]">
              {["Stake in the US", "Level 2 KYC", "Best VPN", "Rakeback"].map(t => (
                <button key={t} onClick={() => setQ(t)} className="px-3 py-1.5 rounded-full border border-ink-600 bg-ink-800/50 text-fg-muted hover:border-teal/40 hover:text-teal transition">
                  {t}
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Secondary Telegram CTA */}
        <a href={SW_DATA.TG_LINK} target="_blank" rel="noopener"
           className="group mt-6 inline-flex items-center gap-2.5 pl-2 pr-4 py-1.5 rounded-full border border-tg/40 bg-tg/10 hover:bg-tg/20 hover:border-tg/70 transition text-[13.5px] font-medium"
           style={{ boxShadow: "0 8px 30px -12px rgba(38,165,228,0.45)" }}>
          <span className="w-7 h-7 rounded-full grid place-items-center text-white shrink-0"
                style={{ background: "linear-gradient(135deg, #2AB0F1, #1F8BC7)" }}>
            <Icon.Telegram className="w-3.5 h-3.5" />
          </span>
          <span className="flex items-center gap-1.5">
            <span className="live-dot" style={{ background: "#26A5E4" }} />
            <span className="text-tg">Need personal help?</span>
            <span className="text-fg-muted">Our experts are online</span>
          </span>
          <Icon.ArrowRight className="w-3.5 h-3.5 text-tg transition-transform group-hover:translate-x-0.5" />
        </a>

        {/* Stats */}
        <div className="mt-14 grid grid-cols-3 gap-6 md:gap-10 max-w-[720px] mx-auto border-t border-ink-600 pt-8">
          <Stat value={50} suffix="+" label="In-depth guides" enabled={ready} />
          <Stat value={180} suffix="+" label="Countries covered" enabled={ready} />
          <div className="flex flex-col">
            <div className="font-display text-3xl md:text-[38px] font-semibold tracking-tight text-fg flex items-baseline justify-center md:justify-start gap-1.5">
              <span>Weekly</span>
            </div>
            <div className="text-[13px] text-fg-dim mt-1">Editorial cadence</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Floating Telegram FAB ----------
function FloatingTelegram() {
  return (
    <a
      href={SW_DATA.TG_LINK}
      target="_blank" rel="noopener"
      className="fab fixed bottom-5 right-5 md:bottom-7 md:right-7 z-50 flex items-center rounded-full tg-pulse"
      style={{ background: "linear-gradient(135deg, #2AB0F1, #1F8BC7)" }}
    >
      <span className="w-14 h-14 md:w-[58px] md:h-[58px] grid place-items-center text-white">
        <Icon.Telegram className="w-6 h-6" />
      </span>
      <span className="fab-label text-white font-medium text-[14px] pr-1.5 hidden md:inline-block">Chat with an Expert</span>
    </a>
  );
}

window.Navbar = Navbar;
window.Hero = Hero;
window.FloatingTelegram = FloatingTelegram;
