export interface Component {
  id: string
  name: string
  type: string
  version: string
  description: string
  safety_relevant: boolean
  parent_id: string | null
  children: Component[]
  library_component_id?: string
  energy_source_ids?: string[]
}

export interface LibraryComponent {
  id: string
  name_de: string
  name_en: string
  category: string
  description_de: string
  typical_hazard_categories: string[]
  typical_energy_sources: string[]
  maps_to_component_type: string
  tags: string[]
  sort_order: number
}

export interface EnergySource {
  id: string
  name_de: string
  name_en: string
  description_de: string
  typical_components: string[]
  typical_hazard_categories: string[]
  tags: string[]
  sort_order: number
}

export interface ComponentFormData {
  name: string
  type: string
  version: string
  description: string
  safety_relevant: boolean
  parent_id: string | null
}

export const LIBRARY_CATEGORIES: Record<string, string> = {
  mechanical: 'Mechanik',
  structural: 'Struktur',
  drive: 'Antrieb',
  hydraulic: 'Hydraulik',
  pneumatic: 'Pneumatik',
  electrical: 'Elektrik',
  control: 'Steuerung',
  sensor: 'Sensorik',
  actuator: 'Aktorik',
  safety: 'Sicherheit',
  it_network: 'IT/Netzwerk',
}

export const COMPONENT_TYPES = [
  { value: 'SW', label: 'Software (SW)' },
  { value: 'FW', label: 'Firmware (FW)' },
  { value: 'AI', label: 'KI-Modul (AI)' },
  { value: 'HMI', label: 'Mensch-Maschine-Schnittstelle (HMI)' },
  { value: 'SENSOR', label: 'Sensor' },
  { value: 'ACTUATOR', label: 'Aktor' },
  { value: 'CONTROLLER', label: 'Steuerung' },
  { value: 'NETWORK', label: 'Netzwerk' },
  { value: 'MECHANICAL', label: 'Mechanik' },
  { value: 'ELECTRICAL', label: 'Elektrik' },
  { value: 'OTHER', label: 'Sonstiges' },
]

export function buildTree(components: Component[]): Component[] {
  const map = new Map<string, Component>()
  const roots: Component[] = []

  components.forEach((c) => {
    map.set(c.id, { ...c, children: [] })
  })

  components.forEach((c) => {
    const node = map.get(c.id)!
    if (c.parent_id && map.has(c.parent_id)) {
      map.get(c.parent_id)!.children.push(node)
    } else {
      roots.push(node)
    }
  })

  return roots
}
