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

import { Progress } from './progress'

const meta = {
  title: 'Progress',
  component: Progress,
  tags: ['autodocs'],
  parameters: {
    layout: 'centered',
  },
  argTypes: {
    value: {
      control: { type: 'range', min: 0, max: 1, step: 0.01 },
      description: 'Current progress value (0-100)',
    },
    size: {
      description: 'css value for width of the progress bar',
    },
  },
  args: {
    size: '100%',
  },
} satisfies Meta<typeof Progress>
export default meta

type Story = StoryObj<typeof meta>

export const Default: Story = {
  args: {
    value: 0.5,
    size: '100%',
  },
  render: (args) => (
    <div className="w-[200px]">
      <Progress value={args.value} size={args.size} />
    </div>
  ),
}

const testValues = [0, 0.283, 0.8731, 1]

export const ValueRatioTest: Story = {
  args: { value: 0, size: '200px' },
  render: () => (
    <div>
      {testValues.map((v, idx) => (
        <div key={idx} data-testid={`progress-${idx}`}>
          <Progress value={v} size="200px" />
        </div>
      ))}
    </div>
  ),
  play: async () => {
    function getFilledWidth(testId: string) {
      const container = screen.getByTestId(testId)
      const filled = container.querySelector('[data-testid="progress-filled"]')
      return filled ? filled.getBoundingClientRect().width : 0
    }
    function getBgWidth(testId: string) {
      const container = screen.getByTestId(testId)
      const bg = container.querySelector('[data-testid="progress-bg"]')
      return bg ? bg.getBoundingClientRect().width : 0
    }

    testValues.forEach((v, idx) => {
      const width = getFilledWidth(`progress-${idx}`)
      const bgWidth = getBgWidth(`progress-${idx}`)
      if (v === 0) {
        expect(width).toBeCloseTo(0, 1)
      } else if (v === 1) {
        expect(width).toBeCloseTo(bgWidth, 1)
      } else {
        expect(width).toBeCloseTo(bgWidth * v, 1)
      }
      expect(bgWidth).toBeGreaterThan(0)
    })
  },
}
