import Script from 'next/script'

import { isClient } from '../constants'

declare global {
  interface Window {
    fontsReady: boolean
  }
}

const encodeBase64 = (str: string) => {
  return isClient ? window.btoa(str) : Buffer.from(str).toString('base64')
}

export const FontsReadyScript = () => {
  const encodedScript = `data:text/javascript;base64,${encodeBase64(`
  function onReady() {
    window.fontsReady = true
    document.documentElement.classList.add('fonts-ready')
  }
  try {
    document.fonts.ready
      .then(() => {
        onReady()
      })
      .catch(() => {
        onReady()
      })
  } catch (error) {
    onReady()
  }
`)}`

  return <Script strategy="beforeInteractive" src={encodedScript} />
}
