/**
 * Compiles each `<script type="text/tsx">` on the page with Sucrase and runs it as a module script,
 * with its bare imports loaded from esm.sh. Load it with `<script type="module" src>`, or load
 * `play-cdn.js`, which loads this and `play-cdn-tailwind.js`.
 */
interface Sucrase {
  transform: (
    code: string,
    options: { transforms: string[]; jsxRuntime: 'automatic'; production: boolean },
  ) => { code: string }
}

interface ModuleImport {
  type: string
  specifier?: string | null
  start: number
  end: number
}

interface ModuleLexer {
  init: () => Promise<void>
  parse: (code: string) => readonly [readonly ModuleImport[]]
}

const cdnUrl =
  globalThis.patternPlayCdnUrl ?? ((specifier: string) => `https://esm.sh/${specifier}`)

// Point each bare import (`from '…'`, `import '…'`, `import('…')`) at its CDN URL. Relative paths
// and absolute URLs are left as they are. The lexer only reports real imports, so code text that
// looks like an import (such as `from "` inside a JSX string) is left alone.
function rewriteImports(code: string, { parse }: ModuleLexer) {
  let rewritten = ''
  let copied = 0
  for (const { type, specifier, start, end } of parse(code)[0]) {
    if (!specifier || /^(\.|\/|[a-z]+:)/.test(specifier)) continue
    const url = cdnUrl(specifier)
    // Dynamic import positions include the quotes; static ones don't.
    rewritten += code.slice(copied, start) + (type === 'dynamic' ? JSON.stringify(url) : url)
    copied = end
  }
  return rewritten + code.slice(copied)
}

function runScripts({ transform }: Sucrase, lexer: ModuleLexer) {
  for (const source of document.querySelectorAll('script[type="text/tsx"]')) {
    const { code } = transform(source.textContent ?? '', {
      transforms: ['typescript', 'jsx'],
      jsxRuntime: 'automatic',
      production: true,
    })
    const script = document.createElement('script')
    script.type = 'module'
    script.textContent = rewriteImports(code, lexer)
    source.after(script)
  }
}

async function loadLexer() {
  // Pinned to a major version: v3 renamed the fields `parse` returns.
  const lexer = (await import(cdnUrl('es-module-lexer@3'))) as ModuleLexer
  await lexer.init()
  return lexer
}

const ready = Promise.all([
  import(cdnUrl('sucrase')) as Promise<Sucrase>,
  loadLexer(),
  document.readyState === 'loading'
    ? new Promise((resolve) =>
        document.addEventListener('DOMContentLoaded', resolve, { once: true }),
      )
    : undefined,
])
void ready.then(([sucrase, lexer]) => runScripts(sucrase, lexer))
