import { useEffect, type ReactNode } from 'react';
import type { Preview, Decorator } from 'storybook-react-rsbuild';
import { Tooltip } from 'radix-ui';

/* The shipped library surface, exactly as a consumer would load it.
   Fonts are self-hosted via fonts.css and inlined at build time; for the
   dev/storybook build they're loaded through preview-head.html instead,
   to avoid bundler inlining the @import url() mid-stylesheet. */
import '../src/styles/index.css';
/* Storybook-only canvas styling (background, docs blocks). */
import './preview.css';
import theme from './theme';

/* Toolbar theme switch → drives `data-theme` on <html>, same lever as the
   library's ThemeProvider. The frame stays content-sized; the canvas
   background comes from preview.css, so stories never balloon to full-viewport. */
function ThemeFrame({ theme, children }: { theme: string; children: ReactNode }) {
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  return <Tooltip.Provider delayDuration={200}>{children}</Tooltip.Provider>;
}

const withMtAir: Decorator = (Story, context) => (
  <ThemeFrame theme={(context.globals.theme as string) ?? 'light'}>
    <Story />
  </ThemeFrame>
);

const preview: Preview = {
  tags: ['autodocs'],
  decorators: [withMtAir],
  parameters: {
    layout: 'centered',
    backgrounds: { disable: true },
    docs: { theme },
    controls: {
      matchers: { color: /(background|color)$/i, date: /Date$/i },
    },
    options: {
      storySort: { order: ['Getting Started', 'Inputs', 'Selection', 'Feedback', 'Overlays', 'Data Display', 'Layout'] },
    },
  },
  globalTypes: {
    theme: {
      description: 'MtAir theme',
      defaultValue: 'light',
      toolbar: {
        title: 'Theme',
        icon: 'contrast',
        items: [
          { value: 'light', title: 'Light', icon: 'sun' },
          { value: 'dark', title: 'Dark', icon: 'moon' },
        ],
        dynamicTitle: true,
      },
    },
  },
};

export default preview;
