"use client";

import { useTranslations } from "next-intl";

import { COLOR_PALETTES, PALETTE_NAMES } from "@/lib/studio-color-palettes";
import { useStudioStore } from "@/lib/studio-store";
import { cn } from "@/lib/utils";

interface ColorsPalettesTabProps {
  activeColorIndex: number;
  onSelectPalette: (index: number) => void;
}

export function ColorsPalettesTab({
  activeColorIndex,
  onSelectPalette,
}: ColorsPalettesTabProps) {
  const t = useTranslations("auto.componentsStudioSidebarColorsPalettesTab");
  const applyPaletteToAllScenes = useStudioStore(
    (state) => state.applyPaletteToAllScenes
  );

  return (
    <div className="min-h-0 flex-1 overflow-y-auto py-2 [scrollbar-width:thin] [scrollbar-color:theme(colors.gray.300)_transparent]">
      <ul className="space-y-1.5">
        {COLOR_PALETTES.map((palette, index) => {
          const isActive = activeColorIndex === index;
          const name =
            PALETTE_NAMES[index] ?? t("paletteFallback", { number: index + 1 });
          return (
            <li key={index}>
              <button
                type="button"
                title={name}
                aria-label={t("applyPaletteAriaLabel", { name })}
                onClick={() => {
                  onSelectPalette(index);
                  applyPaletteToAllScenes(palette[0] ?? "#ffffff", palette[1] ?? "#94a3b8");
                }}
                className={cn(
                  "group relative flex h-9 w-full cursor-pointer items-stretch overflow-hidden rounded-lg transition-all",
                  "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500",
                  "hover:scale-[1.02] hover:shadow-md",
                  isActive
                    ? "ring-2 ring-blue-500 ring-offset-1 ring-offset-white"
                    : "opacity-90 hover:opacity-100"
                )}
              >
                {/* Active left-edge indicator */}
                {isActive && (
                  <span className="absolute inset-y-0 left-0 z-10 w-1 rounded-l bg-blue-500" />
                )}

                {/* Colour swatches */}
                {palette.map((color, ci) => (
                  <span
                    key={ci}
                    className="h-full flex-1"
                    style={{ backgroundColor: color }}
                    aria-hidden
                  />
                ))}

                {/* Name tooltip on hover */}
                <span className="pointer-events-none absolute inset-x-0 bottom-0 translate-y-full rounded-b-lg bg-gray-800 py-0.5 text-center text-[9px] font-medium text-gray-300 opacity-0 transition-all group-hover:translate-y-0 group-hover:opacity-100">
                  {name}
                </span>
              </button>
            </li>
          );
        })}
      </ul>
    </div>
  );
}
