'use client';

import { useEffect, useState } from 'react';

export function useElementWidth(el: HTMLElement | null): number {
  const [w, setW] = useState(0);
  useEffect(() => {
    if (!el || typeof ResizeObserver === 'undefined') return;
    setW(el.clientWidth);
    const obs = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const next = entry.contentRect.width;
        setW((prev) => (Math.abs(prev - next) < 0.5 ? prev : next));
      }
    });
    obs.observe(el);
    return () => obs.disconnect();
  }, [el]);
  return w;
}
