import { useEffect, useState } from 'react';

export type Breakpoint = 'mobile' | 'tablet' | 'desktop';

/**
 * Detects current breakpoint based on viewport width.
 *
 * Breakpoints (must match app's tailwind/MUI/etc. config):
 *   - mobile:  width <= 639px
 *   - tablet:  640px <= width < 1024px
 *   - desktop: width >= 1024px
 *
 * Listens to matchMedia changes — updates on resize.
 */
export function useBreakpoint(): Breakpoint {
  const [bp, setBp] = useState<Breakpoint>(() => {
    if (typeof window === 'undefined') return 'desktop';
    if (window.matchMedia('(max-width: 639px)').matches) return 'mobile';
    if (window.matchMedia('(max-width: 1023px)').matches) return 'tablet';
    return 'desktop';
  });

  useEffect(() => {
    const mq = {
      mobile: window.matchMedia('(max-width: 639px)'),
      tablet: window.matchMedia('(max-width: 1023px)'),
    };
    const apply = () => {
      if (mq.mobile.matches) setBp('mobile');
      else if (mq.tablet.matches) setBp('tablet');
      else setBp('desktop');
    };
    apply();
    mq.mobile.addEventListener('change', apply);
    mq.tablet.addEventListener('change', apply);
    return () => {
      mq.mobile.removeEventListener('change', apply);
      mq.tablet.removeEventListener('change', apply);
    };
  }, []);

  return bp;
}
