// shared.jsx - shared hooks & primitives
const { useState, useEffect, useRef, useContext, createContext } = React;

// Language context
const LangContext = createContext({ lang: 'pt', setLang: () => {}, t: window.TRANSLATIONS.pt });

const useLang = () => useContext(LangContext);

// Intersection observer hook for reveal animations
const useReveal = (options = {}) => {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    // Mark body so reveal-hidden state is active only when JS+IO works
    document.documentElement.classList.add('js-reveal');
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setVisible(true);
        obs.disconnect();
      }
    }, { threshold: 0.05, rootMargin: '0px 0px -30px 0px', ...options });
    obs.observe(el);
    // Fallback: if still not visible after 3s, reveal anyway
    const fallback = setTimeout(() => setVisible(true), 3000);
    return () => { obs.disconnect(); clearTimeout(fallback); };
  }, []);
  return [ref, visible];
};

const Reveal = ({ children, delay = 0, className = '', as = 'div' }) => {
  const [ref, visible] = useReveal();
  const Tag = as;
  const delayClass = delay ? `reveal-delay-${delay}` : '';
  return <Tag ref={ref} className={`reveal ${delayClass} ${visible ? 'in' : ''} ${className}`}>{children}</Tag>;
};

// Animated number count-up - preserves currency prefix + locale decimals
const CountUp = ({ to, prefix = '', suffix = '', duration = 1500 }) => {
  const [ref, visible] = useReveal();
  const [val, setVal] = useState(0);
  const raw = String(to);
  // Detect currency/text prefix (everything before first digit)
  const firstDigit = raw.search(/[0-9]/);
  const autoPrefix = firstDigit > 0 ? raw.slice(0, firstDigit) : '';
  const numericPart = firstDigit >= 0 ? raw.slice(firstDigit) : raw;
  // Detect decimal separator: if comma present, treat as decimal (PT-BR)
  const usesComma = numericPart.includes(',');
  const normalized = numericPart.replace(/[^0-9.,]/g, '').replace(/\./g, '').replace(',', '.');
  const targetNum = parseFloat(normalized) || 0;
  const decimals = usesComma ? (normalized.split('.')[1] || '').length : 0;

  useEffect(() => {
    if (!visible) return;
    let start = null;
    const step = (ts) => {
      if (!start) start = ts;
      const p = Math.min(1, (ts - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(targetNum * eased);
      if (p < 1) requestAnimationFrame(step);
    };
    requestAnimationFrame(step);
  }, [visible]);

  const formatted = decimals > 0
    ? val.toFixed(decimals).replace('.', ',')
    : Number.isInteger(targetNum)
      ? Math.round(val).toLocaleString('pt-BR')
      : val.toFixed(1);
  return <span ref={ref}>{prefix}{autoPrefix}{formatted}{suffix}</span>;
};

window.LangContext = LangContext;
window.useLang = useLang;
window.useReveal = useReveal;
window.Reveal = Reveal;
window.CountUp = CountUp;
