'use client';

import React from 'react';

const WIRE_COLOR_DEFAULT = '#9E9E9E';

// La couleur du fil vient du backend (wire.color). On calcule la luminance pour
// choisir un texte lisible (foncé sur fond clair) et une bordure sur fond très
// clair — sinon un fil blanc (#FFFFFF) afficherait du texte blanc invisible.
function wireBadgeStyle(bg: string): React.CSSProperties {
  const hex = bg.replace('#', '');
  // Supporte le format court (#fff) et long (#ffffff).
  const full = hex.length === 3 ? hex.split('').map((c) => c + c).join('') : hex;
  const r = parseInt(full.slice(0, 2), 16);
  const g = parseInt(full.slice(2, 4), 16);
  const b = parseInt(full.slice(4, 6), 16);
  const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  const isLight = luminance > 0.7;
  return {
    backgroundColor: bg,
    color: isLight ? '#1f2937' : '#fff',
    border: isLight ? '1px solid #d1d5db' : undefined,
  };
}

interface Props {
  label: string;
  color?: string | null;
}

export function WireBadge({ label, color }: Props) {
  return (
    <span className="wire-badge" style={wireBadgeStyle(color || WIRE_COLOR_DEFAULT)}>
      {label}
    </span>
  );
}
