/**
 * Gesamt-Backup: Arbeitseinstellungen (Mic) + Chili-Stimmung.
 * Logs (Diagnose / Diktat) werden bewusst nicht exportiert.
 */
(function initChillicollectivoUnifiedBackup(global) {
  const root = global || (typeof globalThis !== 'undefined' ? globalThis : self);

  const UNIFIED_VERSION = 1;
  const STIMMUNG_KEY = 'chillicollectivoChiliStimmungSettings';
  const STIMMUNG_LEGACY_KEY = 'chillicollectivoMuppetSettings';
  const STIMMUNG_ENABLED_KEY = 'chillicollectivoChiliStimmungEnabled';
  const VOICE_SETTINGS_KEY = 'chillicollectivoVoiceSettings';
  const VOICE_HOTKEY_KEY = 'chillicollectivoVoiceHotkey';
  const PROFILE_CMD_KEY = 'chillicollectivoProfileCommandConfig';
  const FAB_POS_KEY = 'chillicollectivoVoiceFabPos';
  const PREVIEW_SIZE_KEY = 'chillicollectivoVoicePreviewSize';
  const PREVIEW_POS_KEY = 'chillicollectivoVoicePreviewPos';
  const OUT_COUNTER_KEY = 'chillicollectivoOutCounter';
  const OUT_COUNTER_TOTAL_KEY = 'chillicollectivoOutCounterTotal';
  const OUT_TARGET_KEY = 'chillicollectivoOutTarget';
  const OUT_COUNTER_ENABLED_KEY = 'chillicollectivoOutCounterEnabled';

  const STORAGE_KEYS = [
    STIMMUNG_KEY,
    STIMMUNG_LEGACY_KEY,
    STIMMUNG_ENABLED_KEY,
    VOICE_SETTINGS_KEY,
    VOICE_HOTKEY_KEY,
    PROFILE_CMD_KEY,
    FAB_POS_KEY,
    PREVIEW_SIZE_KEY,
    PREVIEW_POS_KEY,
    OUT_COUNTER_KEY,
    OUT_COUNTER_TOTAL_KEY,
    OUT_TARGET_KEY,
    OUT_COUNTER_ENABLED_KEY,
  ];

  function storageGet(keys) {
    return new Promise((resolve) => {
      if (!chrome?.storage?.local) {
        resolve({});
        return;
      }
      chrome.storage.local.get(keys, (data) => resolve(data || {}));
    });
  }

  function storageSet(payload) {
    return new Promise((resolve) => {
      if (!chrome?.storage?.local) {
        resolve();
        return;
      }
      chrome.storage.local.set(payload, () => resolve());
    });
  }

  function downloadTextFile(filename, content) {
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1500);
  }

  function extractBackupJson(text) {
    const value = String(text || '').trim();
    if (!value) throw new Error('Die Datei ist leer.');

    try {
      return JSON.parse(value);
    } catch (_) {}

    const marker = 'MASCHINENLESBARES BACKUP';
    const markerIndex = value.indexOf(marker);
    const searchArea = markerIndex >= 0 ? value.slice(markerIndex + marker.length) : value;
    const firstBrace = searchArea.indexOf('{');
    if (firstBrace < 0) throw new Error('Kein JSON Block im Backup gefunden.');

    let depth = 0;
    let inString = false;
    let escaped = false;

    for (let i = firstBrace; i < searchArea.length; i += 1) {
      const ch = searchArea[i];
      if (inString) {
        if (escaped) escaped = false;
        else if (ch === '\\') escaped = true;
        else if (ch === '"') inString = false;
        continue;
      }
      if (ch === '"') {
        inString = true;
        continue;
      }
      if (ch === '{') depth += 1;
      if (ch === '}') {
        depth -= 1;
        if (depth === 0) return JSON.parse(searchArea.slice(firstBrace, i + 1));
      }
    }
    throw new Error('JSON Block im Backup unvollständig.');
  }

  function isLegacyChiliStimmungOnly(raw) {
    if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return false;
    if (raw.unifiedBackupVersion || raw.arbeitseinstellungen) return false;
    return Array.isArray(raw.profiles) || raw.triggerMode != null || raw.fallbackEmojis != null;
  }

  function normalizeUnifiedPayload(raw, options = {}) {
    if (!raw || typeof raw !== 'object') {
      throw new Error('Das Backup hat kein gültiges Format.');
    }

    if (raw.unifiedBackupVersion || raw.arbeitseinstellungen || raw.chiliStimmung) {
      const stimmungRaw = raw.chiliStimmung || {};
      const normalizeStimmung = options.normalizeChiliStimmung
        || root.chillicollectivoNormalizeChiliStimmungBackup;
      const chiliStimmung = typeof normalizeStimmung === 'function'
        ? normalizeStimmung(stimmungRaw)
        : stimmungRaw;
      const arbeit = raw.arbeitseinstellungen && typeof raw.arbeitseinstellungen === 'object'
        ? raw.arbeitseinstellungen
        : {};
      return {
        unifiedBackupVersion: UNIFIED_VERSION,
        chiliStimmung,
        chiliStimmungEnabled: raw.chiliStimmungEnabled != null
          ? !!raw.chiliStimmungEnabled
          : !!chiliStimmung.enabled,
        arbeitseinstellungen: {
          voiceSettings: arbeit.voiceSettings && typeof arbeit.voiceSettings === 'object'
            ? arbeit.voiceSettings
            : null,
          voiceHotkey: arbeit.voiceHotkey ?? null,
          profileCommandConfig: arbeit.profileCommandConfig && typeof arbeit.profileCommandConfig === 'object'
            ? arbeit.profileCommandConfig
            : null,
          voiceFabPos: arbeit.voiceFabPos ?? null,
          voicePreviewSize: arbeit.voicePreviewSize ?? null,
          voicePreviewPos: arbeit.voicePreviewPos ?? null,
          outCounter: Number.isFinite(Number(arbeit.outCounter)) ? Number(arbeit.outCounter) : null,
          outCounterTotal: Number.isFinite(Number(arbeit.outCounterTotal)) ? Number(arbeit.outCounterTotal) : null,
          outTarget: arbeit.outTarget ?? null,
          outCounterEnabled: arbeit.outCounterEnabled == null ? null : !!arbeit.outCounterEnabled,
        },
      };
    }

    if (isLegacyChiliStimmungOnly(raw)) {
      const normalizeStimmung = options.normalizeChiliStimmung
        || root.chillicollectivoNormalizeChiliStimmungBackup;
      const chiliStimmung = typeof normalizeStimmung === 'function'
        ? normalizeStimmung(raw)
        : raw;
      return {
        unifiedBackupVersion: UNIFIED_VERSION,
        chiliStimmung,
        chiliStimmungEnabled: !!chiliStimmung.enabled,
        arbeitseinstellungen: {},
      };
    }

    throw new Error('Backup-Format nicht erkannt (weder Gesamt- noch Chili-Stimmung-Backup).');
  }

  async function collectUnifiedBackup(options = {}) {
    const stored = await storageGet(STORAGE_KEYS);
    const voiceSettings = stored[VOICE_SETTINGS_KEY] || {};
    const voiceHotkey = stored[VOICE_HOTKEY_KEY] ?? voiceSettings.hotkey ?? null;
    const chiliStimmung = options.chiliStimmungOverride
      || stored[STIMMUNG_KEY]
      || stored[STIMMUNG_LEGACY_KEY]
      || null;

    return {
      unifiedBackupVersion: UNIFIED_VERSION,
      createdAt: new Date().toISOString(),
      extensionVersion: chrome?.runtime?.getManifest?.().version || '',
      chiliStimmungEnabled: options.chiliStimmungEnabledOverride != null
        ? !!options.chiliStimmungEnabledOverride
        : stored[STIMMUNG_ENABLED_KEY] === true || !!chiliStimmung?.enabled,
      chiliStimmung,
      arbeitseinstellungen: {
        voiceSettings,
        voiceHotkey,
        profileCommandConfig: stored[PROFILE_CMD_KEY] || null,
        voiceFabPos: stored[FAB_POS_KEY] || null,
        voicePreviewSize: stored[PREVIEW_SIZE_KEY] || null,
        voicePreviewPos: stored[PREVIEW_POS_KEY] || null,
        outCounter: stored[OUT_COUNTER_KEY] ?? null,
        outCounterTotal: stored[OUT_COUNTER_TOTAL_KEY] ?? null,
        outTarget: stored[OUT_TARGET_KEY] ?? null,
        outCounterEnabled: stored[OUT_COUNTER_ENABLED_KEY] ?? null,
      },
    };
  }

  function formatArbeitSection(arbeit = {}, voiceSettings = {}) {
    const vs = arbeit.voiceSettings || voiceSettings || {};
    const lines = [];
    lines.push('=== ARBEITSEINSTELLUNGEN (Mic) ===');
    lines.push(`Live-Vorschau: ${vs.previewEnabled !== false ? 'Ja' : 'Nein'}`);
    lines.push(`Vorschau verschiebbar: ${vs.previewMovable ? 'Ja' : 'Nein'}`);
    lines.push(`Vorschau fixiert: ${vs.previewPinned ? 'Ja' : 'Nein'}`);
    lines.push(`Vorschau+Enter: ${vs.previewEnterToInsert !== false ? 'Ja' : 'Nein'}`);
    lines.push(`Vorschau+Klick: ${vs.previewClickToInsert !== false ? 'Ja' : 'Nein'}`);
    lines.push(`PP auto nach Sprechen: ${vs.ppAutoInsert ? 'Ja' : 'Nein'}`);
    lines.push(`Chili-Sprüche: ${vs.micTipsEnabled ? 'Ja' : 'Nein'}`);
    lines.push(`Vorschau-Farbe: ${vs.previewColor || '(Standard)'}`);
    lines.push(`Vorschau-Schrift: ${vs.previewFontWeight || 'extrabold'} / ${vs.previewFontSize || 22}px`);
    lines.push(`Tool-Farbe: ${vs.toolColor || '(Standard)'}`);
    lines.push(`Smileys/Korrekturen: in voiceSettings (autoCorrectionsRaw / voiceSmileysRaw)`);
    lines.push(`Profilpflege-Befehle: ${arbeit.profileCommandConfig ? 'Ja' : 'Nein'}`);
    lines.push('');
    return lines.join('\n');
  }

  function formatUnifiedBackupText(payload) {
    const lines = [];
    const now = new Date(payload.createdAt || Date.now());
    lines.push('ChiliColectivo Gesamt-Backup');
    lines.push(`Erstellt am: ${now.toLocaleString('de-DE')}`);
    lines.push('=== SICHERHEITSHINWEIS ===');
    lines.push('Diese Datei enthält Einstellungen im Klartext (Korrekturen, Smileys, Hotkeys).');
    lines.push('Nicht weitergeben oder in Cloud/Chat hochladen. Lizenzschlüssel ist nicht enthalten.');
    lines.push('');
    lines.push(`Extension: ${payload.extensionVersion || 'unbekannt'}`);
    lines.push('Enthält: Arbeitseinstellungen + Chili-Stimmung');
    lines.push('Nicht enthalten: Diagnose-Log, Diktat-Log');
    lines.push('');
    lines.push(formatArbeitSection(payload.arbeitseinstellungen));
    if (typeof root.chillicollectivoFormatChiliStimmungBackupText === 'function' && payload.chiliStimmung) {
      const stimmungText = root.chillicollectivoFormatChiliStimmungBackupText(payload.chiliStimmung);
      const stimmungBody = String(stimmungText || '')
        .split('\n')
        .slice(4)
        .filter((line) => line !== 'MASCHINENLESBARES BACKUP'
          && !line.startsWith('Die Import Funktion')
          && line.trim() !== '');
      const jsonStart = stimmungBody.findIndex((line) => line.trim().startsWith('{'));
      const humanPart = jsonStart >= 0 ? stimmungBody.slice(0, jsonStart) : stimmungBody;
      lines.push('=== CHILI-STIMMUNG ===');
      lines.push(`Chili-Stimmung aktiv: ${payload.chiliStimmungEnabled ? 'Ja' : 'Nein'}`);
      lines.push(...humanPart);
    } else if (payload.chiliStimmung) {
      lines.push('=== CHILI-STIMMUNG ===');
      lines.push(`Aktiv: ${payload.chiliStimmungEnabled ? 'Ja' : 'Nein'}`);
      lines.push(`Profile: ${(payload.chiliStimmung.profiles || []).length}`);
      lines.push('');
    }
    lines.push('MASCHINENLESBARES BACKUP');
    lines.push('Die Import-Funktion liest diesen JSON-Block automatisch.');
    lines.push(JSON.stringify(payload, null, 2));
    lines.push('');
    return lines.join('\n');
  }

  async function applyUnifiedBackup(payload, options = {}) {
    const normalized = normalizeUnifiedPayload(payload, options);
    const storagePayload = {};

    if (normalized.chiliStimmung) {
      storagePayload[STIMMUNG_KEY] = normalized.chiliStimmung;
      storagePayload[STIMMUNG_ENABLED_KEY] = normalized.chiliStimmungEnabled;
    }

    const arbeit = normalized.arbeitseinstellungen || {};
    if (arbeit.voiceSettings) {
      const voiceSettings = { ...arbeit.voiceSettings };
      if (arbeit.voiceHotkey !== undefined) voiceSettings.hotkey = arbeit.voiceHotkey;
      storagePayload[VOICE_SETTINGS_KEY] = voiceSettings;
      storagePayload[VOICE_HOTKEY_KEY] = arbeit.voiceHotkey ?? voiceSettings.hotkey ?? null;
    } else if (arbeit.voiceHotkey !== undefined) {
      storagePayload[VOICE_HOTKEY_KEY] = arbeit.voiceHotkey;
    }

    if (arbeit.profileCommandConfig) storagePayload[PROFILE_CMD_KEY] = arbeit.profileCommandConfig;
    if (arbeit.voiceFabPos) storagePayload[FAB_POS_KEY] = arbeit.voiceFabPos;
    if (arbeit.voicePreviewSize) storagePayload[PREVIEW_SIZE_KEY] = arbeit.voicePreviewSize;
    if (arbeit.voicePreviewPos) storagePayload[PREVIEW_POS_KEY] = arbeit.voicePreviewPos;
    if (arbeit.outCounter != null) storagePayload[OUT_COUNTER_KEY] = arbeit.outCounter;
    if (arbeit.outCounterTotal != null) storagePayload[OUT_COUNTER_TOTAL_KEY] = arbeit.outCounterTotal;
    if (arbeit.outTarget != null) storagePayload[OUT_TARGET_KEY] = arbeit.outTarget;
    if (arbeit.outCounterEnabled != null) storagePayload[OUT_COUNTER_ENABLED_KEY] = arbeit.outCounterEnabled;

    await storageSet(storagePayload);
    return normalized;
  }

  async function downloadUnifiedBackup(options = {}) {
    const payload = await collectUnifiedBackup(options);
    const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
    downloadTextFile(`ChiliColectivo_Gesamt-Backup_${stamp}.txt`, formatUnifiedBackupText(payload));
    return payload;
  }

  async function importUnifiedBackupFromText(text, options = {}) {
    const raw = extractBackupJson(text);
    const normalized = await applyUnifiedBackup(raw, options);
    return normalized;
  }

  async function importUnifiedBackupFromFile(file, options = {}) {
    const text = await file.text();
    return importUnifiedBackupFromText(text, options);
  }

  root.ChillicollectivoUnifiedBackup = {
    UNIFIED_VERSION,
    collect: collectUnifiedBackup,
    formatText: formatUnifiedBackupText,
    extractJson: extractBackupJson,
    normalize: normalizeUnifiedPayload,
    apply: applyUnifiedBackup,
    download: downloadUnifiedBackup,
    importText: importUnifiedBackupFromText,
    importFile: importUnifiedBackupFromFile,
  };
})(typeof globalThis !== 'undefined' ? globalThis : self);
