"use client";

import React from "react";

interface KeywordHighlighterProps {
  text: string;
  keyword: string | null | undefined;
}

export function KeywordHighlighter({ text, keyword }: KeywordHighlighterProps) {
  if (!keyword || !text || keyword.trim() === "") {
    return <>{text}</>;
  }

  const escapedKeyword = keyword.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
  const regex = new RegExp(`(${escapedKeyword})`, "gi");
  const parts = text.split(regex);

  return (
    <>
      {parts.map((part, i) =>
        regex.test(part) ? (
          <mark
            key={i}
            className="bg-yellow-200 text-yellow-900 dark:bg-yellow-700 dark:text-yellow-50 rounded px-1 mx-px font-semibold"
          >
            {part}
          </mark>
        ) : (
          part
        )
      )}
    </>
  );
}