import WidgetErrorBoundary from './WidgetErrorBoundary'

/**
 * @typedef {object} LayoutWidgetEntry
 * @property {string} id
 * @property {boolean} enabled
 * @property {Record<string, unknown>} [config]
 */
/**
 * @typedef {{ refreshTick: number, requestRefresh: () => void, layoutEntry: LayoutWidgetEntry }} WidgetRenderContext
 */

const registry = new Map()

/**
 * @param {{ id: string, Component: import('react').ComponentType<any>, mapProps?: (ctx: WidgetRenderContext) => Record<string, unknown> }} spec
 */
export function registerDashboardWidget(spec) {
  if (!spec?.id || !spec?.Component) {
    console.warn('registerDashboardWidget: id und Component erforderlich', spec)
    return
  }
  registry.set(spec.id, spec)
}

export function getRegisteredWidgetIds() {
  return [...registry.keys()]
}

export function clearDashboardWidgetRegistry() {
  registry.clear()
}

/**
 * Nur für Tests: Registry neu füllen.
 */
export function __resetDashboardWidgetRegistryForTests() {
  registry.clear()
}

/**
 * @param {string} id
 * @param {WidgetRenderContext} ctx
 */
export function renderRegisteredWidget(id, ctx) {
  const spec = registry.get(id)
  if (!spec) {
    return (
      <div key={id} className="card" style={{ borderColor: 'var(--danger, #D85A30)', marginBottom: 16 }}>
        <strong>Unbekanntes Widget</strong>
        <div style={{ fontSize: 13, color: 'var(--text2)' }}>{id}</div>
      </div>
    )
  }
  const { Component } = spec
  const props = spec.mapProps ? spec.mapProps(ctx) : {}
  return (
    <WidgetErrorBoundary key={id} widgetId={id}>
      <Component {...props} />
    </WidgetErrorBoundary>
  )
}

/**
 * Rendert alle aktivierten Widgets in Layout-Reihenfolge.
 * @param {{ version: number, widgets: Array<LayoutWidgetEntry> }} layout
 * @param {{ refreshTick: number, requestRefresh: () => void }} base
 */
export function WidgetRenderer({ layout, refreshTick, requestRefresh }) {
  if (!layout?.widgets?.length) return null
  const enabled = layout.widgets.filter((w) => w.enabled)
  return (
    <>
      {enabled.map((w) =>
        renderRegisteredWidget(w.id, {
          refreshTick,
          requestRefresh,
          layoutEntry: w,
        })
      )}
    </>
  )
}
