export const PT_TO_MM = 0.3527

export const PageSizeUnits = {
  MM: 'mm',
  CM: 'cm',
  PT: 'pt',
  IN: 'in'
}

export const convertToMM = (value, unit) => {
  switch (unit.toLowerCase()) {
    case PageSizeUnits.MM:
      return value
    case PageSizeUnits.CM:
      return value * 10
    case PageSizeUnits.PT:
      return value * PT_TO_MM
    case PageSizeUnits.IN:
      return value * 25.4
    default:
      return value
  }
}

export const detectStandardPaperSizeUnit = (width, height) => {
  const mmSizes = [
    { w: 297, h: 420 },
    { w: 210, h: 297 },
    { w: 148, h: 210 }
  ]
  
  const inSizes = [
    { w: 8.5, h: 11 },
    { w: 8.5, h: 14 },
    { w: 11, h: 17 }
  ]
  
  const checkSize = (size, w, h) => {
    return (Math.abs(size.w - w) < 0.01 && Math.abs(size.h - h) < 0.01) ||
           (Math.abs(size.w - h) < 0.01 && Math.abs(size.h - w) < 0.01)
  }
  
  for (const size of mmSizes) {
    if (checkSize(size, width, height)) {
      return PageSizeUnits.MM
    }
  }
  
  for (const size of inSizes) {
    if (checkSize(size, width, height)) {
      return PageSizeUnits.IN
    }
  }
  
  return null
}

export const parsePageSize = (pageSize, product) => {
  if (!pageSize || pageSize === 'Auto') {
    return { width: null, height: null, unit: PageSizeUnits.PT }
  }
  
  const trimmed = pageSize.trim()
  const unitMatch = trimmed.match(/\s*(mm|cm|pt|in)\s*$/i)
  let unit = null
  
  if (unitMatch) {
    unit = unitMatch[1].toLowerCase()
  } else {
    const sizeString = trimmed
    const [widthStr, heightStr] = sizeString.split(/[xX]/).map(s => s.trim())
    const width = parseFloat(widthStr)
    const height = parseFloat(heightStr)
    
    if (!isNaN(width) && !isNaN(height)) {
      const standardUnit = detectStandardPaperSizeUnit(width, height)
      if (standardUnit) {
        unit = standardUnit
      }
    }
    
    if (!unit) {
      const shortName = product?.Configuration?.Preview?.DimensionsUnit?.ShortName
      if (shortName) {
        const normalizedShortName = shortName.toLowerCase().trim()
        if ([PageSizeUnits.MM, PageSizeUnits.CM, PageSizeUnits.PT, PageSizeUnits.IN].includes(normalizedShortName)) {
          unit = normalizedShortName
        }
      }
    }
    
    if (!unit) {
      unit = PageSizeUnits.PT
    }
  }
  
  const sizeString = unitMatch ? trimmed.slice(0, unitMatch.index).trim() : trimmed
  
  const [widthStr, heightStr] = sizeString.split(/[xX]/).map(s => s.trim())
  const width = parseFloat(widthStr)
  const height = parseFloat(heightStr)
  
  return { width, height, unit }
}

