import global from 'global';

import { PreviewWeb } from '@storybook/preview-web';
import { composeConfigs } from '@storybook/store';
import { ClientApi } from '@storybook/client-api';
import { addons } from '@storybook/addons';
import { createChannel as createPostMessageChannel } from '@storybook/channel-postmessage';
import { createChannel as createWebSocketChannel } from '@storybook/channel-websocket';

import { importFn } from './{{storiesFilename}}';

const { SERVER_CHANNEL_URL } = global;

const getProjectAnnotations = () =>
  composeConfigs([{{#each configs}}require('{{this}}'),{{/each}}]);

const channel = createPostMessageChannel({ page: 'preview' });
addons.setChannel(channel);

if (SERVER_CHANNEL_URL) {
  const serverChannel = createWebSocketChannel({ url: SERVER_CHANNEL_URL, });
  addons.setServerChannel(serverChannel);
  window.__STORYBOOK_SERVER_CHANNEL__ = serverChannel;
}

const preview = new PreviewWeb();

window.__STORYBOOK_PREVIEW__ = preview;
window.__STORYBOOK_STORY_STORE__ = preview.storyStore;
window.__STORYBOOK_ADDONS_CHANNEL__ = channel;
window.__STORYBOOK_CLIENT_API__ = new ClientApi({ storyStore: preview.storyStore });

preview.initialize({ importFn, getProjectAnnotations });

if (module.hot) {
  import.meta.webpackHot.accept('./{{storiesFilename}}', () => {
    // importFn has changed so we need to patch the new one in
    preview.onStoriesChanged({ importFn });
  });

  import.meta.webpackHot.accept([{{#each configs}}'{{this}}',{{/each}}], () => {
    // getProjectAnnotations has changed so we need to patch the new one in
    preview.onGetProjectAnnotationsChanged({ getProjectAnnotations });
  });
}