import React from "react"
import { ComponentName, LayoutComponentDefinition, LayoutComponentNode, LayoutContext, componentMap } from "./component-map"

export interface DynamicLayoutRendererProps {
  nodes: LayoutComponentNode[]
  context: LayoutContext
}

export function DynamicLayoutRenderer({ nodes, context } : DynamicLayoutRendererProps) {

  const nodeArray = Array.isArray(nodes) ? nodes : [nodes];

  return  nodeArray.map((entry, index) => {
      const [key, value] = Object.entries(entry)[0] as [ComponentName, LayoutComponentDefinition]

      if (!value) {
        console.warn(`[UI-Builder] Component definition is undefined: ${key}`);
        return null;
      }

      const component = componentMap[key];
      if (!component) {
        console.warn(`[UI-Builder] Unknown component: ${key}`);
        return null;
      }
      return <React.Fragment key={`${key}-${index}`}>{component.render(value, context)}</React.Fragment>
    })
}