// ============================================
// PRESET MANAGER
// ============================================

class PresetManager {
  constructor() {
    this.presets = this.loadPresetsFromVoiceControl();
    this.customPresets = this.loadCustomPresets();
    this.currentPreset = null;
    this.initializeUI();
  }

  // Load presets từ voice-color-presets.js
  loadPresetsFromVoiceControl() {
    if (typeof VoiceColorPresets !== 'undefined') {
      const voicePresets = new VoiceColorPresets();
      return voicePresets.presets;
    }
    return {};
  }

  // Load custom presets từ localStorage
  loadCustomPresets() {
    const saved = localStorage.getItem('customPresets');
    return saved ? JSON.parse(saved) : {};
  }

  // Save custom presets
  saveCustomPresets() {
    localStorage.setItem('customPresets', JSON.stringify(this.customPresets));
  }

  // Initialize UI
  initializeUI() {
    // Chỉ render khi cần thiết
    this.attachEventListeners();
    
    // Render ngay nếu presetsSection đã visible
    const presetsSection = document.getElementById('presetsSection');
    if (presetsSection && presetsSection.style.display !== 'none') {
      this.renderPresetList();
    }
  }

  // Render preset list
  renderPresetList() {
    const container = document.getElementById('presetList');
    if (!container) {
      console.log('PresetManager: presetList container not found');
      return;
    }

    console.log('PresetManager: Rendering presets...', {
      builtIn: Object.keys(this.presets).length,
      custom: Object.keys(this.customPresets).length
    });

    container.innerHTML = '';

    // Built-in presets
    const builtInSection = document.createElement('div');
    builtInSection.className = 'preset-section';
    builtInSection.innerHTML = '<div class="preset-section-title">📦 Built-in Presets</div>';
    
    Object.entries(this.presets).forEach(([key, preset]) => {
      const presetCard = this.createPresetCard(key, preset, false);
      builtInSection.appendChild(presetCard);
    });
    
    container.appendChild(builtInSection);

    // Custom presets
    if (Object.keys(this.customPresets).length > 0) {
      const customSection = document.createElement('div');
      customSection.className = 'preset-section';
      customSection.innerHTML = '<div class="preset-section-title">⭐ Custom Presets</div>';
      
      Object.entries(this.customPresets).forEach(([key, preset]) => {
        const presetCard = this.createPresetCard(key, preset, true);
        customSection.appendChild(presetCard);
      });
      
      container.appendChild(customSection);
    }
  }

  // Create preset card
  createPresetCard(key, preset, isCustom) {
    const card = document.createElement('div');
    card.className = 'preset-card';
    card.dataset.presetKey = key;
    
    card.innerHTML = `
      <div class="preset-card-header">
        <div class="preset-card-title">${preset.name}</div>
        ${isCustom ? `
          <button class="preset-delete-btn" data-key="${key}" title="Xóa preset">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
          </button>
        ` : ''}
      </div>
      <div class="preset-card-description">${preset.description}</div>
      <div class="preset-card-actions">
        <button class="preset-apply-btn" data-key="${key}">
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
          </svg>
          Áp dụng
        </button>
        <button class="preset-export-btn" data-key="${key}" title="Export preset">
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
          </svg>
        </button>
      </div>
    `;
    
    return card;
  }

  // Attach event listeners
  attachEventListeners() {
    // Apply preset
    document.addEventListener('click', (e) => {
      if (e.target.closest('.preset-apply-btn')) {
        const btn = e.target.closest('.preset-apply-btn');
        const key = btn.dataset.key;
        this.applyPreset(key);
      }
    });

    // Delete preset
    document.addEventListener('click', (e) => {
      if (e.target.closest('.preset-delete-btn')) {
        const btn = e.target.closest('.preset-delete-btn');
        const key = btn.dataset.key;
        this.deletePreset(key);
      }
    });

    // Export preset
    document.addEventListener('click', (e) => {
      if (e.target.closest('.preset-export-btn')) {
        const btn = e.target.closest('.preset-export-btn');
        const key = btn.dataset.key;
        this.exportPreset(key);
      }
    });

    // Save current as preset
    const saveBtn = document.getElementById('saveCurrentPresetBtn');
    if (saveBtn) {
      saveBtn.addEventListener('click', () => this.saveCurrentAsPreset());
    }

    // Import preset
    const importBtn = document.getElementById('importPresetBtn');
    if (importBtn) {
      importBtn.addEventListener('click', () => this.importPreset());
    }

    // Create new preset
    const createBtn = document.getElementById('createPresetBtn');
    if (createBtn) {
      createBtn.addEventListener('click', () => this.createNewPreset());
    }
  }

  // Apply preset
  applyPreset(key) {
    const preset = this.presets[key] || this.customPresets[key];
    if (!preset) return;

    this.currentPreset = key;
    
    // Apply adjustments
    const adjustments = preset.adjustments;
    
    // Apply to sliders
    Object.entries(adjustments).forEach(([key, value]) => {
      const slider = document.getElementById(`${key}Slider`);
      if (slider) {
        slider.value = value;
        slider.dispatchEvent(new Event('input', { bubbles: true }));
      }
    });

    // Show feedback
    this.showFeedback(`✓ Đã áp dụng preset "${preset.name}"`, 'success');
    
    // Highlight active preset
    document.querySelectorAll('.preset-card').forEach(card => {
      card.classList.remove('active');
    });
    const activeCard = document.querySelector(`[data-preset-key="${key}"]`);
    if (activeCard) {
      activeCard.classList.add('active');
    }
  }

  // Save current adjustments as preset
  async saveCurrentAsPreset() {
    const result = await Swal.fire({
      title: 'Lưu Preset',
      html: `
        <input id="presetName" class="swal2-input" placeholder="Tên preset">
        <textarea id="presetDescription" class="swal2-textarea" placeholder="Mô tả (tùy chọn)"></textarea>
      `,
      showCancelButton: true,
      confirmButtonText: 'Lưu',
      cancelButtonText: 'Hủy',
      preConfirm: () => {
        const name = document.getElementById('presetName').value;
        const description = document.getElementById('presetDescription').value;
        
        if (!name) {
          Swal.showValidationMessage('Vui lòng nhập tên preset');
          return false;
        }
        
        return { name, description };
      }
    });

    if (result.isConfirmed) {
      const { name, description } = result.value;
      const key = name.toLowerCase().replace(/\s+/g, '-');
      
      // Get current adjustments
      const adjustments = this.getCurrentAdjustments();
      
      // Save to custom presets
      this.customPresets[key] = {
        name,
        description: description || `Custom preset: ${name}`,
        adjustments
      };
      
      this.saveCustomPresets();
      this.renderPresetList();
      this.showFeedback(`✓ Đã lưu preset "${name}"`, 'success');
    }
  }

  // Get current adjustments from sliders
  getCurrentAdjustments() {
    const adjustments = {};
    const sliders = [
      'brightness', 'contrast', 'saturation', 'temperature', 
      'tint', 'highlights', 'shadows', 'vibrance', 'clarity'
    ];
    
    sliders.forEach(key => {
      const slider = document.getElementById(`${key}Slider`);
      if (slider) {
        adjustments[key] = parseInt(slider.value);
      }
    });
    
    return adjustments;
  }

  // Delete preset
  async deletePreset(key) {
    const preset = this.customPresets[key];
    if (!preset) return;

    const result = await Swal.fire({
      title: 'Xóa Preset?',
      text: `Bạn có chắc muốn xóa preset "${preset.name}"?`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Xóa',
      cancelButtonText: 'Hủy',
      confirmButtonColor: '#d33'
    });

    if (result.isConfirmed) {
      delete this.customPresets[key];
      this.saveCustomPresets();
      this.renderPresetList();
      this.showFeedback(`✓ Đã xóa preset "${preset.name}"`, 'success');
    }
  }

  // Export preset
  exportPreset(key) {
    const preset = this.presets[key] || this.customPresets[key];
    if (!preset) return;

    const data = {
      name: preset.name,
      description: preset.description,
      adjustments: preset.adjustments,
      version: '1.0',
      exportedAt: new Date().toISOString()
    };

    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${preset.name.replace(/\s+/g, '-')}.preset.json`;
    a.click();
    URL.revokeObjectURL(url);

    this.showFeedback(`✓ Đã export preset "${preset.name}"`, 'success');
  }

  // Import preset
  async importPreset() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json,.preset.json';
    
    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      try {
        const text = await file.text();
        const data = JSON.parse(text);
        
        // Validate
        if (!data.name || !data.adjustments) {
          throw new Error('Invalid preset file');
        }

        const key = data.name.toLowerCase().replace(/\s+/g, '-');
        
        // Check if exists
        if (this.customPresets[key]) {
          const result = await Swal.fire({
            title: 'Preset đã tồn tại',
            text: `Preset "${data.name}" đã tồn tại. Bạn có muốn ghi đè?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Ghi đè',
            cancelButtonText: 'Hủy'
          });
          
          if (!result.isConfirmed) return;
        }

        // Import
        this.customPresets[key] = {
          name: data.name,
          description: data.description,
          adjustments: data.adjustments
        };
        
        this.saveCustomPresets();
        this.renderPresetList();
        this.showFeedback(`✓ Đã import preset "${data.name}"`, 'success');
        
      } catch (error) {
        this.showFeedback(`❌ Lỗi: ${error.message}`, 'error');
      }
    };
    
    input.click();
  }

  // Create new preset from scratch
  async createNewPreset() {
    const result = await Swal.fire({
      title: 'Tạo Preset Mới',
      html: `
        <input id="presetName" class="swal2-input" placeholder="Tên preset">
        <textarea id="presetDescription" class="swal2-textarea" placeholder="Mô tả"></textarea>
        <div style="margin-top: 15px; text-align: left; font-size: 13px; color: #666;">
          💡 Preset sẽ được tạo với giá trị mặc định (0). Bạn có thể điều chỉnh sau khi áp dụng.
        </div>
      `,
      showCancelButton: true,
      confirmButtonText: 'Tạo',
      cancelButtonText: 'Hủy',
      preConfirm: () => {
        const name = document.getElementById('presetName').value;
        const description = document.getElementById('presetDescription').value;
        
        if (!name) {
          Swal.showValidationMessage('Vui lòng nhập tên preset');
          return false;
        }
        
        return { name, description };
      }
    });

    if (result.isConfirmed) {
      const { name, description } = result.value;
      const key = name.toLowerCase().replace(/\s+/g, '-');
      
      // Create with default values
      this.customPresets[key] = {
        name,
        description: description || `Custom preset: ${name}`,
        adjustments: {
          brightness: 0,
          contrast: 0,
          saturation: 0,
          temperature: 0,
          tint: 0,
          highlights: 0,
          shadows: 0,
          vibrance: 0,
          clarity: 0
        }
      };
      
      this.saveCustomPresets();
      this.renderPresetList();
      this.showFeedback(`✓ Đã tạo preset "${name}"`, 'success');
    }
  }

  // Show feedback
  showFeedback(message, type = 'info') {
    const feedback = document.getElementById('presetFeedback');
    if (!feedback) return;

    feedback.textContent = message;
    feedback.className = `preset-feedback ${type}`;
    feedback.style.display = 'block';

    setTimeout(() => {
      feedback.style.display = 'none';
    }, 3000);
  }
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
  window.presetManager = new PresetManager();
  
  // Render khi tab Presets được click
  const presetTab = document.querySelector('[data-tab="presets"]');
  if (presetTab) {
    presetTab.addEventListener('click', () => {
      setTimeout(() => {
        if (window.presetManager) {
          window.presetManager.renderPresetList();
        }
      }, 100);
    });
  }
});
