import * as React from 'react'
import { cn } from './utils'
import { FunnelChart as FunnelChartImpl } from '../../charts/funnel/index'
import type { FunnelChartConfig, FunnelSegment } from '../../charts/funnel/types'

export interface FunnelChartProps extends Omit<FunnelChartConfig, 'container'> {
  className?: string
}

function FunnelChart({ className, ...config }: FunnelChartProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const chartRef = React.useRef<FunnelChartImpl | null>(null)

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

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

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

export { FunnelChart }
export type { FunnelSegment }
