import * as React from 'react'
import { cn } from './utils'
import { TreemapChart as TreemapChartImpl } from '../../charts/treemap/index'
import type { TreemapChartConfig, TreemapNode } from '../../charts/treemap/types'

export interface TreemapChartProps extends Omit<TreemapChartConfig, 'container'> {
  className?: string
}

function TreemapChart({ className, ...config }: TreemapChartProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const chartRef = React.useRef<TreemapChartImpl | null>(null)

  React.useEffect(() => {
    if (!containerRef.current) return
    chartRef.current = new TreemapChartImpl({ ...config, container: containerRef.current })
    return () => {
      chartRef.current?.destroy()
      chartRef.current = null
    }
  }, [])

  React.useEffect(() => {
    if (chartRef.current && config.data) {
      chartRef.current.update(config.data)
    }
  }, [config.data])

  return <div ref={containerRef} data-slot="treemap-chart" className={cn('w-full', className)} />
}

export { TreemapChart }
export type { TreemapNode }
