import * as React from 'react'

import type { GlobalTypes } from '@storybook/csf'
import type { Preview, StoryContext, StoryFn } from '@storybook/react'
import { I18nextProvider } from 'react-i18next'
import i18n from 'web/src/i18n'

/** @see {@link https://storybook.js.org/docs/7/essentials/toolbars-and-globals#global-types-and-the-toolbar-annotation | Global types and the toolbar annotation}  */
export const globalTypes: GlobalTypes = {
  locale: {
    name: 'Locale',
    description: 'Internationalization locale',
    defaultValue: 'en',
    toolbar: {
      icon: 'globe',
      items: [
        { value: 'en', right: '🇺🇸', title: 'English' },
        { value: 'fr', right: '🇫🇷', title: 'Français' },
      ],
    },
  },
}

/**
 * @see {@link https://storybook.js.org/docs/7/essentials/toolbars-and-globals#create-a-decorator | Create a decorator}
 */
const withI18n = function WithI18n(Story: StoryFn, context: StoryContext) {
  React.useEffect(() => {
    i18n.changeLanguage(context.globals.locale)
  }, [context.globals.locale])

  return (
    <I18nextProvider i18n={i18n}>
      <Story />
    </I18nextProvider>
  )
}

const preview: Preview = {
  decorators: [withI18n],
}

export default preview
