/**
 * MK2 Rect Clamp Helper
 * Ensures rects fit within safe bounds, accounting for borders
 * FIXED: Never sets w=0 h=0, always enforces minimums
 */
import { MIN_PANEL_W, MIN_PANEL_H } from './computeLayout.js';
import { CMD_MIN_W, CMD_MIN_H } from '../safeViewport.js';
/**
 * Clamp a rect to fit within safe bounds
 * Enforces: x >= 0, y >= 0, rightEdge <= maxX, bottomEdge <= maxY
 * FIXED: Never sets w=0 h=0 - always enforces minimums
 */
export function clampRect(rect, safeW, safeH, topGuard = 0, maxX, // Optional: maximum allowed X position (from geometry)
maxY, // Optional: maximum allowed Y position (from geometry)
isCommand = false // If true, use CMD_MIN_W/CMD_MIN_H instead of MIN_PANEL_W/MIN_PANEL_H
) {
    let { x, y, w, h } = rect;
    // Clamp position
    x = Math.max(0, x);
    y = Math.max(topGuard, y);
    // Use maxX/maxY if provided (from geometry), otherwise calculate from safeW/safeH
    const effectiveMaxX = maxX !== undefined ? maxX : safeW - 1;
    const effectiveMaxY = maxY !== undefined ? maxY : safeH - 1;
    const effectiveMaxYWithGuard = topGuard + effectiveMaxY;
    // CRITICAL: Use different minimums for command box vs regular panels
    const minW = isCommand ? CMD_MIN_W : MIN_PANEL_W;
    const minH = isCommand ? CMD_MIN_H : MIN_PANEL_H;
    // Clamp width: HARD RULE - x + w <= safeW - 1 (leave 1 cell buffer)
    // Blessed box with border: right edge = x + w + 1 (zero-indexed)
    // Must enforce: x + w <= safeW - 1
    const maxW = effectiveMaxX - x; // No +1, we want x + w <= maxX
    w = Math.min(w, maxW);
    w = Math.max(w, minW); // Always enforce minimum
    // Clamp height: HARD RULE - y + h <= safeH - 1 (leave 1 cell buffer)
    // Blessed box with border: bottom edge = y + h + 1 (zero-indexed)
    // Must enforce: y + h <= safeH - 1
    const maxH = effectiveMaxYWithGuard - y; // No +1, we want y + h <= maxY
    h = Math.min(h, maxH);
    h = Math.max(h, minH); // Always enforce minimum
    // Final verification: ensure right and bottom edges are within bounds
    const rightEdge = x + w;
    const bottomEdge = y + h;
    if (rightEdge > effectiveMaxX) {
        w = Math.max(minW, effectiveMaxX - x);
    }
    if (bottomEdge > effectiveMaxYWithGuard) {
        h = Math.max(minH, effectiveMaxYWithGuard - y);
    }
    // CRITICAL: Never return w=0 or h=0 - always enforce minimums
    // If box truly can't fit, it will be small but visible (better than "invalid rect" error)
    w = Math.max(minW, w);
    h = Math.max(minH, h);
    return { x, y, w, h };
}
//# sourceMappingURL=clampRect.js.map