import React from 'react';

interface HighlightProps {
  text: string;
  query: string | string[];
}

function normalize(str: string) {
  return str
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLowerCase();
}

const Highlight: React.FC<HighlightProps> = ({ text, query }) => {
  if (!query) return <>{text}</>;

  const queries = (Array.isArray(query) ? query : query.split(/\s+/))
    .filter(Boolean)
    .map(normalize);

  const normalizedText = normalize(text);
  const matches: { start: number; end: number }[] = [];

  queries.forEach((q) => {
    let startIndex = 0;
    while (true) {
      const index = normalizedText.indexOf(q, startIndex);
      if (index === -1) break;
      matches.push({ start: index, end: index + q.length });
      startIndex = index + q.length;
    }
  });

  // Merge overlapping matches
  matches.sort((a, b) => a.start - b.start);
  const merged: { start: number; end: number }[] = [];
  matches.forEach((m) => {
    const last = merged[merged.length - 1];
    if (!last || m.start > last.end) {
      merged.push({ ...m });
    } else {
      last.end = Math.max(last.end, m.end);
    }
  });

  // Build React nodes
  const result: React.ReactNode[] = [];
  let lastIndex = 0;
  merged.forEach((m, i) => {
    if (m.start > lastIndex) {
      result.push(text.slice(lastIndex, m.start));
    }
    result.push(
      <mark key={i} className="bg-mma-yellow">
        {text.slice(m.start, m.end)}
      </mark>
    );
    lastIndex = m.end;
  });
  if (lastIndex < text.length) result.push(text.slice(lastIndex));

  return <>{result}</>;
};

export default Highlight;
