// Theme detection and toggle
(function initTheme() {
  const stored = localStorage.getItem('imagelite-theme');
  if (stored) {
    document.documentElement.setAttribute('data-theme', stored);
  } else if (window.matchMedia('(prefers-color-scheme: light)').matches) {
    document.documentElement.setAttribute('data-theme', 'light');
  } else {
    document.documentElement.setAttribute('data-theme', 'dark');
  }
})();

document.getElementById('theme-toggle').addEventListener('click', () => {
  const current = document.documentElement.getAttribute('data-theme');
  const next = current === 'dark' ? 'light' : 'dark';
  document.documentElement.setAttribute('data-theme', next);
  localStorage.setItem('imagelite-theme', next);
});

// --- App State ---
const state = {
  images: [],
  settings: {
    format: 'image/webp',
    quality: 82,
    maxWidth: null,
    removeMetadata: true
  }
};

// --- DOM Elements ---
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const imageList = document.getElementById('image-list');
const summaryFooter = document.getElementById('summary-footer');
const summaryText = document.getElementById('summary-text');
const settingsPanel = document.getElementById('settings-panel');
const formatSelect = document.getElementById('format-select');
const qualitySlider = document.getElementById('quality-slider');
const qualityValue = document.getElementById('quality-value');
const maxWidthInput = document.getElementById('max-width');
const removeMetadataCheck = document.getElementById('remove-metadata');
const downloadAllZipBtn = document.getElementById('download-all-zip');

// --- Settings Sync ---
function updateSettingsFromUI() {
  state.settings.format = formatSelect.value;
  state.settings.quality = parseInt(qualitySlider.value);
  state.settings.maxWidth = maxWidthInput.value ? parseInt(maxWidthInput.value) : null;
  state.settings.removeMetadata = removeMetadataCheck.checked;
  qualityValue.textContent = state.settings.quality;
}

formatSelect.addEventListener('change', updateSettingsFromUI);
qualitySlider.addEventListener('input', updateSettingsFromUI);
maxWidthInput.addEventListener('input', updateSettingsFromUI);
removeMetadataCheck.addEventListener('change', updateSettingsFromUI);

// --- Load saved settings ---
chrome.storage.local.get(['imageliteSettings'], (result) => {
  if (result.imageliteSettings) {
    const s = result.imageliteSettings;
    state.settings = { ...state.settings, ...s };
    formatSelect.value = state.settings.format;
    qualitySlider.value = state.settings.quality;
    qualityValue.textContent = state.settings.quality;
    if (state.settings.maxWidth) maxWidthInput.value = state.settings.maxWidth;
    removeMetadataCheck.checked = state.settings.removeMetadata;
  }
});

function saveSettings() {
  chrome.storage.local.set({ imageliteSettings: state.settings });
}

// --- File Handling ---
dropZone.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', (e) => handleFiles(e.target.files));

dropZone.addEventListener('dragover', (e) => {
  e.preventDefault();
  dropZone.classList.add('drag-over');
});

dropZone.addEventListener('dragleave', () => {
  dropZone.classList.remove('drag-over');
});

dropZone.addEventListener('drop', (e) => {
  e.preventDefault();
  dropZone.classList.remove('drag-over');
  handleFiles(e.dataTransfer.files);
});

document.addEventListener('paste', async (e) => {
  const items = e.clipboardData?.items;
  if (!items) return;
  
  for (const item of items) {
    if (item.type.startsWith('image/')) {
      const blob = item.getAsFile();
      if (blob) {
        await addImage(blob);
        showToast('Image pasted from clipboard');
      }
    }
  }
});

// Check for pending clipboard image from popup
chrome.storage.local.get(['pendingClipboardImage', 'pendingClipboardType'], async (result) => {
  if (result.pendingClipboardImage) {
    const response = await fetch(result.pendingClipboardImage);
    const blob = await response.blob();
    const ext = result.pendingClipboardType?.split('/')[1] || 'png';
    const file = new File([blob], `clipboard.${ext}`, { type: result.pendingClipboardType || 'image/png' });
    await addImage(file);
    chrome.storage.local.remove(['pendingClipboardImage', 'pendingClipboardType']);
  }
});

async function handleFiles(files) {
  for (const file of files) {
    if (file.type.startsWith('image/')) {
      await addImage(file);
    } else {
      showToast(`Skipped: ${file.name} (not an image)`);
    }
  }
}

async function addImage(file) {
  const id = crypto.randomUUID();
  const imageData = {
    id,
    originalFile: file,
    originalName: file.name,
    originalSize: file.size,
    originalType: file.type,
    status: 'processing',
    outputBlob: null,
    outputSize: null,
    warnings: []
  };

  state.images.unshift(imageData);
  renderAll();

  try {
    const result = await ImageProcessor.process(file, state.settings);
    imageData.outputBlob = result.blob;
    imageData.outputSize = result.blob.size;
    imageData.dimensions = result.dimensions;
    imageData.originalDimensions = result.originalDimensions;
    
    if (result.warnings?.length) {
      imageData.warnings = result.warnings;
    }
    
    imageData.status = 'ready';
  } catch (err) {
    imageData.status = 'failed';
    imageData.error = err.message;
    console.error('Processing failed:', err);
  }

  renderAll();
  updateSummary();
}

// --- Rendering ---
function renderAll() {
  if (state.images.length > 0) {
    settingsPanel.style.display = 'block';
    summaryFooter.style.display = 'flex';
    dropZone.querySelector('.drop-zone__content').innerHTML = `
      <svg class="drop-zone__icon" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
      <p class="drop-zone__title">Drop more images</p>
    `;
  } else {
    settingsPanel.style.display = 'none';
    summaryFooter.style.display = 'none';
    dropZone.querySelector('.drop-zone__content').innerHTML = `
      <svg class="drop-zone__icon" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
      <p class="drop-zone__title">Drop images here</p>
      <p class="drop-zone__sub">or click to browse · paste from clipboard</p>
      <p class="drop-zone__formats">PNG, JPG, JPEG, WebP</p>
    `;
  }

  renderImageList();
  updateSummary();
}

function renderImageList() {
  imageList.innerHTML = state.images.map(img => {
    const originalUrl = URL.createObjectURL(img.originalFile);
    const outputUrl = img.outputBlob ? URL.createObjectURL(img.outputBlob) : null;
    const savedPercent = img.outputSize ? ((1 - img.outputSize / img.originalSize) * 100).toFixed(1) : null;
    const savedPositive = savedPercent !== null && savedPercent > 0;

    return `
      <div class="image-card ${img.status === 'processing' ? 'image-card--processing' : ''}" data-id="${img.id}">
        <div class="image-card__preview" data-id="${img.id}">
          <img src="${outputUrl || originalUrl}" alt="${img.originalName}" class="image-card__preview-img" data-preview="${img.id}">
          ${img.status === 'ready' ? `
            <span class="image-card__preview-badge">${getFormatLabel(state.settings.format)}</span>
            <button class="image-card__compare-toggle" data-compare="${img.id}">Original</button>
          ` : ''}
          ${img.status === 'processing' ? '<span class="image-card__preview-badge">Processing...</span>' : ''}
        </div>
        <div class="image-card__body">
          <div class="image-card__name">${img.originalName}</div>
          
          ${img.status === 'failed' ? `
            <div class="image-card__warning">⚠️ ${img.error || 'Processing failed'}</div>
          ` : ''}
          
          ${img.status === 'ready' ? `
            <div class="image-card__stats">
              <div class="image-card__stat">
                <strong>${formatBytes(img.originalSize)}</strong>
                Original ${img.originalDimensions ? `· ${img.originalDimensions.w}×${img.originalDimensions.h}` : ''}
              </div>
              <div class="image-card__stat">
                <strong>${formatBytes(img.outputSize)}</strong>
                <span class="image-card__saved ${!savedPositive ? 'image-card__saved--negative' : ''}">
                  ${savedPositive ? 'Saved ' + savedPercent + '%' : 'Larger by ' + Math.abs(savedPercent) + '%'}
                </span>
              </div>
            </div>
            ${img.warnings?.length ? img.warnings.map(w => `<div class="image-card__warning">⚠️ ${w}</div>`).join('') : ''}
            <div class="image-card__actions">
              <button class="image-card__btn image-card__btn--primary" data-download="${img.id}">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                Download
              </button>
              <button class="image-card__btn" data-copy="${img.id}">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
                Copy
              </button>
              <button class="image-card__btn" data-copy-html="${img.id}">
                Copy HTML
              </button>
              <button class="image-card__btn" data-remove="${img.id}">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
              </button>
            </div>
          ` : ''}
        </div>
      </div>
    `;
  }).join('');

  // Attach event listeners
  attachCardListeners();
}

function attachCardListeners() {
  // Download single image
  document.querySelectorAll('[data-download]').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const id = btn.dataset.download;
      const img = state.images.find(i => i.id === id);
      if (img?.outputBlob) {
        downloadBlob(img.outputBlob, getOutputFilename(img.originalName));
        showToast('Downloaded!');
      }
    });
  });

  // Copy image to clipboard
  document.querySelectorAll('[data-copy]').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.stopPropagation();
      const id = btn.dataset.copy;
      const img = state.images.find(i => i.id === id);
      if (img?.outputBlob) {
        try {
          await navigator.clipboard.write([
            new ClipboardItem({ [img.outputBlob.type]: img.outputBlob })
          ]);
          showToast('Image copied to clipboard');
        } catch (err) {
          showToast('Failed to copy image');
        }
      }
    });
  });

  // Copy HTML snippet
  document.querySelectorAll('[data-copy-html]').forEach(btn => {
    btn.addEventListener('click', async (e) => {
      e.stopPropagation();
      const id = btn.dataset.copyHtml;
      const img = state.images.find(i => i.id === id);
      if (img) {
        const filename = getOutputFilename(img.originalName);
        const dims = img.dimensions;
        const html = `<img src="/assets/${filename}" width="${dims.w}" height="${dims.h}" alt="">`;
        try {
          await navigator.clipboard.writeText(html);
          showToast('HTML snippet copied');
        } catch (err) {
          showToast('Failed to copy HTML');
        }
      }
    });
  });

  // Remove image
  document.querySelectorAll('[data-remove]').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const id = btn.dataset.remove;
      state.images = state.images.filter(i => i.id !== id);
      renderAll();
    });
  });

  // Compare toggle (original vs optimized)
  document.querySelectorAll('[data-compare]').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const id = btn.dataset.compare;
      const img = state.images.find(i => i.id === id);
      const previewImg = document.querySelector(`[data-preview="${id}"]`);
      if (!img || !previewImg) return;

      const isShowingOriginal = btn.textContent.trim() === 'Original';
      if (isShowingOriginal) {
        previewImg.src = URL.createObjectURL(img.originalFile);
        btn.textContent = 'Optimized';
      } else {
        previewImg.src = URL.createObjectURL(img.outputBlob);
        btn.textContent = 'Original';
      }
    });
  });
}

function updateSummary() {
  const readyImages = state.images.filter(i => i.status === 'ready');
  if (readyImages.length === 0 && state.images.length === 0) {
    summaryFooter.style.display = 'none';
    return;
  }

  const totalOriginal = state.images.reduce((sum, i) => sum + i.originalSize, 0);
  const totalOutput = readyImages.reduce((sum, i) => sum + (i.outputSize || i.originalSize), 0);
  
  // Include processing images at original size
  const processingOriginal = state.images.filter(i => i.status === 'processing').reduce((sum, i) => sum + i.originalSize, 0);
  const displayOriginal = totalOriginal;
  const displayOutput = totalOutput + processingOriginal;
  
  const savedPercent = displayOriginal > 0 ? ((1 - displayOutput / displayOriginal) * 100).toFixed(1) : 0;
  const savedPositive = savedPercent > 0;

  summaryText.innerHTML = `
    ${state.images.length} image${state.images.length !== 1 ? 's' : ''}
    · Original: ${formatBytes(displayOriginal)}
    → Optimized: ${formatBytes(displayOutput)}
    · <span style="color: ${savedPositive ? '#22c55e' : '#ef4444'}">
      ${savedPositive ? 'Saved ' + savedPercent + '%' : 'Larger by ' + Math.abs(savedPercent) + '%'}
    </span>
  `;
  summaryFooter.style.display = 'flex';

  // Enable/disable download all
  downloadAllZipBtn.disabled = readyImages.length === 0;
}

// --- Download All as ZIP ---
downloadAllZipBtn.addEventListener('click', async () => {
  const readyImages = state.images.filter(i => i.status === 'ready' && i.outputBlob);
  if (readyImages.length === 0) {
    showToast('No optimized images to download');
    return;
  }

  try {
    const zip = new JSZip();
    readyImages.forEach(img => {
      const filename = getOutputFilename(img.originalName);
      zip.file(filename, img.outputBlob);
    });

    const content = await zip.generateAsync({ type: 'blob' });
    downloadBlob(content, 'imagelite-images.zip');
    showToast('ZIP downloaded!');
  } catch (err) {
    showToast('Failed to create ZIP');
    console.error(err);
  }
});

// --- Utility Functions ---
function getOutputFilename(originalName) {
  const dotIndex = originalName.lastIndexOf('.');
  const baseName = dotIndex > 0 ? originalName.substring(0, dotIndex) : originalName;
  const ext = getFormatExtension(state.settings.format);
  return `${baseName}${ext}`;
}

function getFormatLabel(mimeType) {
  const map = {
    'image/webp': 'WebP',
    'image/jpeg': 'JPEG',
    'image/png': 'PNG'
  };
  return map[mimeType] || mimeType;
}

function getFormatExtension(mimeType) {
  const map = {
    'image/webp': '.webp',
    'image/jpeg': '.jpg',
    'image/png': '.png'
  };
  return map[mimeType] || '.png';
}

function formatBytes(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  const val = parseFloat((bytes / Math.pow(k, i)).toFixed(1));
  return `${val} ${sizes[i]}`;
}

function downloadBlob(blob, filename) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

function showToast(message) {
  let toast = document.querySelector('.toast');
  if (!toast) {
    toast = document.createElement('div');
    toast.className = 'toast';
    document.body.appendChild(toast);
  }
  toast.textContent = message;
  toast.classList.add('is-visible');
  clearTimeout(toast._timeout);
  toast._timeout = setTimeout(() => {
    toast.classList.remove('is-visible');
  }, 2000);
}

// Save settings when changed
['change', 'input'].forEach(eventType => {
  formatSelect.addEventListener(eventType, saveSettings);
  qualitySlider.addEventListener(eventType, saveSettings);
  maxWidthInput.addEventListener(eventType, saveSettings);
  removeMetadataCheck.addEventListener(eventType, saveSettings);
});

// Initial render
renderAll();