/* ============================================================
   VIEWPORT — hook + utility responsive
   ============================================================
   Breakpoint:
     mobile:  ≤ 767 px
     tablet:  768 – 1023 px
     desktop: ≥ 1024 px
   ============================================================ */

const VIEWPORT_BREAKPOINTS = {
  mobile: 768,   // < 768 = mobile
  tablet: 1024,  // < 1024 = tablet, ≥ 1024 = desktop
};

window.VIEWPORT_BREAKPOINTS = VIEWPORT_BREAKPOINTS;

function _getViewport() {
  const w = typeof window !== 'undefined' ? window.innerWidth : 1280;
  return {
    width: w,
    isMobile:  w < VIEWPORT_BREAKPOINTS.mobile,
    isTablet:  w >= VIEWPORT_BREAKPOINTS.mobile && w < VIEWPORT_BREAKPOINTS.tablet,
    isDesktop: w >= VIEWPORT_BREAKPOINTS.tablet,
    isMobileOrTablet: w < VIEWPORT_BREAKPOINTS.tablet,
  };
}

/* Hook React: ritorna sempre lo stato corrente del viewport.
   Si aggiorna su resize con debounce 80ms (smooth durante il drag). */
function useViewport() {
  const [vp, setVp] = React.useState(_getViewport);
  React.useEffect(() => {
    let t = null;
    const onResize = () => {
      if (t) clearTimeout(t);
      t = setTimeout(() => setVp(_getViewport()), 80);
    };
    window.addEventListener('resize', onResize);
    window.addEventListener('orientationchange', onResize);
    return () => {
      if (t) clearTimeout(t);
      window.removeEventListener('resize', onResize);
      window.removeEventListener('orientationchange', onResize);
    };
  }, []);
  return vp;
}

/* Utility components per nascondere/mostrare sezioni in base al device */
function MobileOnly({ children }) {
  const { isMobile } = useViewport();
  return isMobile ? children : null;
}
function TabletOnly({ children }) {
  const { isTablet } = useViewport();
  return isTablet ? children : null;
}
function DesktopOnly({ children }) {
  const { isDesktop } = useViewport();
  return isDesktop ? children : null;
}
function MobileTabletOnly({ children }) {
  const { isMobileOrTablet } = useViewport();
  return isMobileOrTablet ? children : null;
}
function NotMobile({ children }) {
  const { isMobile } = useViewport();
  return isMobile ? null : children;
}

/* Helper: ritorna uno tra (mobile, tablet, desktop) in base al viewport.
   Comodo per scegliere stili inline rapidamente:
   const padding = pickByViewport({ mobile: 12, tablet: 18, desktop: 26 }, vp);
*/
function pickByViewport(values, vp) {
  if (vp.isMobile && 'mobile' in values) return values.mobile;
  if (vp.isTablet && 'tablet' in values) return values.tablet;
  return values.desktop !== undefined ? values.desktop : values.default;
}

Object.assign(window, {
  useViewport,
  MobileOnly, TabletOnly, DesktopOnly, MobileTabletOnly, NotMobile,
  pickByViewport,
});