import type { Preview } from '@storybook/react-vite'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { initialize, mswLoader } from 'msw-storybook-addon'
import { MemoryRouter } from 'react-router-dom'

import '../src/index.css'
import '../src/i18n'
import { LOCALE_KEY } from '../src/i18n'
import { ConfigProvider } from '../src/config/config-provider'
import { handlers } from '../src/test/handlers'

initialize({ onUnhandledRequest: 'bypass' })

const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
       color: /(background|color)$/i,
       date: /Date$/i,
      },
    },

    a11y: {
      // 'todo' - show a11y violations in the test UI only
      // 'error' - fail CI on a11y violations
      // 'off' - skip a11y checks entirely
      test: 'todo'
    },

    msw: { handlers },
  },
  loaders: [mswLoader],
  beforeEach() {
    // Pin the UI language so text-based assertions are deterministic; also
    // stops ConfigProvider from switching to the instance default at runtime.
    localStorage.setItem(LOCALE_KEY, 'en')
  },
  decorators: [
    (Story) => {
      const queryClient = new QueryClient({
        defaultOptions: { queries: { retry: false } },
      })

      return (
        <QueryClientProvider client={queryClient}>
          <ConfigProvider>
            <MemoryRouter>
              <Story />
            </MemoryRouter>
          </ConfigProvider>
        </QueryClientProvider>
      )
    },
  ],
};

export default preview;
