import { useEffect, useRef } from "react";

import { P0A_COLOR_CARDS, createColorCardElement, drawColorCard, type ColorCardDefinition } from "./palette-provider.js";

const previewPalette = ["#04D960", "#0ABF58", "#5FD994", "#A0F2C4", "#D5F2E2"] as const;
const previewHalfSize = {
  style_01: { height: 76, width: 26 }, style_02: { height: 77, width: 18 },
  style_08: { height: 10, width: 73 }, style_16: { height: 9, width: 78 },
} as const;

function ColorCardPreview({ definition }: { definition: ColorCardDefinition }) {
  const ref = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    const canvas = ref.current;
    const context = canvas?.getContext("2d");
    if (!canvas || !context) return;
    context.setTransform(1, 0, 0, 1, 0, 0);
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "#30343b";
    context.fillRect(0, 0, canvas.width, canvas.height);
    const half = previewHalfSize[definition.styleId];
    const scale = Math.min(1, 146 / (half.width * 2), 62 / (half.height * 2));
    context.translate(canvas.width / 2, canvas.height / 2);
    context.scale(scale, scale);
    drawColorCard(context, createColorCardElement(definition, previewPalette, {
      createdAt: "2026-08-03T00:00:00.000Z", elementId: "00000000-0000-4000-8000-000000000001",
    }, 0));
  }, [definition]);
  return <canvas aria-hidden="true" className="editor-source-preview-canvas" height={72} ref={ref} width={160} />;
}

export function ColorCardPanel(props: { canAdd: boolean; hasBackground: boolean; onAdd: (definition: ColorCardDefinition) => void }) {
  return <section className="editor-provider-panel">
    <header><h2>色卡</h2><button aria-label="色卡说明" className="editor-info-button" title="色卡基于原始底图，更换底图时更新，不随裁剪、调色和滤镜变化" type="button">i</button></header>
    <p className="editor-provider-note">基于当前原始底图</p>
    <div className="editor-provider-grid">
      {P0A_COLOR_CARDS.map((definition) => <button
        aria-label={`添加色卡 ${definition.cardId} ${definition.displayName}`}
        disabled={!props.canAdd || !props.hasBackground}
        key={definition.cardId}
        onClick={() => props.onAdd(definition)}
        type="button"
      ><ColorCardPreview definition={definition} /><strong>{definition.cardId}</strong><span>{definition.displayName}</span></button>)}
    </div>
    {!props.hasBackground ? <p className="editor-limit" role="status">需要先有原始底图才能提取色卡。</p> : null}
  </section>;
}
