// Shared atoms: ProductSlot (striped placeholder), Reveal (scroll-triggered), Counter
const { useState, useEffect, useRef, useMemo, useCallback } = React;

function ProductSlot({ label = "product shot", aspect = "4 / 3", variant = "default" }) {
  return (
    <div className="product-slot" style={{ aspectRatio: aspect }} data-variant={variant}>
      <div className="slot-stripes"></div>
      <div className="slot-label">{label}</div>
    </div>
  );
}

function Reveal({ children, delay = 0, as = "div", className = "" }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setVisible(true);
          io.disconnect();
        }
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const Tag = as;
  return (
    <Tag
      ref={ref}
      className={`reveal ${visible ? "is-visible" : ""} ${className}`}
      style={{ transitionDelay: `${delay}ms` }}
    >
      {children}
    </Tag>
  );
}

function Counter({ to, suffix = "", duration = 1400 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !started.current) {
        started.current = true;
        const start = performance.now();
        const tick = (t) => {
          const p = Math.min(1, (t - start) / duration);
          const eased = 1 - Math.pow(1 - p, 3);
          setVal(Math.round(eased * to));
          if (p < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
      }
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);
  return (
    <span ref={ref} className="counter">
      {val.toLocaleString("ka-GE")}{suffix}
    </span>
  );
}

function SectionLabel({ num, children }) {
  return (
    <div className="section-label">
      <span className="section-num">{num}</span>
      <span className="section-line"></span>
      <span className="section-text">{children}</span>
    </div>
  );
}

Object.assign(window, { ProductSlot, Reveal, Counter, SectionLabel });
