/**
 * Compiles pattern-ui's styles with Tailwind and rebuilds as classes appear on the page, so any
 * element can use the theme's classes. Load it with `<script type="module" src>`, or load
 * `play-cdn.js`, which loads this and `play-cdn-tsx.js`.
 */
import type * as Tailwind from 'tailwindcss'

const cdnUrl =
  globalThis.patternPlayCdnUrl ?? ((specifier: string) => `https://esm.sh/${specifier}`)
const stylesUrl = new URL('../src/styles.css', import.meta.url).href

async function loadStylesheet(id: string, base: string) {
  const url = id === 'tailwindcss' ? cdnUrl('tailwindcss/index.css') : new URL(id, base).href
  if (globalThis.patternPlayCdnCss) {
    return { path: url, base: url, content: await globalThis.patternPlayCdnCss(url) }
  }
  const response = await fetch(url)
  if (!response.ok) throw new Error(`${response.status} loading ${response.url}`)
  return { path: response.url, base: response.url, content: await response.text() }
}

async function startTailwind() {
  const { compile }: typeof Tailwind = await import(cdnUrl('tailwindcss'))
  // Tailwind leaves `@import "https://…"` to the browser, so compile the entry's text directly.
  const styles = await loadStylesheet(stylesUrl, stylesUrl)
  const compiler = await compile(styles.content, {
    base: styles.base,
    loadStylesheet,
    loadModule() {
      throw new Error('pattern-ui play-cdn does not support Tailwind plugins or config files.')
    },
  })

  const sheet = document.createElement('style')
  document.head.append(sheet)
  const seen = new Set<string>()
  function build() {
    const added: string[] = []
    for (const element of document.querySelectorAll('[class]')) {
      for (const name of element.classList) {
        if (seen.has(name)) continue
        seen.add(name)
        added.push(name)
      }
    }
    if (added.length > 0) sheet.textContent = compiler.build(added)
  }
  build()
  new MutationObserver(build).observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['class'],
    childList: true,
    subtree: true,
  })
}

void startTailwind()
