import { render, RenderOptions, RootPart } from 'lit'
import type { Fragment } from '../Fragment.js'
import { Renderer, renderFn } from './Renderer.js'

export class FragmentRenderer extends Renderer {
  constructor(protected fragment: Fragment) {
    super()
  }

  [renderFn](): void {
    const root = this.renderRoot
    if (!root) {
      // return quietly. Fragments can be rendered directly.
      return
    }
    const fragment = this.fragment
    const host = fragment.getSingleVisibleFragment() || fragment
    if (!this.firstRendered) {
      this.firstRenderedFlag = true
      // cleanup any pre-existing content.
      Array.from(root.childNodes).forEach((node) => root.parentNode?.removeChild(node))
      setTimeout(() => host.onFirstRender())
    }
    const litPart = root as unknown as HTMLElement & { _$litPart$?: RootPart }
    if (litPart._$litPart$) {
      ;(litPart._$litPart$.options as RenderOptions).host = host
    }
    // console.log(host, root)
    render(host.render(), root, { host })
    this.resolveUpdatePromise()
    // this.app.onRendered()
  }
}
