<script lang="ts">
import type { HTMLAttributes } from 'vue'
import type { Assign, BooleanDefaults } from '../../types.ts'
import type { RenderStrategyProps } from '../../utils/use-render-strategy.ts'
import type { CollectionItem } from '../collection/index.ts'
import type { PolymorphicProps } from '../factory.ts'
import type { RootEmits, RootProps } from './select.types.ts'

export interface SelectRootBaseProps<T extends CollectionItem>
  extends RootProps<T>, RenderStrategyProps, PolymorphicProps {}
export interface SelectRootProps<T extends CollectionItem>
  extends
    SelectRootBaseProps<T>,
    /**
     * @vue-ignore
     */
    Omit<HTMLAttributes, 'onSelect'> {}

export type SelectRootComponentProps<T extends CollectionItem = CollectionItem, P = {}> = Assign<SelectRootProps<T>, P>

export type SelectRootComponent<P = {}> = <T extends CollectionItem>(props: SelectRootComponentProps<T, P>) => any

export type { RootEmits as SelectRootEmits } from './select.types.ts'
</script>

<script setup lang="ts" generic="T extends CollectionItem">
import { computed } from 'vue'
import { RenderStrategyPropsProvider } from '../../utils/use-render-strategy.ts'
import { useForwardExpose } from '../../utils/use-forward-expose.ts'
import { ark } from '../factory.ts'
import { PresenceProvider, usePresence } from '../presence/index.ts'
import { useSelect } from './use-select.ts'
import { SelectProvider } from './use-select-context.ts'

const props = withDefaults(defineProps<SelectRootProps<T>>(), {
  closeOnSelect: undefined,
  composite: undefined,
  defaultOpen: undefined,
  deselectable: undefined,
  disabled: undefined,
  invalid: undefined,
  loopFocus: undefined,
  multiple: undefined,
  open: undefined,
  readOnly: undefined,
  required: undefined,
} satisfies BooleanDefaults<RootProps<T>>)

const emits = defineEmits<RootEmits<T>>()

const select = useSelect(props, emits)

const presence = usePresence(
  computed(() => ({
    present: select.value.open,
    lazyMount: props.lazyMount,
    unmountOnExit: props.unmountOnExit,
  })),
  emits,
)

SelectProvider(select)
PresenceProvider(presence)

RenderStrategyPropsProvider(
  computed(() => ({
    lazyMount: props.lazyMount,
    unmountOnExit: props.unmountOnExit,
  })),
)

useForwardExpose()
</script>

<template>
  <ark.div v-bind="select.getRootProps()" :as-child="asChild">
    <slot />
  </ark.div>
</template>
