import { View, timeout } from '@seamly/web-ui'
import { useEffect, useState } from 'preact/hooks'
import StyleGuideStaticCore from './static-core'

const StyleGuideView = ({
  state,
  customComponents = {},
  translations,
  participants,
}) => {
  const [renderView, setRenderView] = useState(true)
  const { config } = state || {}
  const { layoutMode } = config || {}
  const CustomView = customComponents[layoutMode]

  // This ensures that the style guide view is completely
  // reconstructed for each state to avoid artifacts from previous
  // renders showing up.
  useEffect(() => {
    setRenderView(false)
    requestAnimationFrame(async () => {
      await timeout(60)
      setRenderView(true)
    })
  }, [state])

  if (!renderView) {
    return null
  }

  return CustomView ? (
    <StyleGuideStaticCore
      state={state}
      translations={translations}
      participants={participants}
    >
      <CustomView />
    </StyleGuideStaticCore>
  ) : (
    <StyleGuideStaticCore
      state={state}
      translations={translations}
      participants={participants}
    >
      <View />
    </StyleGuideStaticCore>
  )
}

export default StyleGuideView
