import { nothing, type TemplateResult } from 'lit'
import type { Application } from '../Application.js'
import type { Activity } from '../Activity.js'
import { Renderer } from './Renderer.js'
import { ModalActivity } from '../ModalActivity.js'

export class ApplicationRenderer extends Renderer {
  renderedFirst: WeakMap<Application | Activity, boolean>

  constructor(protected app: Application) {
    super()
    this.renderedFirst = new WeakMap()
  }

  private _handleFirstRender(target: Application | Activity, clearRoot: boolean, root: HTMLElement): void {
    if (!this.renderedFirst.has(target)) {
      this.renderedFirst.set(target, true)
      if (clearRoot) {
        this._clearRoot(root)
      }
      queueMicrotask(() => target.onFirstRender())
    }
  }

  protected renderer(): void {
    const { app, renderRoot: defaultRenderRoot } = this
    const activity = app.manager.getTopActivity()

    const host: Application | Activity = activity || app
    const root: HTMLElement | null = activity?.renderRoot || defaultRenderRoot

    let content: TemplateResult | typeof nothing
    if (activity instanceof ModalActivity) {
      content = activity.renderDialog()
    } else {
      content = host.render()
    }
    if (!root) {
      // eslint-disable-next-line no-console
      console.warn(`The "renderRoot" is not set up.`)
      return
    }
    this._handleFirstRender(app, true, root)
    if (!this.firstRendered) {
      this.firstRenderedFlag = true
    }
    if (host !== app) {
      this._handleFirstRender(host, false, root)
    }
    this._render(content, root, host)
    this.app.onRendered()
  }
}
