import { Product } from "lib/shopify/types";

/**
 * Color mapping from color names to hex codes
 */
export const colorHexMap: Record<string, string> = {
  'red': '#FF0000',
  'blue': '#0000FF',
  'green': '#00FF00',
  'black': '#000000',
  'white': '#FFFFFF',
  'yellow': '#FFFF00',
  'purple': '#800080',
  'pink': '#FFC0CB',
  'orange': '#FFA500',
  'gray': '#808080',
  'crvena': '#FF0000',
  'plava': '#0000FF',
  'zelena': '#00FF00',
  'crna': '#000000',
  'bijela': '#FFFFFF',
  'žuta': '#FFFF00',
  'ljubičasta': '#800080',
  'roza': '#FFC0CB',
  'narančasta': '#FFA500',
  'siva': '#808080'
};

export type ColorVariant = {
  color: string; // Hex code
  variantId: string;
  price: number;
  colorName: string;
}

/**
 * Extract color options from a product if they exist
 * Returns an array of hex color codes, or undefined if no colors
 */
export function getProductColors(product: Product) {
  // Get colors directly from variants
  const colorVariants = getProductColorVariants(product);
  if (!colorVariants) return undefined;
  
  // Return just the color codes
  return colorVariants.map(variant => variant.color);
}

/**
 * Get detailed color variants including price and variant ID
 * Extracts directly from the variants array
 */
export function getProductColorVariants(product: Product): ColorVariant[] | undefined {
  if (!product?.variants || product.variants.length === 0) return undefined;
  
  const result: ColorVariant[] = [];
  
  // Iterate through all variants looking for color options
  product.variants.forEach(variant => {
    // Find any color option in the selectedOptions
    const colorSelectedOption = variant.selectedOptions?.find(
      option => option.name.toLowerCase() === 'color' || 
               option.name.toLowerCase() === 'colour' || 
               option.name.toLowerCase() === 'boja'
    );
    
    if (colorSelectedOption) {
      const colorName = colorSelectedOption.value;
      const colorHex = colorHexMap[colorName.toLowerCase()] || colorName;
      
      result.push({
        color: colorHex,
        variantId: variant.id,
        price: parseFloat(variant.price.amount),
        colorName: colorName
      });
    }
  });
  
  return result.length > 0 ? result : undefined;
} 