import { colormode } from '@/clientsettings/vars/colormode'
import DocViewerComponent from '@/components/DocViewer/DocViewerComponent'
import globalStyles from '@/global.scss?inline'
import { Classes } from '@blueprintjs/core'
import createCache from '@emotion/cache'
import { CacheProvider } from '@emotion/react'
import React from 'react'
import ReactDOM from 'react-dom/client'

class DocViewerElement extends HTMLElement {
  constructor() {
    super()
    this.attachShadow({ mode: 'open' })
  }

  connectedCallback() {
    const shadowRoot = this.shadowRoot
    if (!shadowRoot) {
      return
    }

    // import global (blueprintjs) styles
    const style = document.createElement('style')
    style.textContent = globalStyles
    shadowRoot.appendChild(style)

    const root = document.createElement('span')
    shadowRoot.appendChild(root)

    // set initial dark mode; TODO: consider subscribing to changes
    if (colormode()) {
      root.classList.add(Classes.DARK)
    }

    // create cache for emotion
    const cache = createCache({
      key: 'css',
      prepend: true,
      container: this.shadowRoot,
    })

    const teamId = this.getAttribute('team_id')
    const fileId = this.getAttribute('file_info_id')
    const fileName = this.getAttribute('file_name')
    if (!teamId || !fileId || !fileName) {
      throw new Error(
        'team_id, file_info_id, and file_name are required attributes'
      )
    }

    ReactDOM.createRoot(root).render(
      <React.StrictMode>
        <CacheProvider value={cache}>
          <DocViewerComponent
            teamId={teamId}
            fileId={fileId}
            inInstructor={this.getAttribute('in_instructor') === 'true'}
            fileName={fileName}
            contentOnly
          />
        </CacheProvider>
      </React.StrictMode>
    )
  }
}

export default DocViewerElement
