// Shared utilities used by both ALTTAGSOLUTIONS.html and UAE.html

const { useState: __useStateShared, useEffect: __useEffectShared, useRef: __useRefShared } = React;

function useTheme() {
  const [theme, setTheme] = __useStateShared(() => {
    try { return localStorage.getItem("ats-theme") || "dark"; } catch { return "dark"; }
  });
  __useEffectShared(() => {
    document.documentElement.setAttribute("data-theme", theme);
    try { localStorage.setItem("ats-theme", theme); } catch {}
  }, [theme]);
  return [theme, setTheme];
}

function ThemeToggle({ theme, onToggle }) {
  return (
    <button className="theme-toggle" onClick={onToggle} aria-label="Toggle theme" title={theme === "dark" ? "Switch to light" : "Switch to dark"}>
      <span className={`tt-track tt-${theme}`}>
        <span className="tt-thumb">
          {theme === "dark" ? (
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
            </svg>
          ) : (
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="12" cy="12" r="4" />
              <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41" />
            </svg>
          )}
        </span>
      </span>
    </button>
  );
}

function ScrollProgress() {
  const [pct, setPct] = __useStateShared(0);
  __useEffectShared(() => {
    function onScroll() {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setPct(max > 0 ? (h.scrollTop / max) * 100 : 0);
    }
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return <div className="scroll-progress" style={{ transform: `scaleX(${pct / 100})` }} />;
}

function smoothScrollTo(targetId, duration = 1100) {
  const target = document.querySelector(targetId);
  if (!target) return;
  const startY = window.pageYOffset;
  const targetY = target.getBoundingClientRect().top + startY - 20;
  const distance = targetY - startY;
  const startTime = performance.now();
  const ease = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
  function step(now) {
    const elapsed = now - startTime;
    const progress = Math.min(elapsed / duration, 1);
    window.scrollTo(0, startY + distance * ease(progress));
    if (progress < 1) requestAnimationFrame(step);
  }
  requestAnimationFrame(step);
}

function useSmoothScrollLinks() {
  __useEffectShared(() => {
    function onClick(ev) {
      const a = ev.target.closest("a[href^='#']");
      if (!a) return;
      const href = a.getAttribute("href");
      if (!href || href === "#") return;
      const target = document.querySelector(href);
      if (!target) return;
      ev.preventDefault();
      smoothScrollTo(href);
      history.replaceState(null, "", href);
    }
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);
}

function CountUp({ to, suffix = "", duration = 1400 }) {
  const ref = __useRefShared(null);
  const [val, setVal] = __useStateShared(0);
  const [done, setDone] = __useStateShared(false);
  __useEffectShared(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !done) {
          setDone(true);
          const start = performance.now();
          const ease = (t) => 1 - Math.pow(1 - t, 3);
          function step(now) {
            const p = Math.min((now - start) / duration, 1);
            setVal(Math.round(to * ease(p)));
            if (p < 1) requestAnimationFrame(step);
          }
          requestAnimationFrame(step);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration, done]);
  return <span ref={ref}>{val}{suffix}</span>;
}

function useActiveNav(ids) {
  __useEffectShared(() => {
    function update() {
      const threshold = window.innerHeight * 0.45;
      let activeId = null;
      for (const id of ids) {
        const el = document.getElementById(id);
        if (!el) continue;
        if (el.getBoundingClientRect().top <= threshold) activeId = id;
      }
      document.querySelectorAll('.topnav-links a[href^="#"]').forEach(link => {
        link.classList.toggle('active', link.getAttribute('href') === `#${activeId}`);
      });
    }
    window.addEventListener('scroll', update, { passive: true });
    update();
    return () => window.removeEventListener('scroll', update);
  }, []);
}

window.useTheme = useTheme;
window.ThemeToggle = ThemeToggle;
window.ScrollProgress = ScrollProgress;
window.useSmoothScrollLinks = useSmoothScrollLinks;
window.CountUp = CountUp;
window.smoothScrollTo = smoothScrollTo;
window.useActiveNav = useActiveNav;
