export default function Highlight({
  className,
  value,
  query,
}: {
  className?: string;
  value: string;
  query: string;
}) {
  const content = <HighlightContent value={value} query={query} />;
  return className ? <span className={className}>{content}</span> : content;
}

function HighlightContent({ value, query }: { value: string; query: string }) {
  if (value && query) {
    const highlightStart = value.toUpperCase().indexOf(query.trim().toUpperCase());
    const highlightEnd = highlightStart + query.trim().length;
    if (highlightStart !== -1) {
      return (
        <>
          {value.slice(0, Math.max(0, highlightStart))}
          <strong>{value.slice(highlightStart, highlightEnd)}</strong>
          {value.slice(Math.max(0, highlightEnd))}
        </>
      );
    }
  }
  return value;
}
