// ============================================
// VOICE COLOR GRADING PRESETS
// ============================================

class VoiceColorPresets {
  constructor() {
    this.presets = this.initializePresets();
    this.geminiGenerator = typeof GeminiColorGenerator !== 'undefined' ? new GeminiColorGenerator() : null;
  }

  initializePresets() {
    return {
      // Cinematic Looks
      cinematic: {
        name: 'Cinematic',
        description: 'Phong cách điện ảnh Hollywood',
        adjustments: {
          brightness: -5,
          contrast: 15,
          saturation: -10,
          temperature: 5,
          tint: -3,
          highlights: -10,
          shadows: 10,
          vibrance: 5,
          clarity: 10
        }
      },

      'cinematic teal orange': {
        name: 'Cinematic Teal & Orange',
        description: 'Phong cách điện ảnh với tông màu xanh lam và cam',
        adjustments: {
          brightness: -3,
          contrast: 20,
          saturation: 15,
          temperature: 10,
          tint: -5,
          highlights: -15,
          shadows: 15,
          vibrance: 20,
          clarity: 15
        }
      },

      // Vintage Looks
      vintage: {
        name: 'Vintage',
        description: 'Phong cách cổ điển, hoài niệm',
        adjustments: {
          brightness: 5,
          contrast: -10,
          saturation: -20,
          temperature: 15,
          tint: 5,
          highlights: 10,
          shadows: -5,
          vibrance: -15,
          clarity: -5
        }
      },

      retro: {
        name: 'Retro',
        description: 'Phong cách retro những năm 70-80',
        adjustments: {
          brightness: 10,
          contrast: 10,
          saturation: 25,
          temperature: 10,
          tint: 8,
          highlights: 5,
          shadows: 0,
          vibrance: 20,
          clarity: 5
        }
      },

      // Warm & Cool
      warm: {
        name: 'Warm',
        description: 'Tông màu ấm áp, dễ chịu',
        adjustments: {
          brightness: 5,
          contrast: 5,
          saturation: 10,
          temperature: 25,
          tint: 5,
          highlights: 0,
          shadows: 5,
          vibrance: 15,
          clarity: 0
        }
      },

      cool: {
        name: 'Cool',
        description: 'Tông màu lạnh, hiện đại',
        adjustments: {
          brightness: 0,
          contrast: 10,
          saturation: 5,
          temperature: -25,
          tint: -5,
          highlights: 5,
          shadows: 0,
          vibrance: 10,
          clarity: 5
        }
      },

      // Dramatic Looks
      dramatic: {
        name: 'Dramatic',
        description: 'Phong cách kịch tính, tương phản cao',
        adjustments: {
          brightness: -10,
          contrast: 30,
          saturation: 15,
          temperature: 0,
          tint: 0,
          highlights: -20,
          shadows: 20,
          vibrance: 20,
          clarity: 20
        }
      },

      moody: {
        name: 'Moody',
        description: 'Phong cách u ám, tâm trạng',
        adjustments: {
          brightness: -15,
          contrast: 20,
          saturation: -5,
          temperature: -10,
          tint: -5,
          highlights: -15,
          shadows: 15,
          vibrance: 0,
          clarity: 10
        }
      },

      // Bright & Airy
      bright: {
        name: 'Bright & Airy',
        description: 'Sáng sủa, thoáng đãng',
        adjustments: {
          brightness: 20,
          contrast: -5,
          saturation: -5,
          temperature: 10,
          tint: 0,
          highlights: 15,
          shadows: -10,
          vibrance: 5,
          clarity: -5
        }
      },

      // Natural Looks
      natural: {
        name: 'Natural',
        description: 'Tự nhiên, chân thực',
        adjustments: {
          brightness: 0,
          contrast: 5,
          saturation: 0,
          temperature: 5,
          tint: 0,
          highlights: 0,
          shadows: 0,
          vibrance: 5,
          clarity: 5
        }
      },

      // Instagram Inspired
      instagram: {
        name: 'Instagram',
        description: 'Phong cách Instagram phổ biến',
        adjustments: {
          brightness: 10,
          contrast: 15,
          saturation: 20,
          temperature: 5,
          tint: 0,
          highlights: -5,
          shadows: 5,
          vibrance: 25,
          clarity: 10
        }
      },

      vsco: {
        name: 'VSCO',
        description: 'Phong cách VSCO film',
        adjustments: {
          brightness: 5,
          contrast: -5,
          saturation: -10,
          temperature: 10,
          tint: 3,
          highlights: 10,
          shadows: -5,
          vibrance: 0,
          clarity: 0
        }
      },

      // Black & White Variations
      'black and white': {
        name: 'Black & White',
        description: 'Đen trắng cổ điển',
        adjustments: {
          brightness: 0,
          contrast: 15,
          saturation: -100, // Full desaturation
          temperature: 0,
          tint: 0,
          highlights: 0,
          shadows: 0,
          vibrance: 0,
          clarity: 10
        }
      },

      'high contrast bw': {
        name: 'High Contrast B&W',
        description: 'Đen trắng tương phản cao',
        adjustments: {
          brightness: 0,
          contrast: 40,
          saturation: -100,
          temperature: 0,
          tint: 0,
          highlights: -10,
          shadows: 10,
          vibrance: 0,
          clarity: 20
        }
      },

      // Seasonal Looks
      summer: {
        name: 'Summer',
        description: 'Phong cách mùa hè rực rỡ',
        adjustments: {
          brightness: 15,
          contrast: 10,
          saturation: 25,
          temperature: 15,
          tint: 0,
          highlights: 5,
          shadows: 0,
          vibrance: 30,
          clarity: 5
        }
      },

      autumn: {
        name: 'Autumn',
        description: 'Phong cách mùa thu ấm áp',
        adjustments: {
          brightness: 5,
          contrast: 10,
          saturation: 15,
          temperature: 20,
          tint: 10,
          highlights: 0,
          shadows: 5,
          vibrance: 20,
          clarity: 5
        }
      },

      winter: {
        name: 'Winter',
        description: 'Phong cách mùa đông lạnh lẽo',
        adjustments: {
          brightness: 10,
          contrast: 15,
          saturation: -10,
          temperature: -20,
          tint: -5,
          highlights: 10,
          shadows: 0,
          vibrance: 0,
          clarity: 10
        }
      },

      // Film Looks
      'film noir': {
        name: 'Film Noir',
        description: 'Phong cách phim đen tối cổ điển',
        adjustments: {
          brightness: -20,
          contrast: 35,
          saturation: -100,
          temperature: 0,
          tint: 0,
          highlights: -25,
          shadows: 25,
          vibrance: 0,
          clarity: 15
        }
      },

      'kodak portra': {
        name: 'Kodak Portra',
        description: 'Phong cách film Kodak Portra',
        adjustments: {
          brightness: 5,
          contrast: 5,
          saturation: 10,
          temperature: 10,
          tint: 5,
          highlights: 5,
          shadows: 0,
          vibrance: 15,
          clarity: 0
        }
      },

      'fuji velvia': {
        name: 'Fuji Velvia',
        description: 'Phong cách film Fuji Velvia - màu sắc rực rỡ',
        adjustments: {
          brightness: 0,
          contrast: 15,
          saturation: 35,
          temperature: 5,
          tint: 0,
          highlights: -5,
          shadows: 5,
          vibrance: 40,
          clarity: 10
        }
      },

      // Modern Looks
      'matte finish': {
        name: 'Matte Finish',
        description: 'Phong cách matte hiện đại',
        adjustments: {
          brightness: 5,
          contrast: -10,
          saturation: -5,
          temperature: 5,
          tint: 0,
          highlights: 15,
          shadows: -15,
          vibrance: 10,
          clarity: 0
        }
      },

      'faded film': {
        name: 'Faded Film',
        description: 'Phong cách film phai màu',
        adjustments: {
          brightness: 10,
          contrast: -15,
          saturation: -15,
          temperature: 10,
          tint: 5,
          highlights: 20,
          shadows: -20,
          vibrance: -10,
          clarity: -5
        }
      },

      // Portrait Looks
      'portrait soft': {
        name: 'Portrait Soft',
        description: 'Chân dung mềm mại',
        adjustments: {
          brightness: 10,
          contrast: -5,
          saturation: 5,
          temperature: 10,
          tint: 3,
          highlights: 5,
          shadows: -5,
          vibrance: 10,
          clarity: -10
        }
      },

      'portrait dramatic': {
        name: 'Portrait Dramatic',
        description: 'Chân dung kịch tính',
        adjustments: {
          brightness: -5,
          contrast: 25,
          saturation: 10,
          temperature: 0,
          tint: 0,
          highlights: -15,
          shadows: 15,
          vibrance: 15,
          clarity: 20
        }
      },

      // Landscape Looks
      'landscape vivid': {
        name: 'Landscape Vivid',
        description: 'Phong cảnh rực rỡ',
        adjustments: {
          brightness: 5,
          contrast: 20,
          saturation: 30,
          temperature: 5,
          tint: 0,
          highlights: -5,
          shadows: 10,
          vibrance: 35,
          clarity: 20
        }
      },

      'landscape soft': {
        name: 'Landscape Soft',
        description: 'Phong cảnh mềm mại',
        adjustments: {
          brightness: 10,
          contrast: 5,
          saturation: 10,
          temperature: 10,
          tint: 0,
          highlights: 5,
          shadows: 0,
          vibrance: 15,
          clarity: 5
        }
      }
    };
  }

  // Detect preset from voice command
  detectPreset(transcript) {
    const normalized = transcript.toLowerCase().trim();
    
    // Direct match
    if (this.presets[normalized]) {
      return this.presets[normalized];
    }
    
    // Fuzzy match with keywords
    for (const [key, preset] of Object.entries(this.presets)) {
      // Check if transcript contains the preset name
      if (normalized.includes(key)) {
        return preset;
      }
      
      // Check for variations
      const variations = this.getPresetVariations(key);
      for (const variation of variations) {
        if (normalized.includes(variation)) {
          return preset;
        }
      }
    }
    
    return null;
  }

  getPresetVariations(presetKey) {
    const variations = {
      'cinematic': ['điện ảnh', 'phim', 'cinema', 'movie', 'xi nê'],
      'cinematic teal orange': ['teal orange', 'xanh cam', 'teal và orange'],
      'vintage': ['cổ điển', 'hoài niệm', 'xưa', 'retro', 'cổ'],
      'retro': ['retro', 'cổ điển', 'xưa'],
      'warm': ['ấm', 'ấm áp', 'nóng', 'ấm hơn'],
      'cool': ['lạnh', 'mát', 'xanh lạnh', 'lạnh hơn'],
      'dramatic': ['kịch tính', 'mạnh mẽ', 'drama', 'kịch', 'mạnh'],
      'moody': ['u ám', 'tâm trạng', 'buồn', 'u'],
      'bright': ['sáng', 'tươi sáng', 'sáng sủa', 'tươi'],
      'natural': ['tự nhiên', 'chân thực', 'tự nhiên nhất'],
      'instagram': ['insta', 'ig', 'instagram'],
      'vsco': ['vsco', 'film'],
      'black and white': ['đen trắng', 'bw', 'grayscale', 'xám', 'đen và trắng'],
      'high contrast bw': ['đen trắng tương phản', 'bw tương phản', 'high contrast'],
      'summer': ['mùa hè', 'hè', 'summer'],
      'autumn': ['mùa thu', 'thu', 'autumn', 'fall'],
      'winter': ['mùa đông', 'đông', 'winter'],
      'film noir': ['noir', 'phim đen', 'film noir'],
      'kodak portra': ['kodak', 'portra', 'kodak portra'],
      'fuji velvia': ['fuji', 'velvia', 'fuji velvia'],
      'matte finish': ['matte', 'mờ', 'matte finish'],
      'faded film': ['faded', 'phai', 'faded film'],
      'portrait': ['chân dung', 'người', 'portrait'],
      'portrait soft': ['chân dung mềm', 'portrait mềm', 'soft portrait'],
      'portrait dramatic': ['chân dung kịch tính', 'portrait kịch tính', 'dramatic portrait'],
      'landscape': ['phong cảnh', 'cảnh quan', 'landscape'],
      'landscape vivid': ['phong cảnh rực rỡ', 'landscape rực rỡ', 'vivid landscape'],
      'landscape soft': ['phong cảnh mềm', 'landscape mềm', 'soft landscape']
    };
    
    return variations[presetKey] || [];
  }

  // Apply preset to adjustments
  async applyPreset(presetName) {
    let preset = this.detectPreset(presetName);
    
    // If preset not found, try to generate with Gemini AI
    if (!preset && this.geminiGenerator) {
      console.log('🤖 Preset not found, asking Gemini AI...');
      
      // Show loading feedback
      if (typeof voiceControl !== 'undefined') {
        voiceControl.showFeedback('🤖 Đang tạo preset bằng AI...', 'info');
      }
      
      try {
        const result = await this.geminiGenerator.generateColorPreset(presetName);
        
        if (result.success) {
          preset = result.preset;
          console.log('✓ Gemini generated preset:', preset.name);
          
          // Add to presets for future use
          const key = presetName.toLowerCase().trim();
          this.presets[key] = preset;
        } else {
          return {
            success: false,
            message: `❌ Không thể tạo preset: ${result.error}`
          };
        }
      } catch (error) {
        console.error('❌ Gemini error:', error);
        return {
          success: false,
          message: `❌ Lỗi AI: ${error.message}`
        };
      }
    }
    
    if (!preset) {
      return {
        success: false,
        message: `❌ Không tìm thấy preset "${presetName}"`
      };
    }
    
    console.log(`🎨 Applying color preset: ${preset.name}`);
    
    // Apply all adjustments
    const applied = [];
    for (const [key, value] of Object.entries(preset.adjustments)) {
      if (typeof adjustments !== 'undefined' && key in adjustments) {
        adjustments[key] = value;
        
        // Update slider
        const slider = document.getElementById(`${key}Slider`);
        if (slider) {
          slider.value = value;
        }
        
        // Update value display
        const valueDisplay = document.getElementById(`${key}Value`);
        if (valueDisplay) {
          valueDisplay.textContent = value;
        }
        
        applied.push(key);
      }
    }
    
    // Apply filters
    if (typeof applyFilters === 'function') {
      applyFilters();
    }
    
    return {
      success: true,
      message: `✓ Đã áp dụng preset "${preset.name}"`,
      preset: preset,
      applied: applied,
      generatedByAI: !this.detectPreset(presetName) // Flag to indicate if it was AI-generated
    };
  }

  // Get all available presets
  getAllPresets() {
    return Object.entries(this.presets).map(([key, preset]) => ({
      key: key,
      name: preset.name,
      description: preset.description
    }));
  }

  // Get preset by category
  getPresetsByCategory() {
    return {
      'Cinematic': ['cinematic', 'cinematic teal orange', 'film noir'],
      'Vintage': ['vintage', 'retro', 'faded film'],
      'Temperature': ['warm', 'cool'],
      'Mood': ['dramatic', 'moody', 'bright'],
      'Natural': ['natural', 'portrait soft', 'landscape soft'],
      'Vibrant': ['instagram', 'vsco', 'summer', 'fuji velvia'],
      'Black & White': ['black and white', 'high contrast bw'],
      'Seasonal': ['summer', 'autumn', 'winter'],
      'Film': ['kodak portra', 'fuji velvia', 'film noir'],
      'Modern': ['matte finish', 'faded film'],
      'Portrait': ['portrait soft', 'portrait dramatic'],
      'Landscape': ['landscape vivid', 'landscape soft']
    };
  }
}

// Export
if (typeof module !== 'undefined' && module.exports) {
  module.exports = VoiceColorPresets;
}
