import { browser } from '$app/environment';

const MOBILE_BREAKPOINT = 768;

export function useIsMobile() {
  const isMobile = $state(
    browser ? window.innerWidth < MOBILE_BREAKPOINT : false
  );

  if (browser) {
    const media = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
    const handler = (event: MediaQueryListEvent) => {
      isMobile = event.matches;
    };
    media.addEventListener('change', handler);
    $effect(() => {
      return () => media.removeEventListener('change', handler);
    });
  }

  return {
    get current() {
      return isMobile;
    },
  };
}