"use client"

import * as React from "react"

export type Direction = "ltr" | "rtl"

export function useDirection(defaultDirection: Direction = "ltr") {
  const [direction, setDirection] = React.useState<Direction>(defaultDirection)

  React.useEffect(() => {
    const htmlDirection = document.documentElement.getAttribute("dir")

    if (htmlDirection === "ltr" || htmlDirection === "rtl") {
      setDirection(htmlDirection)
      return
    }

    document.documentElement.setAttribute("dir", defaultDirection)
  }, [defaultDirection])

  const updateDirection = React.useCallback((nextDirection: Direction) => {
    document.documentElement.setAttribute("dir", nextDirection)
    setDirection(nextDirection)
  }, [])

  return [direction, updateDirection] as const
}
