/**
 * Keyword Display Component
 *
 * Displays keywords in a clean, readable format with tags
 */

import React, { useState } from "react";

interface KeywordDisplayProps {
  keywords: string | null | undefined;
  getString: (section: string, key: string, fallback: string) => string;
  maxWidth?: string;
  alwaysShowAll?: boolean;
}

const KeywordDisplay: React.FC<KeywordDisplayProps> = ({
  keywords,
  getString,
  maxWidth = "max-w-md",
  alwaysShowAll = false,
}) => {
  const [showAll, setShowAll] = useState(false);
  if (!keywords) {
    return (
      <span className="text-wp-gray italic text-sm">
        {getString("table_cells", "no_keywords", "No keywords")}
      </span>
    );
  }

  // Split keywords by comma and trim whitespace
  const keywordArray = keywords
    .split(",")
    .map((keyword) => keyword.trim())
    .filter((keyword) => keyword.length > 0);

  if (keywordArray.length === 0) {
    return (
      <span className="text-wp-gray italic text-sm">
        {getString("table_cells", "no_keywords", "No keywords")}
      </span>
    );
  }

  const visibleCount = 5;
  const displayKeywords =
    alwaysShowAll || showAll
      ? keywordArray
      : keywordArray.slice(0, visibleCount);
  const hiddenCount = keywordArray.length - visibleCount;

  return (
    <div className={`flex flex-wrap gap-1 ${maxWidth} w-full`}>
      {displayKeywords.map((keyword, index) => (
        <span
          key={index}
          className="inline-flex items-center px-1.5 sm:px-2 py-0.5 sm:py-1 text-xs font-medium bg-blue-100 text-blue-800 rounded-md break-words"
        >
          {keyword}
        </span>
      ))}
      {!alwaysShowAll && hiddenCount > 0 && !showAll && (
        <button
          onClick={() => setShowAll(true)}
          className="inline-flex items-center px-1.5 sm:px-2 py-0.5 sm:py-1 text-xs font-medium bg-gray-100 text-gray-800 rounded-md hover:bg-gray-200 cursor-pointer transition-colors"
          title={`Click to show ${hiddenCount} more keywords`}
        >
          +{hiddenCount} {getString("table_cells", "more", "more")}
        </button>
      )}
      {!alwaysShowAll && showAll && hiddenCount > 0 && (
        <button
          onClick={() => setShowAll(false)}
          className="inline-flex items-center px-1.5 sm:px-2 py-0.5 sm:py-1 text-xs font-medium bg-gray-100 text-gray-800 rounded-md hover:bg-gray-200 cursor-pointer transition-colors"
        >
          {getString("table_cells", "show_less", "Show less")}
        </button>
      )}
    </div>
  );
};

export default KeywordDisplay;
