/**
 * Modelica / Dymola-style component orientation.
 *
 * Handles must NOT be CSS-rotated — React Flow routes edges from Handle
 * `position` (Left/Right/Top/Bottom). We remap logical port sides through
 * rotation + flips so connectors stay on the correct box edge.
 */

export type Side = "left" | "right" | "top" | "bottom";

export type RotationDeg = 0 | 90 | 180 | 270;

export function normaliseRotation(deg: number): RotationDeg {
  const n = ((Math.round(deg / 90) * 90) % 360 + 360) % 360;
  return n as RotationDeg;
}

/** Rotate a side clockwise by 90° × steps. */
export function rotateSide(side: Side, rotation: number): Side {
  const order: Side[] = ["left", "top", "right", "bottom"];
  const steps = ((Math.round(rotation / 90) % 4) + 4) % 4;
  const i = order.indexOf(side);
  return order[(i + steps) % 4];
}

export function flipSideH(side: Side): Side {
  if (side === "left") return "right";
  if (side === "right") return "left";
  return side;
}

export function flipSideV(side: Side): Side {
  if (side === "top") return "bottom";
  if (side === "bottom") return "top";
  return side;
}

/**
 * Effective diagram side for a logical port side after Modelica transform:
 * rotate clockwise, then flip horizontal, then flip vertical.
 */
export function effectiveSide(
  logical: Side,
  rotation: number,
  flipH = false,
  flipV = false,
): Side {
  let s = rotateSide(logical, rotation);
  if (flipH) s = flipSideH(s);
  if (flipV) s = flipSideV(s);
  return s;
}

/**
 * Choose rotation so a 2-port part (inlet=left, outlet=right at 0°)
 * faces along the edge from source → target.
 */
export function orientationAlongEdge(
  sourceCenter: { x: number; y: number },
  targetCenter: { x: number; y: number },
): RotationDeg {
  const dx = targetCenter.x - sourceCenter.x;
  const dy = targetCenter.y - sourceCenter.y;
  if (Math.abs(dx) >= Math.abs(dy)) {
    // Horizontal: 0° = flow left→right, 180° = right→left
    return dx >= 0 ? 0 : 180;
  }
  // Vertical: 90° CW puts inlet on top, outlet on bottom (flow down)
  return dy >= 0 ? 90 : 270;
}

/** Top-left position so the node box is centered on `mid`. */
export function centerNodePosition(
  mid: { x: number; y: number },
  size: { w: number; h: number },
): { x: number; y: number } {
  return { x: mid.x - size.w / 2, y: mid.y - size.h / 2 };
}
