/**
 * PiP Utility Functions
 * Pure functions for Picture-in-Picture window management
 */

// PiP size constants
export const PIP_MIN_W = 500;
export const PIP_MIN_H = 300;
export const PIP_MAX_W = 1200;
export const PIP_MAX_H = 800;
export const PIP_DEFAULT_W = 700;
export const PIP_DEFAULT_H = 400;

/**
 * Compute letterbox rect for an image within a container
 * Maintains aspect ratio and centers the image
 * 
 * @param {number} containerW - Container width
 * @param {number} containerH - Container height
 * @param {number} imageNaturalW - Image natural width
 * @param {number} imageNaturalH - Image natural height
 * @returns {{w: number, h: number, ml: number, mt: number}} Letterbox dimensions and margins
 */
export function computeLetterboxRect(containerW, containerH, imageNaturalW, imageNaturalH) {
  const ratio = imageNaturalW / imageNaturalH;
  
  let w, h;
  if (containerW / containerH > ratio) {
    // Container is wider than image aspect ratio - letterbox on sides
    w = containerH * ratio;
    h = containerH;
  } else {
    // Container is taller than image aspect ratio - letterbox on top/bottom
    w = containerW;
    h = containerW / ratio;
  }
  
  const ml = (containerW - w) / 2;
  const mt = (containerH - h) / 2;
  
  return { w, h, ml, mt };
}

/**
 * Clamp a value between min and max
 * 
 * @param {number} value - Value to clamp
 * @param {number} min - Minimum value
 * @param {number} max - Maximum value
 * @returns {number} Clamped value
 */
export function clampSize(value, min, max) {
  return Math.max(min, Math.min(max, value));
}

/**
 * Load PiP size from localStorage
 * 
 * @returns {{w: number, h: number}} PiP size or default if not found
 */
export function loadPipSize() {
  try {
    const stored = localStorage.getItem('pipSize');
    if (stored) {
      const parsed = JSON.parse(stored);
      if (parsed && typeof parsed.w === 'number' && typeof parsed.h === 'number') {
        return {
          w: clampSize(parsed.w, PIP_MIN_W, PIP_MAX_W),
          h: clampSize(parsed.h, PIP_MIN_H, PIP_MAX_H)
        };
      }
    }
  } catch (e) {
    // Failed to load PiP size from localStorage
  }
  
  return { w: PIP_DEFAULT_W, h: PIP_DEFAULT_H };
}

/**
 * Save PiP size to localStorage
 * 
 * @param {{w: number, h: number}} size - PiP size to save
 */
export function savePipSize(size) {
  try {
    localStorage.setItem('pipSize', JSON.stringify(size));
  } catch (e) {
    // Failed to save PiP size to localStorage
  }
}
