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

const ENTITY_COLORS: Record<string, { bg: string; text: string; label: string }> = {
  // IBAN
  IBAN_CODE:      { bg: "bg-red-100",    text: "text-red-800",    label: "IBAN" },
  IBAN:           { bg: "bg-red-100",    text: "text-red-800",    label: "IBAN" },
  // Credit card
  CREDIT_CARD:    { bg: "bg-red-100",    text: "text-red-800",    label: "CB" },
  // Email
  EMAIL_ADDRESS:  { bg: "bg-orange-100", text: "text-orange-800", label: "Email" },
  EMAIL:          { bg: "bg-orange-100", text: "text-orange-800", label: "Email" },
  // Phone
  PHONE_NUMBER:   { bg: "bg-purple-100", text: "text-purple-800", label: "Tél." },
  PHONE_FR:       { bg: "bg-purple-100", text: "text-purple-800", label: "Tél." },
  PHONE_INTL:     { bg: "bg-purple-100", text: "text-purple-800", label: "Tél. Intl." },
  // Person
  PERSON:         { bg: "bg-blue-100",   text: "text-blue-800",   label: "Personne" },
  PER:            { bg: "bg-blue-100",   text: "text-blue-800",   label: "Personne" },
  // SSN
  FR_SSN:         { bg: "bg-rose-100",   text: "text-rose-800",   label: "INSEE" },
  FR_NIF:         { bg: "bg-rose-100",   text: "text-rose-800",   label: "INSEE" },
  // Location
  LOCATION:       { bg: "bg-green-100",  text: "text-green-800",  label: "Lieu" },
  LOC:            { bg: "bg-green-100",  text: "text-green-800",  label: "Lieu" },
  GPE:            { bg: "bg-green-100",  text: "text-green-800",  label: "Lieu" },
  // Organisation
  ORGANIZATION:   { bg: "bg-teal-100",   text: "text-teal-800",   label: "Org." },
  ORG:            { 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 and remove overlapping spans.
  const sorted = [...entities]
    .sort((a, b) => a.start - b.start)
    .reduce<PiiEntity[]>((acc, e) => {
      if (acc.length === 0 || e.start >= acc[acc.length - 1].end) {
        acc.push(e);
      }
      return acc;
    }, []);

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

  for (const entity of sorted) {
    // Guard against out-of-bounds offsets from the API.
    const start = Math.max(0, Math.min(entity.start, text.length));
    const end   = Math.max(start, Math.min(entity.end, text.length));

    if (start > cursor) {
      parts.push(<span key={`t-${cursor}`}>{text.slice(cursor, start)}</span>);
    }
    if (start < end) {
      const color = ENTITY_COLORS[entity.type] ?? DEFAULT_COLOR;
      const layerNote = entity.layer === "regex" ? " (détection locale)" : "";
      parts.push(
        <mark
          key={`e-${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)}%${layerNote}`}
        >
          {text.slice(start, end)}
          <sup className="ml-0.5 text-[9px] opacity-70">{color.label}</sup>
        </mark>
      );
    }
    cursor = end;
  }

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

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