import type { StorybookConfig } from '@storybook/svelte-vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import tailwindcss from '@tailwindcss/vite';

const config: StorybookConfig = {
  stories: ['../src/lib/ui/**/*.stories.@(js|jsx|ts|tsx|svelte)'],
  framework: {
    name: '@storybook/svelte-vite',
    options: {},
  },
  docs: {
    /** Name der automatisch erzeugten Docs-Seite pro Komponente */
    defaultName: 'Dokumentation',
  },
  viteFinal: async (config) => {
    config.plugins = config.plugins || [];
    // Svelte-Plugin explizit vorn einfügen, damit .svelte-Dateien (auch aus node_modules/@storybook/svelte)
    // vor dem Vite-Import-Analysis-Plugin transformiert werden – nötig für Astro-Projekte ohne eigene vite.config
    const sveltePlugins = svelte({
      compilerOptions: {
        runes: true,
      },
      include: ['**/*.svelte', '**/node_modules/@storybook/svelte/**/*.svelte'],
    });
    config.plugins.unshift(...sveltePlugins);
    config.plugins.push(tailwindcss());
    config.optimizeDeps = config.optimizeDeps ?? {};
    config.optimizeDeps.exclude = [...(config.optimizeDeps.exclude ?? []), '@storybook/svelte'];
    config.ssr = config.ssr ?? {};
    const existing = config.ssr.noExternal;
    const noExternalList = Array.isArray(existing)
      ? existing
      : existing
        ? [existing]
        : [];
    const normalized = noExternalList.filter(
      (x): x is string | RegExp => typeof x === 'string' || x instanceof RegExp
    );
    config.ssr.noExternal = [...normalized, '@storybook/svelte'];
    return config;
  },
};

export default config;
