'use client'

import {
  useCallback,
  useEffect,
  useRef,
  useState,
  type ReactNode,
  type HTMLAttributes,
} from 'react'
import { cn } from './utils'

export interface ChartFrameProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
  children: (size: { width: number; height: number }) => ReactNode
  minHeight?: number
}

function ChartFrame({ children, minHeight = 200, className, style, ...props }: ChartFrameProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const [size, setSize] = useState<{ width: number; height: number } | null>(null)

  const measure = useCallback(() => {
    if (!containerRef.current) return
    const { width, height } = containerRef.current.getBoundingClientRect()
    const w = Math.floor(width)
    const h = Math.floor(height)
    setSize(prev => {
      if (prev && prev.width === w && prev.height === h) return prev
      return { width: w, height: h }
    })
  }, [])

  useEffect(() => {
    const el = containerRef.current
    if (!el) return
    measure()
    if (typeof globalThis.ResizeObserver !== 'function') {
      window.addEventListener('resize', measure)
      return () => window.removeEventListener('resize', measure)
    }
    const observer = new globalThis.ResizeObserver(measure)
    observer.observe(el)
    return () => observer.disconnect()
  }, [measure])

  return (
    <div
      ref={containerRef}
      className={cn('w-full', className)}
      style={{ minHeight, ...style }}
      {...props}
    >
      {size ? children(size) : null}
    </div>
  )
}
ChartFrame.displayName = 'ChartFrame'
export { ChartFrame }
