'use strict';

// ════════════════════════════════════════════════════════════════════════════
// popup.js — Toolbar-Popup für das Compose-Fenster
// Nutzt shared.js für alle gemeinsamen Funktionen.
// Profile werden ausschließlich aus background.js (get-template-names) geladen.
// ════════════════════════════════════════════════════════════════════════════

let composeTabId = null;

PPP_SHARED.images = [];
PPP_SHARED.profiles = [];
PPP_SHARED.defaults = {};
PPP_SHARED.cardElements = new Map();
PPP_SHARED.profileSettings = {};

function showError(msg) {
  PPP_SHARED.$('error').textContent = msg;
  PPP_SHARED.$('error').style.display = 'block';
  PPP_SHARED.$('content').style.display = 'none';
}

function collectState() {
  const state = {};
  const sm = document.querySelector('input[name="sendMode"]:checked');
  state.sendMode = sm ? sm.value : 'ask';
  state.attachProfile = attachProfile.value;
  state.inlineProfile = inlineProfile.value;
  state.quoteProfile = quoteProfile.value;
  state.resizeAlgorithm = resizeAlgorithm.value;
  return state;
}

function saveState() {
  if (!composeTabId) return;
  browser.runtime.sendMessage({
    type: 'set-tab-state',
    tabId: composeTabId,
    state: collectState(),
  });
}

document.querySelectorAll('input[name="sendMode"]').forEach((r) =>
  r.addEventListener('change', saveState)
);

['attachProfile', 'inlineProfile', 'quoteProfile'].forEach((id) => {
  const el = document.getElementById(id);
  el.addEventListener('change', () => {
    saveState();
    const category = id.replace('Profile', '');
    PPP_SHARED.syncCardProfiles(category, el.value);
  });
});

document.getElementById('resizeAlgorithm').addEventListener('change', saveState);

PPP_SHARED.$('btn-apply-all').addEventListener('click', async () => {
  if (!composeTabId) return;
  saveState();
  await PPP_SHARED.compressAll();
  setTimeout(() => window.close(), 600);
});

PPP_SHARED.$('btn-settings').addEventListener('click', () => {
  browser.runtime.openOptionsPage();
});

async function init() {
  PPP_SHARED.showLoading(browser.i18n.getMessage('loading_imagesLoading'));

  try {
    // FIX (Multi-Fenster): Das Popup gehört zu genau einem Compose-Fenster.
    // Die tabId muss aus dem EIGENEN Fenster kommen, nicht aus einer globalen
    // Suche: Bei mehreren Compose-Fenstern ist 'active' in JEDEM Fenster true,
    // find() lieferte daher immer das zuerst geöffnete Fenster.
    const ownTab = await browser.tabs.getCurrent();
    if (ownTab && ownTab.id != null && ownTab.type === 'messageCompose') {
      composeTabId = ownTab.id;
    } else {
      // Fallback: aktiver Tab des Fensters, in dem dieses Popup läuft.
      const ownWin = await browser.windows.getCurrent();
      const winTabs = await browser.tabs.query({ windowId: ownWin.id, active: true });
      const composeTab = winTabs.find((t) => t.type === 'messageCompose') || winTabs[0];
      if (composeTab && composeTab.id != null) composeTabId = composeTab.id;
    }
    if (composeTabId == null) {
      showError(browser.i18n.getMessage('error_noComposeWindow'));
      return;
    }

    PPP_SHARED.tabId = composeTabId;

    const stateResp = await browser.runtime.sendMessage({ type: 'get-tab-state', tabId: composeTabId });
    const state = stateResp.state;

    const names = await browser.runtime.sendMessage({ type: 'get-template-names' });
    PPP_SHARED.profiles = names || [];
    const fallbackProfile = '2. quality optimized';

    PPP_SHARED.defaults = {
      attach: state.attachProfile || fallbackProfile,
      inline: state.inlineProfile || fallbackProfile,
      quote: state.quoteProfile || fallbackProfile,
    };

    PPP_SHARED.populateProfileDropdowns(PPP_SHARED.profiles, PPP_SHARED.defaults);

    const algorithms = await browser.runtime.sendMessage({ type: 'get-resize-algorithms' });
    PPP_SHARED.resizeAlgorithms = algorithms;
    PPP_SHARED.populateResizeAlgorithms(
      document.getElementById('resizeAlgorithm'),
      state.resizeAlgorithm
    );

    document.querySelectorAll('input[name="sendMode"]').forEach((r) => r.checked = r.value === (state.sendMode || 'ask'));

    const result = await browser.runtime.sendMessage({ type: 'dialog-init', tabId: composeTabId });

    // ── Ausnahme einblenden: Button zeigen, wenn excluded-Bilder existieren ──
    if (result && result.excludedCount > 0) {
      PPP_SHARED.setupExcludedButton(result.excludedCount, document.getElementById('fs-verhalten'));
    }

    if (!result || !result.images || result.images.length === 0) {
      PPP_SHARED.$('empty-state').style.display = 'block';
      return;
    }

    PPP_SHARED.images = result.images;
    PPP_SHARED.profileSettings = result.profileSettings || {};

    const list = PPP_SHARED.$('image-list');
    list.innerHTML = '';

    for (const img of PPP_SHARED.images) {
      const card = PPP_SHARED.renderCard(img);
      list.appendChild(card);
      PPP_SHARED.cardElements.set(img.id, card);
    }

    PPP_SHARED.updateSummary();
  } catch (err) {
    console.error('[PPP] Popup-Init-Fehler:', err);
    showError(err.message || String(err));
  } finally {
    PPP_SHARED.hideLoading();
  }
}

init();
