"use client";

import type { NewsroomCategory } from "@/types/newsroom";

interface CategorySliderProps {
  categories: NewsroomCategory[];
  selectedCategory: string; // "" means "All"
  onSelectCategory: (categoryId: string) => void;
  disabled?: boolean;
}

const DEFAULT_TOPICS = [
  "COMPANY NEWS & ANNOUNCEMENTS",
  "MEMBERSHIP & PRIVILEGES",
  "LEADERSHIP & PEOPLE",
  "GLOBAL TRAVEL SECURITY",
  "CLOSE PROTECTION",
];

export function CategorySlider({
  categories,
  selectedCategory,
  onSelectCategory,
  disabled = false,
}: CategorySliderProps) {
  const isAllActive = selectedCategory === "" || selectedCategory === "all";

  // Use backend categories if available, otherwise fallback to the default design topics
  const topicList =
    categories.length > 0
      ? categories.map((cat) => ({
        id: cat._id,
        name: cat.n.toUpperCase(),
      }))
      : DEFAULT_TOPICS.map((topic) => ({
        id: topic,
        name: topic,
      }));

  return (
    <div className="mb-10 w-full">
      {/* Category Chips Container matching design in Image 4 */}
      <div className="flex flex-wrap items-center gap-2.5 sm:gap-3">
        {/* "ALL NEWS" Category Chip */}
        <button
          type="button"
          onClick={() => onSelectCategory("")}
          disabled={disabled}
          className={`cursor-pointer rounded-[4px] px-4 py-2 text-xs font-semibold tracking-wider uppercase transition-all duration-200 select-none sm:px-5 sm:py-2.5 ${isAllActive
            ? "border border-accent bg-accent text-white shadow-sm"
            : "border border-[#7ba4d0] bg-transparent text-[#2e5e99] hover:bg-[#e7f0fa]/60 hover:border-accent"
            }`}
        >
          ALL NEWS
        </button>

        {/* Category Chips */}
        {topicList.map((topic) => {
          const isActive =
            selectedCategory === topic.id ||
            selectedCategory.toLowerCase() === topic.name.toLowerCase();

          return (
            <button
              key={topic.id}
              type="button"
              onClick={() => onSelectCategory(topic.id)}
              disabled={disabled}
              title={topic.name}
              className={`max-w-[600px] cursor-pointer truncate overflow-hidden whitespace-nowrap rounded-[4px] px-4 py-2 text-xs font-semibold tracking-wider uppercase transition-all duration-200 select-none sm:px-5 sm:py-2.5 ${isActive
                ? "border border-accent bg-accent text-white shadow-sm"
                : "border border-[#7ba4d0] bg-transparent text-[#2e5e99] hover:bg-[#e7f0fa]/60 hover:border-accent"
                }`}
            >
              {topic.name}
            </button>
          );
        })}
      </div>

      {/* Horizontal Separator Line */}
      <div className="mt-8 sm:mt-10 w-full border-b border-[#e5e7eb]" />
    </div>
  );
}
