import { useRef } from "react";
import type { NoteCard } from "../types";

interface Props {
  card: NoteCard;
  onUpdate: (patch: Partial<NoteCard>) => void;
}

export function NoteCardView({ card, onUpdate }: Props) {
  const dragState = useRef<{ startX: number; startY: number; cardX: number; cardY: number } | null>(
    null,
  );

  const onHeaderPointerDown = (e: React.PointerEvent) => {
    if (e.button !== 0) return;
    e.stopPropagation();
    (e.target as Element).setPointerCapture(e.pointerId);
    dragState.current = { startX: e.clientX, startY: e.clientY, cardX: card.x, cardY: card.y };
  };

  const onHeaderPointerMove = (e: React.PointerEvent) => {
    if (!dragState.current) return;
    const worldEl = (e.currentTarget as HTMLElement).closest(".canvas-world") as HTMLElement;
    const scale = worldEl ? parseTransformScale(worldEl.style.transform) : 1;
    const dx = (e.clientX - dragState.current.startX) / scale;
    const dy = (e.clientY - dragState.current.startY) / scale;
    onUpdate({ x: dragState.current.cardX + dx, y: dragState.current.cardY + dy });
  };

  const onHeaderPointerUp = (e: React.PointerEvent) => {
    if (dragState.current) {
      (e.target as Element).releasePointerCapture(e.pointerId);
      dragState.current = null;
    }
  };

  return (
    <div
      className="card note-card"
      style={{ left: card.x, top: card.y, width: card.width, height: card.height, zIndex: card.z }}
    >
      <div
        className="card-header"
        onPointerDown={onHeaderPointerDown}
        onPointerMove={onHeaderPointerMove}
        onPointerUp={onHeaderPointerUp}
        onPointerCancel={onHeaderPointerUp}
      >
        note
      </div>
      <div className="card-body">
        <textarea
          value={card.text}
          onChange={(e) => onUpdate({ text: e.target.value })}
          onPointerDown={(e) => e.stopPropagation()}
        />
      </div>
    </div>
  );
}

function parseTransformScale(transform: string): number {
  const m = transform.match(/scale\(([^)]+)\)/);
  return m ? parseFloat(m[1]) : 1;
}
