import React from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { InventoryGUI, type InventoryGUIProps } from './InventoryGUI'

export interface MountedInventory {
  update(props: Partial<InventoryGUIProps>): void
  destroy(): void
}

/**
 * Mount an inventory GUI into a DOM element without writing React code.
 *
 * ```js
 * import { mountInventory, createDemoConnector } from 'minecraft-inventory'
 *
 * const connector = createDemoConnector({ windowType: 'chest', slots: [] })
 * const inv = mountInventory(document.getElementById('root'), {
 *   type: 'chest',
 *   connector,
 *   scale: 2,
 * })
 *
 * // Later: update props
 * inv.update({ scale: 3 })
 *
 * // Cleanup
 * inv.destroy()
 * ```
 */
export function mountInventory(
  container: HTMLElement,
  initialProps: InventoryGUIProps,
): MountedInventory {
  let currentProps = { ...initialProps }
  const root: Root = createRoot(container)

  function render() {
    root.render(<InventoryGUI {...currentProps} />)
  }

  render()

  return {
    update(props: Partial<InventoryGUIProps>) {
      currentProps = { ...currentProps, ...props }
      render()
    },
    destroy() {
      root.unmount()
    },
  }
}
