import { useEffect, useRef } from "react";
import "./ColorPanel.css";

interface Props {
  colors: string[];
  activeColor: string;
  onColorChange: (c: string) => void;
  onColorsChange: (colors: string[]) => void;
}

export default function ColorPanel({
  colors,
  activeColor,
  onColorChange,
  onColorsChange,
}: Props) {
  // One hidden color input ref per slot
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

  // Keys 1–9 select the corresponding color slot (plain, no shift)
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) return;
      if (
        e.target instanceof HTMLInputElement ||
        e.target instanceof HTMLTextAreaElement
      )
        return;
      const num = parseInt(e.key, 10);
      if (num >= 1 && num <= colors.length) {
        onColorChange(colors[num - 1]);
      }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [colors, onColorChange]);

  function handleDoubleClick(index: number) {
    // Select the color first, then open the picker
    onColorChange(colors[index]);
    inputRefs.current[index]?.click();
  }

  function handleColorEdit(index: number, newColor: string) {
    const updated = colors.map((c, i) => (i === index ? newColor : c));
    onColorsChange(updated);
    onColorChange(newColor);
  }

  return (
    <div className="color-panel">
      <div className="cp-swatches">
        {colors.map((c, i) => (
          <div key={i} className="cp-swatch-wrapper">
            <button
              className={`cp-swatch ${activeColor === c ? "selected" : ""}`}
              style={{ background: c }}
              onClick={() => onColorChange(c)}
              onDoubleClick={() => handleDoubleClick(i)}
              title={`${c} (${i + 1}) — double-click to edit`}
            >
              <span className="cp-key-hint">{i + 1}</span>
            </button>
            {/* Hidden color picker for this slot */}
            <input
              ref={(el) => {
                inputRefs.current[i] = el;
              }}
              type="color"
              value={c}
              onChange={(e) => handleColorEdit(i, e.target.value)}
              className="cp-color-input"
              tabIndex={-1}
            />
          </div>
        ))}
      </div>
    </div>
  );
}
