import { h, render } from 'preact'
import { injectStyles } from './twind.js'

// Web component registration function with hook cleanup.
export default function register (Component, elementName) {
  class CustomElement extends HTMLElement {
    connectedCallback () {
      this.shadow = this.attachShadow({ mode: 'open' })
      this.attrs = Object.fromEntries(Array.from(this.attributes, ({ name, value }) => [name, value]))
      this.vnode = h(Component, this.attrs)

      injectStyles(this.shadow)
      render(this.vnode, this.shadow)
    }

    disconnectedCallback () {
      // Call cleanup functions for all hooks.
      // Based on https://github.com/preactjs/preact/blob/main/hooks/src/index.js
      for (const hook of this.vnode?.__c?.__H?.__ || []) {
        hook?.__c?.call?.()
      }
    }
  }

  customElements.get(elementName) || customElements.define(elementName, CustomElement)
}
