/* ===== Luxury Academy — Enhancements: scroll FX, scroll-spy, count-up, CTAs ===== */

// ── Scroll effects engine (vanilla, runs after React mounts) ──────────────────
(function () {
  const REVEAL_SELECTORS = [
    ".section-head", ".svc-card", ".course-card", ".offer-card",
    ".value-card", ".testi-card", ".gallery-cell", ".about-visual",
    ".contact-card", ".map-shell", ".booking-shell", ".faq-item",
    ".hero-stats", ".news-form",
  ];

  let revealObs = null;
  let countObs = null;
  const prefersReduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  // Count-up: "+500" -> +500, "4.9★" -> 4.9★ (preserves prefix/suffix & decimals)
  function animateCount(el) {
    const raw = (el.dataset.cuRaw || el.textContent).trim();
    if (!el.dataset.cuRaw) el.dataset.cuRaw = raw;
    const m = raw.match(/^(\D*)([\d.,]+)(.*)$/);
    if (!m) return;
    const prefix = m[1], suffix = m[3];
    const numStr = m[2].replace(/,/g, "");
    const target = parseFloat(numStr);
    const decimals = (numStr.split(".")[1] || "").length;
    if (isNaN(target)) return;
    const dur = 1400, t0 = performance.now();
    const fmt = (v) => prefix + (decimals
      ? v.toFixed(decimals)
      : Math.round(v).toLocaleString("es-CO")) + suffix;
    function tick(now) {
      const p = Math.min(1, (now - t0) / dur);
      const eased = 1 - Math.pow(1 - p, 3); // easeOutCubic
      el.textContent = fmt(target * eased);
      if (p < 1) requestAnimationFrame(tick);
      else el.textContent = fmt(target);
    }
    requestAnimationFrame(tick);
  }

  function ensureObservers() {
    if (prefersReduced) return;
    if (!revealObs) {
      revealObs = new IntersectionObserver((entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) { e.target.classList.add("is-in"); revealObs.unobserve(e.target); }
        });
      }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    }
    if (!countObs) {
      countObs = new IntersectionObserver((entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) { animateCount(e.target); countObs.unobserve(e.target); }
        });
      }, { threshold: 0.6 });
    }
  }

  // Apply reveal + register count-up targets. Safe to call repeatedly (async data).
  window.lxObserveFX = function () {
    if (prefersReduced) return;
    ensureObservers();
    REVEAL_SELECTORS.forEach((sel) => {
      document.querySelectorAll(sel).forEach((el) => {
        if (el.dataset.fx) return;
        el.dataset.fx = "1";
        el.classList.add("reveal");
        // stagger siblings of the same kind
        const sibs = el.parentElement ? Array.from(el.parentElement.children).filter(c => c.classList.contains(el.classList[0])) : [];
        const i = sibs.indexOf(el);
        if (i > 0) el.style.setProperty("--d", Math.min(i, 6) * 70 + "ms");
        revealObs.observe(el);
      });
    });
    document.querySelectorAll(".hero-stats .num, .about-stat-card .num").forEach((el) => {
      if (el.dataset.cu) return;
      el.dataset.cu = "1";
      countObs.observe(el);
    });
  };

  // Scroll-spy (nav active link) + top progress bar
  function initScrollWatchers() {
    const sections = ["services","courses","offers","about","gallery","contact"]
      .map(id => document.getElementById(id)).filter(Boolean);
    const links = {};
    document.querySelectorAll(".nav-link").forEach(a => {
      const href = a.getAttribute("href") || "";
      if (href.startsWith("#")) links[href.slice(1)] = a;
    });
    const bar = document.getElementById("lx-progress");

    let ticking = false;
    function onScroll() {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        const y = window.scrollY;
        // progress
        if (bar) {
          const h = document.documentElement.scrollHeight - window.innerHeight;
          bar.style.width = (h > 0 ? (y / h) * 100 : 0) + "%";
        }
        // spy
        let current = "";
        const probe = y + window.innerHeight * 0.32;
        sections.forEach(s => { if (probe >= s.offsetTop) current = s.id; });
        Object.entries(links).forEach(([id, a]) =>
          a.classList.toggle("active", id === current));
        ticking = false;
      });
    }
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
  }

  window.lxInitScrollFX = function () {
    window.lxObserveFX();
    initScrollWatchers();
  };
})();

// ── Back-to-top button ────────────────────────────────────────────────────────
function BackToTop() {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 700);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <button
      className={`back-to-top ${show ? "show" : ""}`}
      aria-label="Volver arriba"
      onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
    >
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M18 15l-6-6-6 6" />
      </svg>
    </button>
  );
}

// ── Sticky mobile CTA bar (conversion-focused) ────────────────────────────────
function StickyCTA({ lang, scrollTo }) {
  const waText = lang === "es"
    ? "Hola Luxury Academy! Quiero más información sobre sus servicios y cursos."
    : "Hello Luxury Academy! I'd like more info about your services and courses.";
  return (
    <div className="sticky-cta">
      <button className="btn btn-gold btn-block" onClick={() => window.cartStore && window.cartStore.openDrawer()}>
        <Icon.Calendar size={16} /> {lang === "es" ? "Agendar cita" : "Book now"}
      </button>
      <a
        className="sticky-cta-wa"
        href={`https://wa.me/573332716890?text=${encodeURIComponent(waText)}`}
        target="_blank" rel="noopener" aria-label="WhatsApp"
      >
        <Icon.Whatsapp size={22} />
      </a>
    </div>
  );
}

window.BackToTop = BackToTop;
window.StickyCTA = StickyCTA;
