// fit-scaler.jsx — shared FitScaler component.
// Fits a fixed design-width block into any viewport by scaling it down
// (never up past maxScale). Below minScale it stops shrinking and lets the
// block scroll horizontally instead of going microscopic on phones.
// Loaded before any script that uses <window.FitScaler>.
(function () {
  function FitScaler({ designWidth = 1320, maxScale = 1, minScale = 0.5, className = "", children }) {
    const outerRef = React.useRef(null);
    const innerRef = React.useRef(null);
    const lastRef = React.useRef({ s: -1, h: -1 });
    const [scale, setScale] = React.useState(1);
    const [box, setBox] = React.useState({ h: undefined, scroll: false });

    React.useLayoutEffect(() => {
      const outer = outerRef.current, inner = innerRef.current;
      if (!outer || !inner) return;
      let t = 0;
      const apply = () => {
        const host = outer.parentElement || outer;
        const ow = host.clientWidth || outer.clientWidth;
        let s = ow / designWidth;
        let scroll = false;
        if (s < minScale) { s = minScale; scroll = true; }
        s = Math.min(maxScale, s);
        const h = inner.offsetHeight * s;
        const last = lastRef.current;
        if (Math.abs(s - last.s) < 0.002 && Math.abs(h - last.h) < 0.75) return;
        lastRef.current = { s, h };
        setScale(s);
        setBox({ h, scroll });
      };
      const measure = () => { clearTimeout(t); t = setTimeout(apply, 80); };
      apply(); // synchronous initial fit (rAF can be throttled in embeds)
      // Observe ONLY the inner content (whose size we never mutate) so this can
      // never feed back into itself. Width changes are caught via window resize.
      const roInner = new ResizeObserver(measure);
      roInner.observe(inner);
      window.addEventListener("resize", measure);
      // A couple of delayed re-measures catch late layout (fonts/images/babel).
      const t1 = setTimeout(apply, 250);
      const t2 = setTimeout(apply, 1200);
      return () => {
        clearTimeout(t); clearTimeout(t1); clearTimeout(t2);
        roInner.disconnect();
        window.removeEventListener("resize", measure);
      };
    }, [designWidth, maxScale, minScale]);

    return (
      <div
        ref={outerRef}
        className={`fit-scaler ${box.scroll ? "fit-scaler--scroll" : ""} ${className}`}
        style={{ height: box.h }}
      >
        <div
          ref={innerRef}
          className="fit-scaler__inner"
          style={{ width: designWidth, transform: `scale(${scale})`, transformOrigin: "top center" }}
        >
          {children}
        </div>
      </div>
    );
  }
  window.FitScaler = FitScaler;
})();
