import { useMemo } from 'react';
import type { BoothDto } from '../../api/types';
import './canvas.css';

/*
 * 플로어플랜 SVG 캔버스 (SCR-03 히어로).
 * - 다크 서피스(#1C2536) 위 부스 폴리곤 + 트렌치 그리드 + 위반 오버레이.
 * - 좌표계: 홀 로컬 미터 → SVG 유저 유닛(1m = 1unit), viewBox로 스케일.
 * - 대규모(수백 부스)는 후속 WebGL/Canvas 검토. 지금은 SVG 우선.
 */

export interface CanvasLayer {
  trench: boolean;
  structure: boolean;
  violations: boolean;
}

interface FloorplanCanvasProps {
  hallDims: [number, number]; // [width_m, height_m]
  booths: BoothDto[];
  layers: CanvasLayer;
  selectedBoothId: string | null;
  onSelectBooth: (boothId: string | null) => void;
  zoom: number;
}

const TRENCH_SPACING_M = 9; // 가정 트렌치 그리드 간격(실측 대체 — R4)
const PAD = 6; // viewBox 여백(m)

function centroid(poly: number[][]): [number, number] {
  const n = poly.length;
  let x = 0;
  let y = 0;
  for (const [px, py] of poly) {
    x += px;
    y += py;
  }
  return [x / n, y / n];
}

export function FloorplanCanvas({
  hallDims,
  booths,
  layers,
  selectedBoothId,
  onSelectBooth,
  zoom,
}: FloorplanCanvasProps) {
  const [hw, hh] = hallDims;

  const trenchLines = useMemo(() => {
    const lines: { x1: number; y1: number; x2: number; y2: number }[] = [];
    for (let x = TRENCH_SPACING_M; x < hw; x += TRENCH_SPACING_M) {
      lines.push({ x1: x, y1: 0, x2: x, y2: hh });
    }
    for (let y = TRENCH_SPACING_M; y < hh; y += TRENCH_SPACING_M) {
      lines.push({ x1: 0, y1: y, x2: hw, y2: y });
    }
    return lines;
  }, [hw, hh]);

  return (
    <div className="kx-canvas" style={{ transform: `scale(${zoom})` }}>
      <svg
        className="kx-canvas__svg"
        viewBox={`${-PAD} ${-PAD} ${hw + PAD * 2} ${hh + PAD * 2}`}
        role="img"
        aria-label={`홀 도면 ${hw}×${hh}m, 부스 ${booths.length}개`}
        onClick={() => onSelectBooth(null)}
      >
        {/* 홀 외곽 */}
        <rect
          x={0}
          y={0}
          width={hw}
          height={hh}
          className="kx-canvas__hall"
          rx={0.5}
        />

        {/* 트렌치 그리드 */}
        {layers.trench && (
          <g className="kx-canvas__trench">
            {trenchLines.map((l, i) => (
              <line key={i} x1={l.x1} y1={l.y1} x2={l.x2} y2={l.y2} />
            ))}
          </g>
        )}

        {/* 부스 폴리곤 */}
        <g className="kx-canvas__booths">
          {booths.map((b) => {
            const pts = b.polygon.map(([x, y]) => `${x},${y}`).join(' ');
            const [cx, cy] = centroid(b.polygon);
            const selected = b.boothId === selectedBoothId;
            return (
              <g
                key={b.boothId}
                className={`kx-canvas__booth ${b.premium ? 'is-premium' : ''} ${
                  selected ? 'is-selected' : ''
                }`}
                onClick={(e) => {
                  e.stopPropagation();
                  onSelectBooth(b.boothId);
                }}
                tabIndex={0}
                role="button"
                aria-label={`부스 ${b.boothNo}${b.assignedCompanyName ? `, ${b.assignedCompanyName}` : ''}`}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    onSelectBooth(b.boothId);
                  }
                }}
              >
                <polygon points={pts} />
                <text x={cx} y={cy} className="kx-canvas__booth-label">
                  {b.boothNo}
                </text>
              </g>
            );
          })}
        </g>

        {/* 축척 눈금 (상단) */}
        <g className="kx-canvas__ruler" aria-hidden="true">
          <line x1={0} y1={-2} x2={hw} y2={-2} />
          <text x={0} y={-3}>0m</text>
          <text x={hw / 2} y={-3} textAnchor="middle">{Math.round(hw / 2)}m</text>
          <text x={hw} y={-3} textAnchor="end">{hw}m</text>
        </g>
      </svg>
    </div>
  );
}
