"use client";

import { useEffect, useRef } from "react";
import { FlipHorizontal2, FlipVertical2, RotateCcw, RotateCw, Trash2 } from "lucide-react";

export interface NodeContextMenuState {
  x: number;
  y: number;
  nodeId: string;
  nodeName: string;
}

interface Props {
  menu: NodeContextMenuState | null;
  onClose: () => void;
  onRotate: (dir: 1 | -1) => void;
  onFlipH: () => void;
  onFlipV: () => void;
  onDelete: () => void;
}

/** Right-click menu — Modelica-style orientation + delete. */
export default function NodeContextMenu({
  menu,
  onClose,
  onRotate,
  onFlipH,
  onFlipV,
  onDelete,
}: Props) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!menu) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    const onDown = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as HTMLElement)) onClose();
    };
    window.addEventListener("keydown", onKey);
    window.addEventListener("mousedown", onDown);
    return () => {
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("mousedown", onDown);
    };
  }, [menu, onClose]);

  if (!menu) return null;

  const item = (
    label: string,
    shortcut: string,
    icon: React.ReactNode,
    action: () => void,
  ) => (
    <button
      type="button"
      className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-[12px] text-[var(--ink)] hover:bg-[var(--chrome-2)]"
      onClick={() => {
        action();
        onClose();
      }}
    >
      <span className="text-[var(--ink-faint)]">{icon}</span>
      <span className="flex-1">{label}</span>
      <span className="mono text-[10px] text-[var(--ink-faint)]">{shortcut}</span>
    </button>
  );

  return (
    <div
      ref={ref}
      className="fixed z-50 min-w-[200px] overflow-hidden rounded-md border border-[var(--line)] bg-white py-1 shadow-lg"
      style={{ left: menu.x, top: menu.y }}
      role="menu"
    >
      <div className="border-b border-[var(--line)] px-3 py-1.5">
        <div className="mono truncate text-[11px] font-semibold text-[var(--ink)]">{menu.nodeName}</div>
        <div className="text-[10px] text-[var(--ink-faint)]">Orientation (Modelica)</div>
      </div>
      {item("Rotate 90° CW", "R", <RotateCw size={14} />, () => onRotate(1))}
      {item("Rotate 90° CCW", "Shift+R", <RotateCcw size={14} />, () => onRotate(-1))}
      {item("Flip horizontal", "H", <FlipHorizontal2 size={14} />, onFlipH)}
      {item("Flip vertical", "V", <FlipVertical2 size={14} />, onFlipV)}
      <div className="my-1 h-px bg-[var(--line)]" />
      {item("Delete", "Del", <Trash2 size={14} />, onDelete)}
    </div>
  );
}
