/**
 * Storybook preview: MSW intercepts all API calls when run via `npm run storybook` / `npm run build-storybook`.
 * Those scripts set VITE_API_URL=/api/v1 (same-origin) and VITE_STORYBOOK=true (logger does not send to backend).
 * Do not run Storybook with an absolute API URL or MSW will not intercept.
 */
import type { Preview } from '@storybook/react';
import { initialize, mswLoader } from 'msw-storybook-addon';
import { handlers } from '../src/mocks/handlers';
import '../src/index.css';
import '../src/lib/i18n'; // Initialize i18n
import { StorybookDecorator } from './decorators';

// Custom viewports for responsive testing
const customViewports = {
    mobile: {
        name: 'Mobile',
        styles: {
            width: '375px',
            height: '667px',
        },
    },
    tablet: {
        name: 'Tablet',
        styles: {
            width: '768px',
            height: '1024px',
        },
    },
    desktop: {
        name: 'Desktop',
        styles: {
            width: '1440px',
            height: '900px',
        },
    },
};

// Initialize MSW: strict mode — any unhandled request throws in console and fails the story.
initialize({
    onUnhandledRequest: 'error',
    serviceWorker: {
        url: './mockServiceWorker.js',
    },
});

const preview: Preview = {
    parameters: {
        msw: {
            handlers,
        },
        controls: {
            matchers: {
                color: /(background|color)$/i,
                date: /Date$/i,
            },
            expanded: true,
        },
        a11y: {
            test: 'error-on-violation',
        },
        viewport: {
            options: customViewports,
        },
        backgrounds: {
            options: {
                dark: { name: 'dark', value: '#121215' },
                light: { name: 'light', value: '#faf9f6' },
                raised: { name: 'raised', value: '#1a1a1f' }
            }
        },
        layout: 'centered',
        docs: {
            toc: true, // Enable table of contents in docs
        },
    },

    decorators: [StorybookDecorator],
    tags: ['autodocs'],
    loaders: [mswLoader],

    initialGlobals: {
        backgrounds: {
            value: 'dark'
        }
    }
};

export default preview;
