/* Shared hooks and motion helpers for AMARINE */
const { useState, useEffect, useRef } = React;

/* ====== useT — re-renders on lang change ====== */
function useT() {
  const [, setTick] = useState(0);
  useEffect(() => {
    const onChange = () => setTick(t => t + 1);
    window.addEventListener('lang-change', onChange);
    return () => window.removeEventListener('lang-change', onChange);
  }, []);
  return window.AMARINE_I18N.t;
}

function useLang() {
  const [lang, setLang] = useState(window.AMARINE_I18N.getLang());
  useEffect(() => {
    const onChange = (e) => setLang(e.detail.lang);
    window.addEventListener('lang-change', onChange);
    return () => window.removeEventListener('lang-change', onChange);
  }, []);
  return lang;
}

/** Locale-prefixed path for links (/about -> /en/about when EN). */
function useLocalizedPath() {
  const lang = useLang();
  return (routePath, opts) => window.AMARINE_LOCALE.pathFor(lang, routePath, opts);
}

/* ====== Reveal on scroll ====== */
function Reveal({ children, delay = 0, as: As = 'div', className = '', style, ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          el.classList.add('in');
          io.unobserve(el);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <As
      ref={ref}
      {...rest}
      className={`reveal ${className}`}
      style={{ transitionDelay: `${delay}ms`, ...style }}
    >
      {children}
    </As>
  );
}

Object.assign(window, { useT, useLang, useLocalizedPath, Reveal });
