import Antd from 'ant-design-vue'
import { createCache, extractStyle } from 'ant-design-vue/es/_util/cssinjs'

function parseStyleTags(styleHTML: string) {
  const tags: Array<Record<string, any>> = []
  const styleTagRe = /<style([^>]*)>([\s\S]*?)<\/style>/gi
  let match: RegExpExecArray | null

  while ((match = styleTagRe.exec(styleHTML))) {
    const rawAttrs = (match[1] || '').trim()
    const children = match[2] || ''
    const props: Record<string, any> = { children }

    const attrRe = /([^\s=]+)\s*=\s*"([^"]*)"/g
    let a: RegExpExecArray | null
    while ((a = attrRe.exec(rawAttrs))) {
      const key = a[1]
      const value = a[2]
      props[key] = value
    }

    tags.push(props)
  }

  return tags
}

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(Antd)

  // Ant Design Vue 4 uses css-in-js for component styles. Without SSR extraction,
  // users will see a flash of unstyled content on refresh until hydration completes.
  const cssinjsCache = createCache()
  ;(nuxtApp.vueApp.config.globalProperties as any).__ANTDV_CSSINJS_CACHE__ = cssinjsCache

  if (import.meta.server) {
    nuxtApp.hook('app:rendered', ({ ssrContext }) => {
      if (!ssrContext) return
      const styleText = extractStyle(cssinjsCache)
      const styleTags = parseStyleTags(styleText)
      if (styleTags.length) {
        ssrContext.head.push({ style: styleTags as any })
      }
    })
  }
})
