import { render } from 'hono/jsx/dom'
import type { Child } from 'hono/jsx'

let globalRenderFn: (() => void) | null = null

export const initUpdate = (renderFn: () => void) => {
  globalRenderFn = renderFn
}

/**
 * Update the UI from state.
 *
 * update()                              - redraw everything
 * update('#emoji-results', <Results />) - target specific element
 */
export function update(): void
export function update(selector: string, component: Child): void
export function update(selector?: string, component?: Child) {
  if (selector && component !== undefined) {
    const el = document.querySelector(selector) as HTMLElement | null
    if (el) render(component, el)
  } else {
    globalRenderFn?.()
  }
}
