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

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

const BODY_FONT_BASE = 13;

export function NoteCardView({ card, onUpdate }: Props) {
  const vp = useViewport();
  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) => {
    const ds = dragState.current;
    if (!ds) return;
    const dx = (e.clientX - ds.startX) / vp.scale;
    const dy = (e.clientY - ds.startY) / vp.scale;
    onUpdate({ x: ds.cardX + dx, y: ds.cardY + dy });
  };

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

  const screenLeft = vp.x + card.x * vp.scale;
  const screenTop = vp.y + card.y * vp.scale;
  const screenW = card.width * vp.scale;
  const screenH = card.height * vp.scale;

  return (
    <div
      className="card note-card"
      style={
        {
          left: screenLeft,
          top: screenTop,
          width: screenW,
          height: screenH,
          zIndex: card.z,
          fontSize: BODY_FONT_BASE * vp.scale,
          "--scale": vp.scale,
        } as React.CSSProperties
      }
    >
      <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>
  );
}
