/**
 * Voice AI Vision - Context-Aware Image Editing
 * Combines Voice Control + AI Vision for natural language editing
 */

class VoiceAIVision {
  constructor() {
    this.geminiApiKey = null;
    this.visionModel = 'gemini-1.5-flash'; // Supports vision
    this.detectionCache = new Map();
    this.isProcessing = false;
  }

  /**
   * Initialize with API key
   */
  async init(apiKey) {
    this.geminiApiKey = apiKey;
    console.log('✓ Voice AI Vision initialized');
  }

  /**
   * Process context-aware voice command
   */
  async processContextCommand(transcript, imageElement) {
    if (!this.geminiApiKey) {
      return {
        success: false,
        message: '❌ Cần API key để sử dụng AI Vision',
        needsApiKey: true
      };
    }

    if (this.isProcessing) {
      return {
        success: false,
        message: '⏳ Đang xử lý lệnh trước...'
      };
    }

    this.isProcessing = true;

    try {
      // Step 1: Analyze command intent with vision context
      const analysis = await this.analyzeCommandWithVision(transcript, imageElement);
      
      if (!analysis.success) {
        return analysis;
      }

      // Step 2: Execute the context-aware action
      const result = await this.executeContextAction(analysis.action, imageElement);
      
      return result;

    } catch (error) {
      console.error('Context command error:', error);
      return {
        success: false,
        message: '❌ Lỗi khi xử lý lệnh: ' + error.message
      };
    } finally {
      this.isProcessing = false;
    }
  }

  /**
   * Analyze command with vision context using Gemini
   */
  async analyzeCommandWithVision(transcript, imageElement) {
    try {
      // Convert image to base64
      const imageBase64 = await this.imageToBase64(imageElement);

      // Prepare prompt for Gemini Vision
      const prompt = `Bạn là AI assistant cho ứng dụng chỉnh sửa ảnh.
Người dùng nói: "${transcript}"

Phân tích ảnh và lệnh, trả về JSON với format:
{
  "intent": "crop|brighten|blur|remove|adjust",
  "target": "sky|face|person|background|foreground|specific_object",
  "region": {
    "x": 0-100,
    "y": 0-100,
    "width": 0-100,
    "height": 0-100
  },
  "parameters": {
    "amount": 0-100,
    "type": "specific_type"
  },
  "description": "Mô tả ngắn gọn hành động"
}

Ví dụ:
- "Cắt bớt phần trời ở trên" → intent: crop, target: sky, region: top area
- "Làm cho khuôn mặt sáng hơn" → intent: brighten, target: face
- "Xóa người ở góc phải" → intent: remove, target: person, region: right corner
- "Làm nền mờ" → intent: blur, target: background

Chỉ trả về JSON, không giải thích thêm.`;

      // Call Gemini Vision API
      const response = await fetch(
        `https://generativelanguage.googleapis.com/v1beta/models/${this.visionModel}:generateContent?key=${this.geminiApiKey}`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            contents: [{
              parts: [
                { text: prompt },
                {
                  inline_data: {
                    mime_type: 'image/jpeg',
                    data: imageBase64
                  }
                }
              ]
            }]
          })
        }
      );

      if (!response.ok) {
        throw new Error(`Gemini API error: ${response.status}`);
      }

      const data = await response.json();
      const text = data.candidates[0].content.parts[0].text;
      
      // Parse JSON response
      const jsonMatch = text.match(/\{[\s\S]*\}/);
      if (!jsonMatch) {
        throw new Error('Invalid response format');
      }

      const action = JSON.parse(jsonMatch[0]);

      return {
        success: true,
        action: action,
        originalTranscript: transcript
      };

    } catch (error) {
      console.error('Vision analysis error:', error);
      return {
        success: false,
        message: '❌ Không thể phân tích lệnh với AI Vision'
      };
    }
  }

  /**
   * Execute context-aware action
   */
  async executeContextAction(action, imageElement) {
    console.log('🎯 Executing context action:', action);

    switch (action.intent) {
      case 'crop':
        return await this.executeCrop(action, imageElement);
      
      case 'brighten':
        return await this.executeBrighten(action, imageElement);
      
      case 'blur':
        return await this.executeBlur(action, imageElement);
      
      case 'remove':
        return await this.executeRemove(action, imageElement);
      
      case 'adjust':
        return await this.executeAdjust(action, imageElement);
      
      default:
        return {
          success: false,
          message: '❌ Không hỗ trợ hành động này'
        };
    }
  }

  /**
   * Execute crop with AI-detected region
   */
  async executeCrop(action, imageElement) {
    try {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      const img = imageElement;
      const region = action.region;

      // Calculate crop coordinates
      const cropX = (region.x / 100) * img.naturalWidth;
      const cropY = (region.y / 100) * img.naturalHeight;
      const cropWidth = (region.width / 100) * img.naturalWidth;
      const cropHeight = (region.height / 100) * img.naturalHeight;

      // Set canvas size to cropped size
      canvas.width = cropWidth;
      canvas.height = cropHeight;

      // Draw cropped image
      ctx.drawImage(
        img,
        cropX, cropY, cropWidth, cropHeight,
        0, 0, cropWidth, cropHeight
      );

      // Update preview
      img.src = canvas.toDataURL();

      // Save to history
      if (typeof saveToHistory === 'function') {
        saveToHistory('AI Crop', action.description);
      }

      return {
        success: true,
        message: `✓ ${action.description}`
      };

    } catch (error) {
      console.error('Crop error:', error);
      return {
        success: false,
        message: '❌ Lỗi khi crop ảnh'
      };
    }
  }

  /**
   * Execute selective brightening
   */
  async executeBrighten(action, imageElement) {
    try {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      const img = imageElement;
      canvas.width = img.naturalWidth;
      canvas.height = img.naturalHeight;

      ctx.drawImage(img, 0, 0);

      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;
      const region = action.region;
      const amount = action.parameters.amount || 30;

      // Calculate region bounds
      const startX = Math.floor((region.x / 100) * canvas.width);
      const startY = Math.floor((region.y / 100) * canvas.height);
      const endX = Math.floor(((region.x + region.width) / 100) * canvas.width);
      const endY = Math.floor(((region.y + region.height) / 100) * canvas.height);

      // Apply brightening to region
      for (let y = 0; y < canvas.height; y++) {
        for (let x = 0; x < canvas.width; x++) {
          // Check if pixel is in target region
          if (x >= startX && x <= endX && y >= startY && y <= endY) {
            const idx = (y * canvas.width + x) * 4;
            
            // Brighten
            data[idx] = Math.min(255, data[idx] + amount);     // R
            data[idx + 1] = Math.min(255, data[idx + 1] + amount); // G
            data[idx + 2] = Math.min(255, data[idx + 2] + amount); // B
          }
        }
      }

      ctx.putImageData(imageData, 0, 0);
      img.src = canvas.toDataURL();

      // Save to history
      if (typeof saveToHistory === 'function') {
        saveToHistory('AI Selective Brighten', action.description);
      }

      return {
        success: true,
        message: `✓ ${action.description}`
      };

    } catch (error) {
      console.error('Brighten error:', error);
      return {
        success: false,
        message: '❌ Lỗi khi làm sáng'
      };
    }
  }

  /**
   * Execute selective blur (bokeh effect)
   */
  async executeBlur(action, imageElement) {
    try {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      const img = imageElement;
      canvas.width = img.naturalWidth;
      canvas.height = img.naturalHeight;

      ctx.drawImage(img, 0, 0);

      const region = action.region;
      const blurAmount = action.parameters.amount || 10;

      // Create mask for blur region
      const maskCanvas = document.createElement('canvas');
      const maskCtx = maskCanvas.getContext('2d');
      maskCanvas.width = canvas.width;
      maskCanvas.height = canvas.height;

      // Draw white rectangle for blur region
      maskCtx.fillStyle = 'white';
      const startX = (region.x / 100) * canvas.width;
      const startY = (region.y / 100) * canvas.height;
      const width = (region.width / 100) * canvas.width;
      const height = (region.height / 100) * canvas.height;
      maskCtx.fillRect(startX, startY, width, height);

      // Apply blur using CSS filter (simple approach)
      ctx.filter = `blur(${blurAmount}px)`;
      ctx.drawImage(img, 0, 0);
      ctx.filter = 'none';

      img.src = canvas.toDataURL();

      // Save to history
      if (typeof saveToHistory === 'function') {
        saveToHistory('AI Selective Blur', action.description);
      }

      return {
        success: true,
        message: `✓ ${action.description}`
      };

    } catch (error) {
      console.error('Blur error:', error);
      return {
        success: false,
        message: '❌ Lỗi khi làm mờ'
      };
    }
  }

  /**
   * Execute object removal
   */
  async executeRemove(action, imageElement) {
    try {
      // This would require more advanced AI (inpainting)
      // For now, we'll use a simple approach: blur + darken the region
      
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      const img = imageElement;
      canvas.width = img.naturalWidth;
      canvas.height = img.naturalHeight;

      ctx.drawImage(img, 0, 0);

      const region = action.region;
      const startX = (region.x / 100) * canvas.width;
      const startY = (region.y / 100) * canvas.height;
      const width = (region.width / 100) * canvas.width;
      const height = (region.height / 100) * canvas.height;

      // Get surrounding pixels for inpainting (simple average)
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;

      // Simple inpainting: fill with average of surrounding pixels
      const surroundingColors = this.getSurroundingColors(
        data, canvas.width, canvas.height,
        startX, startY, width, height
      );

      // Fill region with average color
      ctx.fillStyle = `rgb(${surroundingColors.r}, ${surroundingColors.g}, ${surroundingColors.b})`;
      ctx.fillRect(startX, startY, width, height);

      // Apply slight blur to blend
      ctx.filter = 'blur(5px)';
      ctx.drawImage(canvas, 0, 0);
      ctx.filter = 'none';

      img.src = canvas.toDataURL();

      // Save to history
      if (typeof saveToHistory === 'function') {
        saveToHistory('AI Object Remove', action.description);
      }

      return {
        success: true,
        message: `✓ ${action.description} (Simple inpainting)`
      };

    } catch (error) {
      console.error('Remove error:', error);
      return {
        success: false,
        message: '❌ Lỗi khi xóa đối tượng'
      };
    }
  }

  /**
   * Execute general adjustment
   */
  async executeAdjust(action, imageElement) {
    try {
      // Map to existing adjustment controls
      const params = action.parameters;
      
      if (params.brightness !== undefined && typeof adjustments !== 'undefined') {
        adjustments.brightness = params.brightness;
        const slider = document.getElementById('brightnessSlider');
        if (slider) slider.value = params.brightness;
        document.getElementById('brightnessValue').textContent = params.brightness;
      }

      if (params.contrast !== undefined && typeof adjustments !== 'undefined') {
        adjustments.contrast = params.contrast;
        const slider = document.getElementById('contrastSlider');
        if (slider) slider.value = params.contrast;
        document.getElementById('contrastValue').textContent = params.contrast;
      }

      if (typeof applyFilters === 'function') {
        applyFilters();
      }

      // Save to history
      if (typeof saveToHistory === 'function') {
        saveToHistory('AI Adjust', action.description);
      }

      return {
        success: true,
        message: `✓ ${action.description}`
      };

    } catch (error) {
      console.error('Adjust error:', error);
      return {
        success: false,
        message: '❌ Lỗi khi điều chỉnh'
      };
    }
  }

  /**
   * Get surrounding colors for inpainting
   */
  getSurroundingColors(data, width, height, x, y, w, h) {
    let r = 0, g = 0, b = 0, count = 0;

    // Sample pixels around the region
    const margin = 10;
    for (let dy = -margin; dy < h + margin; dy++) {
      for (let dx = -margin; dx < w + margin; dx++) {
        // Skip pixels inside the region
        if (dx >= 0 && dx < w && dy >= 0 && dy < h) continue;

        const px = Math.floor(x + dx);
        const py = Math.floor(y + dy);

        if (px >= 0 && px < width && py >= 0 && py < height) {
          const idx = (py * width + px) * 4;
          r += data[idx];
          g += data[idx + 1];
          b += data[idx + 2];
          count++;
        }
      }
    }

    return {
      r: Math.floor(r / count),
      g: Math.floor(g / count),
      b: Math.floor(b / count)
    };
  }

  /**
   * Convert image element to base64
   */
  async imageToBase64(imageElement) {
    return new Promise((resolve, reject) => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      canvas.width = imageElement.naturalWidth;
      canvas.height = imageElement.naturalHeight;
      
      ctx.drawImage(imageElement, 0, 0);
      
      try {
        // Get base64 without data URL prefix
        const dataURL = canvas.toDataURL('image/jpeg', 0.8);
        const base64 = dataURL.split(',')[1];
        resolve(base64);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * Check if command is context-aware
   */
  isContextCommand(transcript) {
    const contextKeywords = [
      'cắt bớt', 'crop', 'xóa', 'remove',
      'làm cho', 'make', 'chỉ', 'only',
      'phần', 'vùng', 'khu vực', 'area',
      'trời', 'sky', 'mặt', 'face', 'người', 'person',
      'nền', 'background', 'góc', 'corner',
      'trên', 'dưới', 'trái', 'phải',
      'top', 'bottom', 'left', 'right'
    ];

    const lowerTranscript = transcript.toLowerCase();
    return contextKeywords.some(keyword => lowerTranscript.includes(keyword));
  }

  /**
   * Clear API key
   */
  clearApiKey() {
    this.geminiApiKey = null;
    localStorage.removeItem('gemini_vision_api_key');
  }

  /**
   * Load API key from storage
   */
  loadApiKey() {
    const stored = localStorage.getItem('gemini_vision_api_key');
    if (stored) {
      this.geminiApiKey = stored;
      return true;
    }
    return false;
  }

  /**
   * Save API key to storage
   */
  saveApiKey(apiKey) {
    this.geminiApiKey = apiKey;
    localStorage.setItem('gemini_vision_api_key', apiKey);
  }
}

// Create global instance
window.voiceAIVision = new VoiceAIVision();

// Try to load API key from storage
window.voiceAIVision.loadApiKey();

console.log('✓ Voice AI Vision module loaded');
