// AutoFitHeadline — universal solution for "headline text of varying length must not blow up".
// Renders headline, measures line count after paint, and scales font-size down in small steps
// until the rendered line count <= maxLines. Re-runs on resize.
//
// Used wherever translated strings might wrap unpredictably.
function AutoFitHeadline({
  children,
  as: Tag = 'h2',
  className = '',
  maxLines = 2,
  minScale = 0.55,
  step = 0.04,
  style = {}
}) {
  const ref = React.useRef(null);
  const [scale, setScale] = React.useState(1);

  const fit = React.useCallback(() => {
    const el = ref.current;
    if (!el) return;
    // Reset first to measure at full size
    el.style.fontSize = '';
    el.style.setProperty('--fit-scale', '1');
    let s = 1;
    // We measure line count via offsetHeight / line-height
    const lh = parseFloat(getComputedStyle(el).lineHeight);
    if (!lh) return;
    const targetHeight = lh * maxLines + 2; // tolerance
    let guard = 20;
    while (el.offsetHeight > targetHeight && s > minScale && guard-- > 0) {
      s -= step;
      el.style.setProperty('--fit-scale', String(s));
    }
    setScale(s);
  }, [maxLines, minScale, step, children]);

  React.useEffect(() => {
    fit();
    let t;
    const onR = () => { clearTimeout(t); t = setTimeout(fit, 80); };
    window.addEventListener('resize', onR);
    return () => { window.removeEventListener('resize', onR); clearTimeout(t); };
  }, [fit]);

  // Also refit when fonts finish loading
  React.useEffect(() => {
    if (document.fonts && document.fonts.ready) {
      document.fonts.ready.then(() => fit()).catch(() => {});
    }
  }, [fit]);

  return (
    <Tag
      ref={ref}
      className={`autofit ${className}`}
      style={{ ...style }}
      data-scale={scale.toFixed(2)}
    >
      {children}
    </Tag>
  );
}

Object.assign(window, { AutoFitHeadline });
