'use client'

import { mergeProps } from '@zag-js/react'
import { forwardRef } from 'react'
import { createSplitProps } from '../../utils/create-split-props.ts'
import { type HTMLProps, type PolymorphicProps, ark } from '../factory.ts'
import type { UseScrollAreaReturn } from './use-scroll-area.ts'
import { ScrollAreaProvider } from './use-scroll-area-context.ts'

interface RootProviderProps {
  value: UseScrollAreaReturn
}

export interface ScrollAreaRootProviderBaseProps extends RootProviderProps, PolymorphicProps {}
export interface ScrollAreaRootProviderProps extends HTMLProps<'div'>, ScrollAreaRootProviderBaseProps {}

const splitRootProviderProps = createSplitProps<RootProviderProps>()

export const ScrollAreaRootProvider = forwardRef<HTMLDivElement, ScrollAreaRootProviderProps>((props, ref) => {
  const [{ value: scrollArea }, localProps] = splitRootProviderProps(props, ['value'])
  const mergedProps = mergeProps(scrollArea.getRootProps(), localProps)

  return (
    <ScrollAreaProvider value={scrollArea}>
      <ark.div {...mergedProps} ref={ref} />
    </ScrollAreaProvider>
  )
})

ScrollAreaRootProvider.displayName = 'ScrollAreaRootProvider'
