import type { Meta, StoryObj } from '@storybook/react-vite'
import { useState } from 'react'
import { expect, within } from 'storybook/test'

import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './select'

function Controlled() {
  const [value, setValue] = useState('')
  return (
    <Select value={value} onValueChange={(next) => setValue(next ?? '')}>
      <SelectTrigger aria-label="Fruit">
        <SelectValue placeholder="Pick one" />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value="apple">Apple</SelectItem>
        <SelectItem value="pear">Pear</SelectItem>
        <SelectItem value="plum">Plum</SelectItem>
      </SelectContent>
    </Select>
  )
}

const meta = {
  component: Select,
  tags: ['ai-generated'],
  render: () => <Controlled />,
} satisfies Meta<typeof Select>

export default meta
type Story = StoryObj<typeof meta>

export const Default: Story = {
  play: async ({ canvas, userEvent }) => {
    await userEvent.click(canvas.getByRole('combobox', { name: 'Fruit' }))
    await userEvent.click(await within(document.body).findByRole('option', { name: 'Pear' }))
    await expect(canvas.getByRole('combobox', { name: 'Fruit' })).toHaveTextContent('Pear')
  },
}
