import { useEffect, useRef } from 'react'

const BASE_WIDTH = 1920
const BASE_HEIGHT = 1080

export function useScale() {
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    function scale() {
      const el = ref.current
      if (!el) return

      const scaleX = window.innerWidth / BASE_WIDTH
      const scaleY = window.innerHeight / BASE_HEIGHT
      const s = Math.min(scaleX, scaleY)

      el.style.transform = `scale(${s})`
      el.style.transformOrigin = 'top left'
      el.style.width = `${BASE_WIDTH}px`
      el.style.height = `${BASE_HEIGHT}px`
      el.style.position = 'absolute'
      el.style.left = `${(window.innerWidth - BASE_WIDTH * s) / 2}px`
      el.style.top = `${(window.innerHeight - BASE_HEIGHT * s) / 2}px`
      el.style.overflow = 'hidden'
    }

    scale()
    window.addEventListener('resize', scale)
    return () => window.removeEventListener('resize', scale)
  }, [])

  return ref
}
