'use strict';

// ════════════════════════════════════════════════════════════════════════════
// options.js — Optionsseite
// Resize-Algorithmen werden aus background.js geladen (get-resize-algorithms).
// ════════════════════════════════════════════════════════════════════════════

const PROFILE_REMOVE = 'remove Image';
const PROFILE_NOTHING = 'do nothing';

const PREDEFINED_TEMPLATES = {
  '1. visually lossless': {
    preserveMeta: true,
    crossConvert: true,
    scale: false,
    antialias: 2.0,
    resizeAlgorithm: 'auto',
    jpegQuality: 90,
    chromaSubsampling: '444',
    maxColors: 256,
    minQuality: 75,
    maxQuality: 100,
    dithering: 0.5,
    speed: 1,
    oxipngAlpha: true,
    oxipngLevel: 4,
  },
  '2. quality optimized': {
    preserveMeta: true,
    crossConvert: true,
    scale: false,
    antialias: 2.0,
    resizeAlgorithm: 'auto',
    jpegQuality: 83,
    chromaSubsampling: '444',
    maxColors: 256,
    minQuality: 60,
    maxQuality: 85,
    dithering: 0.5,
    speed: 1,
    oxipngAlpha: true,
    oxipngLevel: 4,
  },
  '3. size optimized': {
    preserveMeta: true,
    crossConvert: true,
    scale: true,
    antialias: 1.5,
    resizeAlgorithm: 'auto',
    jpegQuality: 76,
    chromaSubsampling: '420',
    maxColors: 256,
    minQuality: 40,
    maxQuality: 65,
    dithering: 0.5,
    speed: 1,
    oxipngAlpha: true,
    oxipngLevel: 4,
  },
  '4. pedantic': {
    preserveMeta: false,
    crossConvert: true,
    scale: true,
    antialias: 1.3,
    resizeAlgorithm: 'auto',
    jpegQuality: 70,
    chromaSubsampling: '420',
    maxColors: 128,
    minQuality: 20,
    maxQuality: 45,
    dithering: 0.5,
    speed: 1,
    oxipngAlpha: true,
    oxipngLevel: 5,
  },
};

const PROTECTED_PROFILES = new Set([
  PROFILE_REMOVE,
  PROFILE_NOTHING,
  ...Object.keys(PREDEFINED_TEMPLATES),
]);

const DEFAULT_TEMPLATE = {
  preserveMeta: true,
  crossConvert: true,
  scale: false,
  antialias: 1.0,
  resizeAlgorithm: 'auto',
  jpegQuality: 85,
  chromaSubsampling: '444',
  maxColors: 256,
  minQuality: 65,
  maxQuality: 85,
  dithering: 0.5,
  speed: 1,
  oxipngLevel: 2,
  oxipngAlpha: true,
};

const DEFAULT_SETTINGS = {
  sendMode: 'ask',
  minFileSize: 1,
  minSavingsPercent: 10,
  replaceText: 'Image removed',
  attachProfile: '2. quality optimized',
  inlineProfile: '2. quality optimized',
  quoteProfile: '3. size optimized',
  precalc: true,
  workerPoolSize: 1,
  convertWebp: false,
  convertGif: true,
  convertBmp: true,
  templates: {},
  excludedHashes: [],
};

const TEMPLATE_FIELDS = [
  { id: 'preserveMeta', type: 'checkbox' },
  { id: 'crossConvert', type: 'checkbox' },
  { id: 'antialias', type: 'range', integer: false, min: 1.0, max: 2.0 },
  { id: 'scale', type: 'checkbox' },
  { id: 'resizeAlgorithm', type: 'select' },
  { id: 'jpegQuality', type: 'range', integer: true, min: 1, max: 100 },
  { id: 'chromaSubsampling', type: 'select' },
  { id: 'maxColors', type: 'range', integer: true, min: 2, max: 256 },
  { id: 'minQuality', type: 'range', integer: true, min: 0, max: 100 },
  { id: 'maxQuality', type: 'range', integer: true, min: 0, max: 100 },
  { id: 'dithering', type: 'range', integer: false, min: 0, max: 1 },
  { id: 'speed', type: 'range', integer: true, min: 1, max: 10 },
  { id: 'oxipngAlpha', type: 'checkbox' },
  { id: 'oxipngLevel', type: 'range', integer: true, min: 0, max: 6 },
];

let settings = { ...DEFAULT_SETTINGS };
let currentTemplateName = '2. quality optimized';

function getTemplate(name) {
  if (PREDEFINED_TEMPLATES[name]) return PREDEFINED_TEMPLATES[name];
  return settings.templates?.[name] || DEFAULT_TEMPLATE;
}

function applyI18n() {
  document.querySelectorAll('[data-i18n]').forEach((el) => {
    const msg = browser.i18n.getMessage(el.getAttribute('data-i18n'));
    if (msg) el.textContent = msg;
  });
  document.querySelectorAll('[data-i18n-placeholder]').forEach((el) => {
    const msg = browser.i18n.getMessage(el.getAttribute('data-i18n-placeholder'));
    if (msg) el.placeholder = msg;
  });
}

function showSaved() {
  const saved = document.getElementById('saved');
  saved.classList.add('show');
  setTimeout(() => saved.classList.remove('show'), 1500);
}

function saveSettings() {
  browser.storage.local.set({ settings });
  showSaved();
}

function getProfileNames() {
  return [PROFILE_REMOVE, PROFILE_NOTHING, ...Object.keys(PREDEFINED_TEMPLATES), ...Object.keys(settings.templates)];
}

function getTemplateNames() {
  return [...Object.keys(PREDEFINED_TEMPLATES), ...Object.keys(settings.templates)].sort();
}

function populateProfileDropdowns() {
  const profileNames = getProfileNames();
  const templateNames = getTemplateNames();

  for (const selectId of ['attachProfile', 'inlineProfile', 'quoteProfile']) {
    const sel = document.getElementById(selectId);
    const current = sel.value;
    sel.innerHTML = '';
    for (const name of profileNames) {
      const opt = document.createElement('option');
      opt.value = name;
      opt.textContent = name;
      sel.appendChild(opt);
    }
    if (profileNames.includes(current)) sel.value = current;
  }

  const tsSel = document.getElementById('templateSelect');
  const tsCurrent = tsSel.value;
  tsSel.innerHTML = '';
  for (const name of templateNames) {
    const opt = document.createElement('option');
    opt.value = name;
    opt.textContent = name;
    tsSel.appendChild(opt);
  }
  if (templateNames.includes(tsCurrent)) tsSel.value = tsCurrent;
}

function loadTemplateIntoEditor(name) {
  currentTemplateName = name;

  const t = getTemplate(name);
  document.getElementById('templateSelect').value = name;

  for (const f of TEMPLATE_FIELDS) {
    const el = document.getElementById('t_' + f.id);
    if (!el) continue;
    if (f.type === 'checkbox') {
      el.checked = !!t[f.id];
    } else {
      el.value = t[f.id] !== undefined ? t[f.id] : '';
    }
    const numEl = document.getElementById('t_' + f.id + 'Num');
    if (numEl) numEl.value = el.value;
  }

  const nameInput = document.getElementById('templateName');
  const deleteBtn = document.getElementById('btnDeleteTemplate');

  if (PROTECTED_PROFILES.has(name)) {
    nameInput.value = '';
    nameInput.placeholder = browser.i18n.getMessage('placeholder_templateName');
    deleteBtn.disabled = true;
  } else {
    nameInput.value = name;
    deleteBtn.disabled = false;
  }

  updateSaveAsButton();
}

function readTemplateFromEditor() {
  const t = {};
  for (const f of TEMPLATE_FIELDS) {
    const el = document.getElementById('t_' + f.id);
    if (!el) continue;
    if (f.type === 'checkbox') {
      t[f.id] = el.checked;
    } else if (f.type === 'select') {
      t[f.id] = el.value;
    } else if (f.integer) {
      t[f.id] = parseInt(el.value, 10);
    } else {
      t[f.id] = parseFloat(el.value);
    }
  }
  return t;
}

function updateSaveAsButton() {
  const name = document.getElementById('templateName').value.trim();
  const btn = document.getElementById('btnSaveAs');
  btn.disabled = !name || PROTECTED_PROFILES.has(name);
}

function onTemplateSelectChange() {
  loadTemplateIntoEditor(document.getElementById('templateSelect').value);
}

function onProfileChange() {
  settings.attachProfile = document.getElementById('attachProfile').value;
  settings.inlineProfile = document.getElementById('inlineProfile').value;
  settings.quoteProfile = document.getElementById('quoteProfile').value;
  saveSettings();
}

function saveAsTemplate() {
  const name = document.getElementById('templateName').value.trim();
  if (!name || PROTECTED_PROFILES.has(name)) return;

  settings.templates[name] = readTemplateFromEditor();
  currentTemplateName = name;

  populateProfileDropdowns();
  document.getElementById('templateSelect').value = name;
  document.getElementById('btnDeleteTemplate').disabled = false;
  saveSettings();
}

function deleteTemplate() {
  if (PROTECTED_PROFILES.has(currentTemplateName)) return;
  delete settings.templates[currentTemplateName];

  if (settings.attachProfile === currentTemplateName) settings.attachProfile = '2. quality optimized';
  if (settings.inlineProfile === currentTemplateName) settings.inlineProfile = '2. quality optimized';
  if (settings.quoteProfile === currentTemplateName) settings.quoteProfile = '3. size optimized';

  document.getElementById('attachProfile').value = '2. quality optimized';
  document.getElementById('inlineProfile').value = '2. quality optimized';
  document.getElementById('quoteProfile').value = '3. size optimized';

  populateProfileDropdowns();
  loadTemplateIntoEditor('2. quality optimized');
  saveSettings();
}

function syncRangeToNum(id) {
  const range = document.getElementById('t_' + id);
  const num = document.getElementById('t_' + id + 'Num');
  if (range && num) num.value = range.value;
}

function syncNumToRange(id) {
  const range = document.getElementById('t_' + id);
  const num = document.getElementById('t_' + id + 'Num');
  if (!range || !num) return;
  let v = parseFloat(num.value);
  if (isNaN(v)) return;
  const min = parseFloat(range.min);
  const max = parseFloat(range.max);
  v = Math.max(min, Math.min(max, v));
  range.value = v;
}

function updateExcludedCount() {
  const count = (settings.excludedHashes || []).length;
  const el = document.getElementById('excludedCount');
  if (el) el.textContent = count;
  const btn = document.getElementById('btnClearExclusions');
  if (btn) btn.disabled = count === 0;
}

// ── Template Export ──────────────────────────────────────────────────────────
function exportTemplates() {
  const templates = settings.templates || {};
  const count = Object.keys(templates).length;

  if (count === 0) {
    alert(browser.i18n.getMessage('alert_noProfilesToExport'));
    return;
  }

  const data = {
    format: 'PPP-Templates',
    version: 1,
    exportedAt: new Date().toISOString(),
    templates,
  };

  const json = JSON.stringify(data, null, 2);
  const blob = new Blob([json], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const date = new Date().toISOString().slice(0, 10);
  const filename = `ppp-profiles-${date}.json`;

  if (browser.downloads && browser.downloads.download) {
    browser.downloads.download({
      url,
      filename,
      saveAs: true,
    }).then((downloadId) => {
      const listener = (delta) => {
        if (delta.id === downloadId && delta.state &&
            (delta.state.current === 'complete' || delta.state.current === 'interrupted')) {
          URL.revokeObjectURL(url);
          browser.downloads.onChanged.removeListener(listener);
        }
      };
      browser.downloads.onChanged.addListener(listener);
    }).catch((err) => {
      console.error('[PPP] Export-Fehler:', err);
      URL.revokeObjectURL(url);
    });
  } else {
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  }
}

// ── Template Import ──────────────────────────────────────────────────────────
function importTemplates(file) {
  const reader = new FileReader();

  reader.onload = async (e) => {
    try {
      const raw = JSON.parse(e.target.result);
      let templates;

      if (raw && raw.format === 'PPP-Templates' && raw.templates && typeof raw.templates === 'object') {
        templates = raw.templates;
      } else if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
        templates = raw;
      } else {
        alert(browser.i18n.getMessage('alert_invalidFileFormat'));
        return;
      }

      let imported = 0;
      let overwritten = 0;
      let skipped = 0;
      const skippedNames = [];

      for (const [name, template] of Object.entries(templates)) {
        const trimmedName = name.trim();
        if (!trimmedName) { skipped++; continue; }

        if (PROTECTED_PROFILES.has(trimmedName)) {
          skipped++;
          skippedNames.push(trimmedName);
          continue;
        }

        if (typeof template !== 'object' || Array.isArray(template)) {
          skipped++;
          continue;
        }

        const merged = { ...DEFAULT_TEMPLATE };
        for (const f of TEMPLATE_FIELDS) {
          if (template[f.id] !== undefined) {
            merged[f.id] = template[f.id];
          }
        }

        if (settings.templates[trimmedName]) overwritten++;

        settings.templates[trimmedName] = merged;
        imported++;
      }

      if (imported === 0) {
        alert(browser.i18n.getMessage('alert_noProfilesImported',
          (skipped > 0 ? `${skipped} ${browser.i18n.getMessage('text_skipped')}` : '')));
        return;
      }

      saveSettings();
      populateProfileDropdowns();
      loadTemplateIntoEditor('2. quality optimized');

      let msg = browser.i18n.getMessage('alert_profilesImported', String(imported));
      if (overwritten > 0) msg += ` (${overwritten} ${browser.i18n.getMessage('text_overwritten')})`;
      if (skipped > 0) {
        msg += `, ${skipped} ${browser.i18n.getMessage('text_skipped')}`;
        if (skippedNames.length > 0) msg += `: ${skippedNames.join(', ')}`;
      }
      msg += '.';
      alert(msg);
    } catch (err) {
      alert(browser.i18n.getMessage('alert_importError', err.message));
    }
  };

  reader.onerror = () => {
    alert(browser.i18n.getMessage('alert_fileReadError'));
  };

  reader.readAsText(file);
}

async function load() {
  const result = await browser.storage.local.get('settings');
  settings = JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
  if (result.settings) {
    Object.assign(settings, result.settings);
    if (!settings.templates) settings.templates = {};
    if (!settings.excludedHashes) settings.excludedHashes = [];
    if (settings.quoteMode === 'replace-boxes') {
      settings.quoteProfile = PROFILE_REMOVE;
      delete settings.quoteMode;
    }
    delete settings.quoteMode;
  }

  // Resize-Algorithmen aus background.js laden (vor loadTemplateIntoEditor!)
  const algorithms = await browser.runtime.sendMessage({ type: 'get-resize-algorithms' });
  const resizeSel = document.getElementById('t_resizeAlgorithm');
  resizeSel.innerHTML = '';
  for (const { value, label } of algorithms) {
    const opt = document.createElement('option');
    opt.value = value;
    opt.textContent = label;
    resizeSel.appendChild(opt);
  }

  document.getElementById('minFileSize').value = settings.minFileSize;
  document.getElementById('minSavingsPercent').value = settings.minSavingsPercent;
  document.getElementById('replaceText').value = settings.replaceText;
  document.getElementById('precalc').checked = settings.precalc ?? true;
  document.getElementById('workerPoolSize').value = settings.workerPoolSize ?? 1;
  document.getElementById('convertWebp').checked = settings.convertWebp ?? false;
  document.getElementById('convertGif').checked = settings.convertGif ?? true;
  document.getElementById('convertBmp').checked = settings.convertBmp ?? true;
  document.querySelectorAll('input[name="sendMode"]').forEach((r) => r.checked = r.value === (settings.sendMode || 'ask'));

  populateProfileDropdowns();

  document.getElementById('attachProfile').value = settings.attachProfile || '2. quality optimized';
  document.getElementById('inlineProfile').value = settings.inlineProfile || '2. quality optimized';
  document.getElementById('quoteProfile').value = settings.quoteProfile || '2. quality optimized';

  updateExcludedCount();

  loadTemplateIntoEditor('2. quality optimized');
}

function resetDefaults() {
  // Selbst angelegte Profile erhalten — nur allgemeine Einstellungen zurücksetzen.
  // excludedHashes wird bewusst gelöscht (neue leere Liste).
  const userTemplates = settings.templates;
  settings = JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
  settings.templates = userTemplates;
  browser.storage.local.set({ settings });
  load();
  showSaved();
}

function clearExclusions() {
  settings.excludedHashes = [];
  saveSettings();
  updateExcludedCount();
}

applyI18n();

document.getElementById('minFileSize').addEventListener('change', () => {
  settings.minFileSize = parseInt(document.getElementById('minFileSize').value, 10) || 0;
  saveSettings();
});

document.getElementById('minSavingsPercent').addEventListener('change', () => {
  settings.minSavingsPercent = parseInt(document.getElementById('minSavingsPercent').value, 10) || 0;
  saveSettings();
});

document.getElementById('replaceText').addEventListener('change', () => {
  settings.replaceText = document.getElementById('replaceText').value;
  saveSettings();
});

for (const id of ['precalc', 'convertWebp', 'convertGif', 'convertBmp']) {
  document.getElementById(id).addEventListener('change', () => {
    settings[id] = document.getElementById(id).checked;
    saveSettings();
  });
}

document.getElementById('workerPoolSize').addEventListener('change', () => {
  const v = parseInt(document.getElementById('workerPoolSize').value, 10);
  settings.workerPoolSize = Math.min(8, Math.max(1, isNaN(v) ? 1 : v));
  document.getElementById('workerPoolSize').value = settings.workerPoolSize;
  saveSettings();
});

document.querySelectorAll('input[name="sendMode"]').forEach((r) =>
  r.addEventListener('change', () => {
    const checked = document.querySelector('input[name="sendMode"]:checked');
    settings.sendMode = checked ? checked.value : 'ask';
    saveSettings();
  })
);

document.getElementById('attachProfile').addEventListener('change', onProfileChange);
document.getElementById('inlineProfile').addEventListener('change', onProfileChange);
document.getElementById('quoteProfile').addEventListener('change', onProfileChange);

document.getElementById('templateSelect').addEventListener('change', onTemplateSelectChange);
document.getElementById('btnDeleteTemplate').addEventListener('click', deleteTemplate);
document.getElementById('btnSaveAs').addEventListener('click', saveAsTemplate);
document.getElementById('templateName').addEventListener('input', updateSaveAsButton);

for (const f of TEMPLATE_FIELDS) {
  if (f.type !== 'range') continue;
  const rangeEl = document.getElementById('t_' + f.id);
  const numEl = document.getElementById('t_' + f.id + 'Num');
  if (!rangeEl || !numEl) continue;
  rangeEl.addEventListener('input', () => syncRangeToNum(f.id));
  numEl.addEventListener('input', () => syncNumToRange(f.id));
  numEl.addEventListener('change', () => syncNumToRange(f.id));
}

document.getElementById('btnReset').addEventListener('click', resetDefaults);
document.getElementById('btnClearExclusions').addEventListener('click', clearExclusions);

// ── Template Export/Import Event-Listener ────────────────────────────────────
document.getElementById('btnExportTemplates').addEventListener('click', exportTemplates);

document.getElementById('btnImportTemplates').addEventListener('click', () => {
  document.getElementById('importFileInput').click();
});

document.getElementById('importFileInput').addEventListener('change', (e) => {
  const file = e.target.files[0];
  if (file) importTemplates(file);
  e.target.value = ''; // Reset, damit dieselbe Datei erneut gewählt werden kann
});

load();
