import { ReactNode, useRef, useState } from 'react'
import { StyleSheetManager } from 'styled-components'
import React from 'react'

export const MainComponentWrapper = ({ children }: { children: ReactNode }) => {
  const [ref, setRef] = useState<HTMLDivElement | null>()
  const styleRef = useRef<any>()
  const [cssIsInjected, setCssIsInjected] = useState(false)

  if (styleRef.current) {
    styleRef.current.onload = () => {
      setCssIsInjected(true)
    }
    styleRef.current.onerror = () => {
      // if we don't have any css file (if you use styled components only)
      setCssIsInjected(true)
    }
  }
  return (
    <div ref={(newRef) => setRef(newRef)}>
      <link
        ref={styleRef}
        rel='stylesheet'
        // @ts-ignore
        href={import.meta.env.BASE_URL + 'main.css'}
      />
      {ref && cssIsInjected && (
        <>
          <StyleSheetManager target={ref}>
            {children}
          </StyleSheetManager>
        </>
      )}
    </div>
  )
}
