import { Engine, API } from '@seamly/web-ui'
import { render } from 'preact'
import StyleGuideApp from './components/app'

class SeamlyStyleGuideInstance extends Engine {
  styleGuideConfig: any

  constructor({ styleGuideConfig, ...config }: any, externalApi) {
    super(config, externalApi)
    this.styleGuideConfig = styleGuideConfig || {}
  }

  async render() {
    const restComponents = {
      ...(this.config.customComponents || {}),
      view: undefined,
    }

    const api = new API({
      namespace: this.config.namespace || '',
      config: this.config.api,
      context: this.config.context,
      layoutMode: this.config.layoutMode,
    })

    const translations = await api.getTranslations(
      this.config.context?.userLocale || 'en-GB',
    )
    const { agentParticipant, userParticipant } = await api.getConfig()
    const participants = [
      {
        id: 'user',
        ...userParticipant,
      },
      {
        id: 'agent',
        introduction: 'I am {{name}}',
        ...agentParticipant,
      },
    ]
    const renderConfig = {
      ...this.config,
      customComponents: Object.keys(restComponents).length
        ? restComponents
        : undefined,
    }

    render(
      <StyleGuideApp
        config={renderConfig}
        styleGuideConfig={this.styleGuideConfig}
        translations={translations}
        participants={participants}
      />,
      this.parentElement,
    )
  }
}

export default SeamlyStyleGuideInstance
