'use client'

import base from '../../theme/base'
import { useMediaQuery } from './useMediaQuery'

type Viewport = 'XS' | 'S' | 'M' | 'L' | 'XL'

export function useViewport(
  serverFallback: Viewport | null = 'XL',
): Viewport | null {
  // Logic matches base.ts screens:
  // XL: >= 1200
  // L:  >= 996
  // M:  >= 768
  // S:  >= 480
  // XS: < 480

  const isXL = useMediaQuery(
    `(min-width: ${base.theme.extend.screens.xl})`,
    serverFallback === null ? null : serverFallback === 'XL',
  )
  const isL = useMediaQuery(
    `(min-width: ${base.theme.extend.screens.lg})`,
    serverFallback === null
      ? null
      : serverFallback === 'XL' || serverFallback === 'L',
  )
  const isM = useMediaQuery(
    `(min-width: ${base.theme.extend.screens.md})`,
    serverFallback === null
      ? null
      : serverFallback === 'XL' ||
          serverFallback === 'L' ||
          serverFallback === 'M',
  )
  const isS = useMediaQuery(
    `(min-width: ${base.theme.extend.screens.sm})`,
    serverFallback === null
      ? null
      : serverFallback === 'XL' ||
          serverFallback === 'L' ||
          serverFallback === 'M' ||
          serverFallback === 'S',
  )

  // If any query returns null, return null (waiting for hydration)
  if (isXL === null || isL === null || isM === null || isS === null) {
    return null
  }

  if (isXL) {
    return 'XL'
  }
  if (isL) {
    return 'L'
  }
  if (isM) {
    return 'M'
  }
  if (isS) {
    return 'S'
  }
  return 'XS'
}
