/**
 * Before/After Comparison
 * Multiple comparison modes for original vs edited image
 */

class BeforeAfter {
  constructor() {
    this.originalImage = null;
    this.isActive = false;
    this.mode = 'toggle'; // toggle, slider, split, side-by-side
    this.sliderPosition = 50; // For slider mode
    this.isDragging = false;
  }

  /**
   * Save original image
   */
  saveOriginal(imageDataUrl) {
    this.originalImage = imageDataUrl;
    console.log('[Before/After] Original image saved');
  }

  /**
   * Check if original exists
   */
  hasOriginal() {
    return this.originalImage !== null;
  }

  /**
   * Toggle before/after
   */
  toggle() {
    if (!this.hasOriginal()) {
      showMessage('Chưa có ảnh gốc để so sánh', 'error');
      return;
    }

    this.isActive = !this.isActive;
    
    if (this.isActive) {
      this.show();
    } else {
      this.hide();
    }
  }

  /**
   * Show comparison
   */
  show() {
    const previewImage = document.getElementById('previewImage');
    if (!previewImage) return;

    // Save current (edited) image
    this.editedImage = previewImage.src;

    // Apply mode
    switch (this.mode) {
      case 'toggle':
        this.showToggleMode();
        break;
      case 'slider':
        this.showSliderMode();
        break;
      case 'split':
        this.showSplitMode();
        break;
      case 'side-by-side':
        this.showSideBySideMode();
        break;
    }

    // Update button state
    this.updateButtonState(true);
  }

  /**
   * Hide comparison
   */
  hide() {
    const previewImage = document.getElementById('previewImage');
    if (!previewImage) return;

    // Restore edited image
    if (this.editedImage) {
      previewImage.src = this.editedImage;
    }

    // Remove overlays
    this.removeOverlays();

    // Update button state
    this.updateButtonState(false);
  }

  /**
   * Toggle mode - Click to switch between before/after
   */
  showToggleMode() {
    const previewImage = document.getElementById('previewImage');
    previewImage.src = this.originalImage;

    // Add overlay with instruction
    const overlay = document.createElement('div');
    overlay.id = 'beforeAfterOverlay';
    overlay.className = 'before-after-overlay';
    overlay.innerHTML = `
      <div class="before-after-label">BEFORE (Original)</div>
      <div class="before-after-hint">Click anywhere to see AFTER</div>
    `;

    const imageContainer = document.getElementById('imageContainer');
    imageContainer.appendChild(overlay);

    // Click to toggle
    let showingBefore = true;
    imageContainer.style.cursor = 'pointer';
    
    const toggleImage = () => {
      if (showingBefore) {
        previewImage.src = this.editedImage;
        overlay.querySelector('.before-after-label').textContent = 'AFTER (Edited)';
        overlay.querySelector('.before-after-hint').textContent = 'Click anywhere to see BEFORE';
      } else {
        previewImage.src = this.originalImage;
        overlay.querySelector('.before-after-label').textContent = 'BEFORE (Original)';
        overlay.querySelector('.before-after-hint').textContent = 'Click anywhere to see AFTER';
      }
      showingBefore = !showingBefore;
    };

    imageContainer.addEventListener('click', toggleImage);
    
    // Store for cleanup
    this.toggleHandler = toggleImage;
  }

  /**
   * Slider mode - Drag to reveal before/after
   */
  showSliderMode() {
    const imageContainer = document.getElementById('imageContainer');
    const previewImage = document.getElementById('previewImage');

    // Create before image
    const beforeImg = document.createElement('img');
    beforeImg.src = this.originalImage;
    beforeImg.className = 'before-image';
    beforeImg.style.cssText = `
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: contain;
      clip-path: inset(0 ${100 - this.sliderPosition}% 0 0);
    `;

    // Create slider handle
    const slider = document.createElement('div');
    slider.className = 'before-after-slider';
    slider.style.cssText = `
      position: absolute;
      top: 0;
      left: ${this.sliderPosition}%;
      width: 4px;
      height: 100%;
      background: white;
      cursor: ew-resize;
      z-index: 10;
      box-shadow: 0 0 10px rgba(0,0,0,0.5);
    `;

    const handle = document.createElement('div');
    handle.style.cssText = `
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 40px;
      height: 40px;
      background: white;
      border-radius: 50%;
      box-shadow: 0 2px 10px rgba(0,0,0,0.3);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
    `;
    handle.innerHTML = '⇔';
    slider.appendChild(handle);

    // Labels
    const beforeLabel = document.createElement('div');
    beforeLabel.className = 'before-after-label';
    beforeLabel.textContent = 'BEFORE';
    beforeLabel.style.cssText = `
      position: absolute;
      top: 20px;
      left: 20px;
      background: rgba(0,0,0,0.7);
      color: white;
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 600;
      z-index: 5;
    `;

    const afterLabel = document.createElement('div');
    afterLabel.className = 'before-after-label';
    afterLabel.textContent = 'AFTER';
    afterLabel.style.cssText = `
      position: absolute;
      top: 20px;
      right: 20px;
      background: rgba(0,0,0,0.7);
      color: white;
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 600;
      z-index: 5;
    `;

    imageContainer.appendChild(beforeImg);
    imageContainer.appendChild(slider);
    imageContainer.appendChild(beforeLabel);
    imageContainer.appendChild(afterLabel);

    // Drag functionality
    const onMouseMove = (e) => {
      if (!this.isDragging) return;

      const rect = imageContainer.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const percent = (x / rect.width) * 100;
      this.sliderPosition = Math.max(0, Math.min(100, percent));

      slider.style.left = this.sliderPosition + '%';
      beforeImg.style.clipPath = `inset(0 ${100 - this.sliderPosition}% 0 0)`;
    };

    const onMouseDown = () => {
      this.isDragging = true;
      imageContainer.style.cursor = 'ew-resize';
    };

    const onMouseUp = () => {
      this.isDragging = false;
      imageContainer.style.cursor = 'default';
    };

    slider.addEventListener('mousedown', onMouseDown);
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);

    // Store for cleanup
    this.sliderHandlers = { onMouseMove, onMouseDown, onMouseUp };
  }

  /**
   * Split mode - Vertical split
   */
  showSplitMode() {
    const imageContainer = document.getElementById('imageContainer');
    const previewImage = document.getElementById('previewImage');

    // Create before image (left half)
    const beforeImg = document.createElement('img');
    beforeImg.src = this.originalImage;
    beforeImg.style.cssText = `
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: contain;
      clip-path: inset(0 50% 0 0);
    `;

    // Create divider
    const divider = document.createElement('div');
    divider.style.cssText = `
      position: absolute;
      top: 0;
      left: 50%;
      width: 2px;
      height: 100%;
      background: white;
      z-index: 10;
      box-shadow: 0 0 10px rgba(0,0,0,0.5);
    `;

    // Labels
    const beforeLabel = document.createElement('div');
    beforeLabel.className = 'before-after-label';
    beforeLabel.textContent = 'BEFORE';
    beforeLabel.style.cssText = `
      position: absolute;
      top: 20px;
      left: 20px;
      background: rgba(0,0,0,0.7);
      color: white;
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 600;
      z-index: 5;
    `;

    const afterLabel = document.createElement('div');
    afterLabel.className = 'before-after-label';
    afterLabel.textContent = 'AFTER';
    afterLabel.style.cssText = `
      position: absolute;
      top: 20px;
      right: 20px;
      background: rgba(0,0,0,0.7);
      color: white;
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 600;
      z-index: 5;
    `;

    imageContainer.appendChild(beforeImg);
    imageContainer.appendChild(divider);
    imageContainer.appendChild(beforeLabel);
    imageContainer.appendChild(afterLabel);
  }

  /**
   * Side-by-side mode - Two images next to each other
   */
  showSideBySideMode() {
    // Create overlay
    const overlay = document.createElement('div');
    overlay.id = 'beforeAfterSideBySide';
    overlay.style.cssText = `
      position: fixed;
      top: 60px;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0,0,0,0.95);
      z-index: 9999;
      display: flex;
      flex-direction: column;
    `;

    // Header
    const header = document.createElement('div');
    header.style.cssText = `
      padding: 20px;
      border-bottom: 1px solid #3c3c3c;
      display: flex;
      align-items: center;
      justify-content: space-between;
    `;
    header.innerHTML = `
      <h3 style="margin: 0; color: white; font-size: 18px;">📊 Before & After Comparison</h3>
      <button onclick="beforeAfter.hide()" style="
        background: none;
        border: none;
        color: #888;
        font-size: 32px;
        cursor: pointer;
        padding: 0;
        width: 40px;
        height: 40px;
      ">×</button>
    `;

    // Content
    const content = document.createElement('div');
    content.style.cssText = `
      flex: 1;
      display: flex;
      gap: 20px;
      padding: 20px;
      overflow: hidden;
    `;

    // Before side
    const beforeSide = document.createElement('div');
    beforeSide.style.cssText = `
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 15px;
    `;
    beforeSide.innerHTML = `
      <div style="
        background: rgba(255,255,255,0.1);
        padding: 10px 20px;
        border-radius: 6px;
        color: white;
        font-weight: 600;
      ">BEFORE (Original)</div>
      <img src="${this.originalImage}" style="
        max-width: 100%;
        max-height: calc(100% - 60px);
        object-fit: contain;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.5);
      ">
    `;

    // After side
    const afterSide = document.createElement('div');
    afterSide.style.cssText = `
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 15px;
    `;
    afterSide.innerHTML = `
      <div style="
        background: rgba(74, 158, 255, 0.3);
        padding: 10px 20px;
        border-radius: 6px;
        color: white;
        font-weight: 600;
      ">AFTER (Edited)</div>
      <img src="${this.editedImage}" style="
        max-width: 100%;
        max-height: calc(100% - 60px);
        object-fit: contain;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.5);
      ">
    `;

    content.appendChild(beforeSide);
    content.appendChild(afterSide);
    overlay.appendChild(header);
    overlay.appendChild(content);
    document.body.appendChild(overlay);
  }

  /**
   * Change comparison mode
   */
  setMode(mode) {
    const wasActive = this.isActive;
    
    if (wasActive) {
      this.hide();
    }

    this.mode = mode;

    if (wasActive) {
      this.show();
    }

    console.log('[Before/After] Mode changed to:', mode);
  }

  /**
   * Remove all overlays
   */
  removeOverlays() {
    // Remove toggle overlay
    const overlay = document.getElementById('beforeAfterOverlay');
    if (overlay) overlay.remove();

    // Remove side-by-side overlay
    const sideBySide = document.getElementById('beforeAfterSideBySide');
    if (sideBySide) sideBySide.remove();

    // Remove slider elements
    const imageContainer = document.getElementById('imageContainer');
    if (imageContainer) {
      const beforeImg = imageContainer.querySelector('.before-image');
      if (beforeImg) beforeImg.remove();

      const slider = imageContainer.querySelector('.before-after-slider');
      if (slider) slider.remove();

      const labels = imageContainer.querySelectorAll('.before-after-label');
      labels.forEach(label => label.remove());

      imageContainer.style.cursor = 'default';

      // Remove event listeners
      if (this.toggleHandler) {
        imageContainer.removeEventListener('click', this.toggleHandler);
        this.toggleHandler = null;
      }

      if (this.sliderHandlers) {
        document.removeEventListener('mousemove', this.sliderHandlers.onMouseMove);
        document.removeEventListener('mouseup', this.sliderHandlers.onMouseUp);
        this.sliderHandlers = null;
      }
    }
  }

  /**
   * Update button state
   */
  updateButtonState(active) {
    // Toolbar button
    const btn = document.getElementById('beforeAfterBtn');
    if (btn) {
      if (active) {
        btn.classList.add('active');
        btn.style.background = '#4a9eff';
      } else {
        btn.classList.remove('active');
        btn.style.background = '';
      }
    }

    // Header button
    const headerBtn = document.getElementById('beforeAfterHeaderBtn');
    if (headerBtn) {
      if (active) {
        headerBtn.classList.add('active');
      } else {
        headerBtn.classList.remove('active');
      }
    }

    // Update floating button state
    if (typeof this.updateFloatingButtonState === 'function') {
      this.updateFloatingButtonState(active);
    }
  }

  /**
   * Show mode selector
   */
  async showModeSelector() {
    if (typeof Swal === 'undefined') {
      const mode = prompt('Mode: toggle, slider, split, side-by-side');
      if (mode) this.setMode(mode);
      return;
    }

    const result = await Swal.fire({
      title: '📊 Comparison Mode',
      html: `
        <div style="text-align: left; margin: 20px 0;">
          <div style="margin-bottom: 15px;">
            <input type="radio" id="mode-toggle" name="mode" value="toggle" ${this.mode === 'toggle' ? 'checked' : ''}>
            <label for="mode-toggle" style="margin-left: 8px;">
              <strong>Toggle</strong> - Click to switch
            </label>
          </div>
          <div style="margin-bottom: 15px;">
            <input type="radio" id="mode-slider" name="mode" value="slider" ${this.mode === 'slider' ? 'checked' : ''}>
            <label for="mode-slider" style="margin-left: 8px;">
              <strong>Slider</strong> - Drag to reveal
            </label>
          </div>
          <div style="margin-bottom: 15px;">
            <input type="radio" id="mode-split" name="mode" value="split" ${this.mode === 'split' ? 'checked' : ''}>
            <label for="mode-split" style="margin-left: 8px;">
              <strong>Split</strong> - Vertical split
            </label>
          </div>
          <div style="margin-bottom: 15px;">
            <input type="radio" id="mode-side" name="mode" value="side-by-side" ${this.mode === 'side-by-side' ? 'checked' : ''}>
            <label for="mode-side" style="margin-left: 8px;">
              <strong>Side-by-Side</strong> - Two images
            </label>
          </div>
        </div>
      `,
      showCancelButton: true,
      confirmButtonText: 'Apply',
      cancelButtonText: 'Cancel',
      preConfirm: () => {
        const selected = document.querySelector('input[name="mode"]:checked');
        return selected ? selected.value : null;
      }
    });

    if (result.isConfirmed && result.value) {
      this.setMode(result.value);
      if (this.isActive) {
        this.show();
      }
    }
  }

  /**
   * Clear original
   */
  clear() {
    this.originalImage = null;
    this.isActive = false;
    this.hide();
  }
}

// Create global instance
window.beforeAfter = new BeforeAfter();

console.log('[Before/After] Module loaded ✓');
