// Marker color logic for the shop-floor map, shared so the PDF export renders
// the exact same colors the map shows on screen. Mirrors the maps defined in
// ShopFloorMap.vue - keep the two in sync if the palette changes.

export const assetTypeColorsMap = {
  equipment: '#F44336',        // Red
  computer: '#2196F3',         // Blue
  printer: '#4CAF50',          // Green
  'network device': '#FF9800', // Orange
  network_device: '#FF9800'    // Orange (alternate key)
}

const DEFAULT_COLOR = '#BDBDBD'

// Canonical form for comparing asset-type strings. The API sends the machine
// type as 'network_device' but subtype keys and labels use 'network device',
// so normalize underscores to spaces before any comparison. Without this,
// network-device subtypes silently fail to match (equipment/computer/printer
// are single words and were unaffected, which is why only network broke).
export function normalizeAssetType(assettype) {
  return (assettype || '').toLowerCase().replace(/_/g, ' ')
}

// Color for an asset by its top-level asset type (used when no type filter is
// active, so every type is distinguished by color).
export function getAssetTypeColor(assettype) {
  if (!assettype) return DEFAULT_COLOR
  return assetTypeColorsMap[assettype.toLowerCase()] || DEFAULT_COLOR
}

// The subtype id for an asset, read from the plugin-specific typedata block.
// Returns null when the asset has no subtype.
export function getSubtypeId(asset) {
  if (!asset || !asset.typedata) return null
  const typeLower = normalizeAssetType(asset.assettype)
  if (typeLower === 'equipment') return asset.typedata.equipmenttypeid
  if (typeLower === 'computer') return asset.typedata.computertypeid
  if (typeLower === 'network device') return asset.typedata.networkdevicetypeid
  if (typeLower === 'printer') return asset.typedata.printertypeid
  return null
}

// Resolve the marker color for an asset the same way ShopFloorMap does: when a
// type is selected, color by subtype (grey fallback); otherwise by asset type.
export function resolveMarkerColor(asset, { selectedType, subtypeColors = {} }) {
  if (selectedType) {
    const id = getSubtypeId(asset)
    return (id != null && subtypeColors[id]) || DEFAULT_COLOR
  }
  return getAssetTypeColor(asset.assettype)
}
