import { type ReactNode, useEffect } from "react"
import { useLayout } from "./layout-context"

type Breakpoints = {
  sm: boolean
  md: boolean
  lg: boolean
  xl: boolean
}

const breakpoints: Breakpoints = { sm: false, md: false, lg: false, xl: false }

export function useBreakpoint() {
  return breakpoints
}

export const bp = breakpoints

export default function Effects(props: { children?: ReactNode }) {
  const { setNavbar } = useLayout()

  useEffect(() => {
    const sm = window.matchMedia("(width >= 40rem)")
    const md = window.matchMedia("(width >= 48rem)")
    const lg = window.matchMedia("(width >= 64rem)")
    const xl = window.matchMedia("(width >= 80rem)")

    breakpoints.sm = sm.matches
    breakpoints.md = md.matches
    breakpoints.lg = lg.matches
    breakpoints.xl = xl.matches

    setNavbar(md.matches)

    sm.addEventListener("change", e => {
      breakpoints.sm = e.matches
    })
    md.addEventListener("change", e => {
      breakpoints.md = e.matches
      setNavbar(e.matches)
    })
    lg.addEventListener("change", e => {
      breakpoints.lg = e.matches
    })
    xl.addEventListener("change", e => {
      breakpoints.xl = e.matches
    })

    const html = document.documentElement
    const originalFontSize = html.style.fontSize
    html.style.fontSize = "16px"

    return () => {
      html.style.fontSize = originalFontSize
    }
  }, [setNavbar])

  return <>{props.children}</>
}
