import type { PiiEntity } from "@/types/api";

const ENTITY_COLORS: Record<string, { bg: string; text: string; label: string }> = {
  IBAN_CODE:      { bg: "bg-red-100",    text: "text-red-800",    label: "IBAN" },
  CREDIT_CARD:    { bg: "bg-red-100",    text: "text-red-800",    label: "CB" },
  EMAIL:          { bg: "bg-orange-100", text: "text-orange-800", label: "Email" },
  PHONE_NUMBER:   { bg: "bg-purple-100", text: "text-purple-800", label: "Tél." },
  PERSON:         { bg: "bg-blue-100",   text: "text-blue-800",   label: "Personne" },
  FR_SSN:         { bg: "bg-rose-100",   text: "text-rose-800",   label: "INSEE" },
  LOCATION:       { bg: "bg-green-100",  text: "text-green-800",  label: "Lieu" },
  ORGANIZATION:   { bg: "bg-teal-100",   text: "text-teal-800",   label: "Org." },
};

const DEFAULT_COLOR = { bg: "bg-yellow-100", text: "text-yellow-800", label: "PII" };

interface Props {
  text: string;
  entities: PiiEntity[];
  className?: string;
}

export function PiiHighlight({ text, entities, className }: Props) {
  if (entities.length === 0) {
    return <span className={className}>{text}</span>;
  }

  // Sort by start position
  const sorted = [...entities].sort((a, b) => a.start - b.start);

  const parts: React.ReactNode[] = [];
  let cursor = 0;

  for (const entity of sorted) {
    if (entity.start > cursor) {
      parts.push(
        <span key={`text-${cursor}`}>{text.slice(cursor, entity.start)}</span>
      );
    }
    const color = ENTITY_COLORS[entity.type] ?? DEFAULT_COLOR;
    parts.push(
      <mark
        key={`entity-${entity.start}`}
        className={`${color.bg} ${color.text} rounded px-0.5 py-px text-xs font-medium cursor-help`}
        title={`${entity.type} — confiance: ${Math.round(entity.confidence * 100)}%`}
      >
        {text.slice(entity.start, entity.end)}
        <sup className="ml-0.5 text-[9px] opacity-70">{color.label}</sup>
      </mark>
    );
    cursor = entity.end;
  }

  if (cursor < text.length) {
    parts.push(<span key={`text-end`}>{text.slice(cursor)}</span>);
  }

  return <span className={className}>{parts}</span>;
}
