/**
 * ChiliColectivo Mic – Web-Portal Sync (2.1.39)
 */
(function (global) {
  const CHILLICOLLECTIVO_WEB_MIC = {
    OPTIONS_BASE: 'http://www.chili-voice.de/portal/62941853/settings.php',
    API_BASE: 'http://www.chili-voice.de/portal/mic-settings/api/',
    PORTAL_API_BASE: 'http://www.chili-voice.de/portal/api/',
    SYNC_ALARM: 'chillicollectivoMicWebSync',
    SYNC_MINUTES: 1,
    PING_MS: 2500,
  };

  function chillicollectivoMainPortalApiUrl(file) {
    return `${CHILLICOLLECTIVO_WEB_MIC.PORTAL_API_BASE}${file}`;
  }

  async function chillicollectivoPingWebMicPortal() {
    const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
    const timer = controller ? setTimeout(() => controller.abort(), CHILLICOLLECTIVO_WEB_MIC.PING_MS) : null;
    try {
      const res = await fetch(`${chillicollectivoMainPortalApiUrl('mic-update.php')}?version=0.0.0`, {
        method: 'GET',
        cache: 'no-store',
        signal: controller?.signal,
      });
      if (timer) clearTimeout(timer);
      if (res.ok) return true;
    } catch (_) {
      if (timer) clearTimeout(timer);
    }

    const legacyController = typeof AbortController !== 'undefined' ? new AbortController() : null;
    const legacyTimer = legacyController ? setTimeout(() => legacyController.abort(), CHILLICOLLECTIVO_WEB_MIC.PING_MS) : null;
    try {
      const res = await fetch(`${CHILLICOLLECTIVO_WEB_MIC.API_BASE}mic-sync.php?deviceId=ping`, {
        method: 'GET',
        cache: 'no-store',
        signal: legacyController?.signal,
      });
      if (legacyTimer) clearTimeout(legacyTimer);
      return res.ok;
    } catch (_) {
      if (legacyTimer) clearTimeout(legacyTimer);
      return false;
    }
  }

  function micEmbeddedOptionsUrl(deviceId, extId, version) {
    const q = new URLSearchParams();
    if (deviceId) q.set('device', deviceId);
    if (extId) q.set('ext', extId);
    if (version) q.set('v', version);
    const suffix = q.toString() ? `?${q.toString()}` : '';
    return chrome.runtime.getURL(`options.html${suffix}`);
  }

  async function chillicollectivoOpenWebMicOptions() {
    const deviceId = await chillicollectivoGetOrCreateDeviceId();
    const extId = typeof chrome !== 'undefined' && chrome.runtime?.id ? chrome.runtime.id : '';
    const version = typeof chillicollectivoGetExtensionVersion === 'function'
      ? chillicollectivoGetExtensionVersion()
      : '0.0.0';

    const embeddedUrl = micEmbeddedOptionsUrl(deviceId, extId, version);
    if (typeof chrome === 'undefined' || !chrome.tabs?.create) {
      return false;
    }

    try {
      await chrome.tabs.create({ url: embeddedUrl, active: true });
      return true;
    } catch (_) {
      return false;
    }
  }

  async function chillicollectivoFetchMainPortalDeviceSettings(deviceId) {
    const licenseKey = typeof chillicollectivoGetStoredLicenseKey === 'function'
      ? await chillicollectivoGetStoredLicenseKey()
      : '';
    const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
    const timer = controller ? setTimeout(() => controller.abort(), 8000) : null;
    try {
      const q = new URLSearchParams({
        deviceId: String(deviceId || ''),
        licenseKey: String(licenseKey || ''),
      });
      const res = await fetch(`${chillicollectivoMainPortalApiUrl('mic-device-settings.php')}?${q}`, {
        method: 'GET',
        cache: 'no-store',
        signal: controller?.signal,
      });
      if (timer) clearTimeout(timer);
      if (!res.ok) return null;
      const data = await res.json().catch(() => ({}));
      return data?.success ? data : null;
    } catch (_) {
      if (timer) clearTimeout(timer);
      return null;
    }
  }

  async function chillicollectivoFetchWebMicSync(deviceId) {
    const api = `${CHILLICOLLECTIVO_WEB_MIC.API_BASE}mic-sync.php?deviceId=${encodeURIComponent(deviceId)}`;
    const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
    const timer = controller ? setTimeout(() => controller.abort(), 8000) : null;
    try {
      const res = await fetch(api, { method: 'GET', cache: 'no-store', signal: controller?.signal });
      if (timer) clearTimeout(timer);
      if (!res.ok) return null;
      const data = await res.json();
      return data?.success ? data : null;
    } catch (_) {
      if (timer) clearTimeout(timer);
      return null;
    }
  }

  async function chillicollectivoActivateLicenseViaWebMicPortal(key, email) {
    const deviceId = await chillicollectivoGetOrCreateDeviceId();
    const extId = typeof chrome !== 'undefined' && chrome.runtime?.id ? chrome.runtime.id : '';
    const version = typeof chillicollectivoGetExtensionVersion === 'function'
      ? chillicollectivoGetExtensionVersion()
      : '';
    const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
    const timer = controller ? setTimeout(() => controller.abort(), 8000) : null;
    try {
      const res = await fetch(`${CHILLICOLLECTIVO_WEB_MIC.API_BASE}mic-license.php`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          key,
          email,
          deviceId,
          extensionId: extId,
          extensionVersion: version,
          doActivate: true,
        }),
        signal: controller?.signal,
      });
      if (timer) clearTimeout(timer);
      if (res.status === 404 || res.status === 410) {
        return { ok: false, unavailable: true, data: null };
      }
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data?.valid) {
        const msg = data?.error || data?.message || null;
        return {
          ok: false,
          unavailable: res.status >= 500,
          error: msg || (res.status >= 500 ? 'Lizenzserver vorübergehend nicht erreichbar.' : null),
          data,
        };
      }
      return { ok: true, data };
    } catch (err) {
      if (timer) clearTimeout(timer);
      return { ok: false, error: err?.message || 'Portal nicht erreichbar' };
    }
  }

  async function chillicollectivoPushLicenseToWebMicPortal(key, email) {
    const result = await chillicollectivoActivateLicenseViaWebMicPortal(key, email);
    return !!result?.ok;
  }

  async function chillicollectivoClearWebMicPortalLicense() {
    const deviceId = await chillicollectivoGetOrCreateDeviceId();
    const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
    const timer = controller ? setTimeout(() => controller.abort(), 8000) : null;
    try {
      const res = await fetch(`${CHILLICOLLECTIVO_WEB_MIC.API_BASE}mic-license.php`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'clear', deviceId }),
        signal: controller?.signal,
      });
      if (timer) clearTimeout(timer);
      return res.ok;
    } catch (_) {
      if (timer) clearTimeout(timer);
      return false;
    }
  }

  async function chillicollectivoPushSettingsToWebMicPortal(settings) {
    if (!settings || typeof settings !== 'object') return false;
    const deviceId = await chillicollectivoGetOrCreateDeviceId();
    const licenseKey = typeof chillicollectivoGetStoredLicenseKey === 'function'
      ? await chillicollectivoGetStoredLicenseKey()
      : '';
    const extensionVersion = typeof chillicollectivoGetExtensionVersion === 'function'
      ? chillicollectivoGetExtensionVersion()
      : '';
    const payload = JSON.stringify({ deviceId, licenseKey, settings, extensionVersion });
    const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
    const timer = controller ? setTimeout(() => controller.abort(), 8000) : null;
    try {
      const mainRes = await fetch(chillicollectivoMainPortalApiUrl('mic-device-settings.php'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: payload,
        signal: controller?.signal,
      });
      if (timer) clearTimeout(timer);
      if (mainRes.ok) {
        const mainData = await mainRes.json().catch(() => ({}));
        if (mainData?.success) return true;
      }
    } catch (_) {
      if (timer) clearTimeout(timer);
    }

    const legacyController = typeof AbortController !== 'undefined' ? new AbortController() : null;
    const legacyTimer = legacyController ? setTimeout(() => legacyController.abort(), 8000) : null;
    try {
      const res = await fetch(`${CHILLICOLLECTIVO_WEB_MIC.API_BASE}mic-settings.php`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: payload,
        signal: legacyController?.signal,
      });
      if (legacyTimer) clearTimeout(legacyTimer);
      if (!res.ok) return false;
      const data = await res.json();
      return !!data?.success;
    } catch (_) {
      if (legacyTimer) clearTimeout(legacyTimer);
      return false;
    }
  }

  async function chillicollectivoApplyRemoteMicLicense(license) {
    const key = CHILLICOLLECTIVO_LICENSE?.STORAGE_KEY || 'chillicollectivoLicense';
    if (!license?.valid) return;
    const now = Date.now();
    const stored = {
      key: license.key || null,
      valid: true,
      validatedAt: Number(license.validatedAt) || now,
      lastError: null,
      email: license.email || null,
      plan: license.plan || 'standard',
      expiresAt: license.expiresAt
        ? chillicollectivoNormalizeExpiryMs(license.expiresAt)
        : null,
      status: license.status || 'active',
      source: license.source || 'portal',
    };
    await chrome.storage.local.set({ [key]: stored });
    if (typeof chillicollectivoSetLicenseForceLocked === 'function') {
      await chillicollectivoSetLicenseForceLocked(false);
    }
    if (typeof chillicollectivoPersistActivatedLicense === 'function') {
      await chillicollectivoPersistActivatedLicense(stored);
    }
  }

  async function chillicollectivoApplyRemoteMicSettings(settings, voiceManager) {
    if (!settings || typeof settings !== 'object' || !Object.keys(settings).length) return;
    const patch = { ...settings };
    const effects = {};
    if (patch.previewEnabled !== undefined) effects.previewEnabled = patch.previewEnabled !== false;
    if (patch.previewOpacity != null) effects.previewOpacity = patch.previewOpacity;
    if (patch.previewColor) effects.previewColor = patch.previewColor;
    if (patch.toolColor) effects.toolColor = patch.toolColor;
    if (patch.toolOpacity != null) effects.toolOpacity = patch.toolOpacity;
    if (patch.fabGearIcon) effects.fabGearIcon = patch.fabGearIcon;
    if (patch.sendCrumbleIntensity != null) effects.sendCrumbleIntensity = patch.sendCrumbleIntensity;
    const storagePatch = {
      chillicollectivoVoiceSettings: patch,
    };
    if (patch.hotkey !== undefined) storagePatch.chillicollectivoVoiceHotkey = patch.hotkey || null;
    if (Object.keys(effects).length) storagePatch.chillicollectivoVoiceEffects = effects;
    if (patch.outCounterEnabled !== undefined) {
      storagePatch.chillicollectivoOutCounterEnabled = patch.outCounterEnabled !== false;
    }
    if (patch.outTarget !== undefined) storagePatch.chillicollectivoOutTarget = patch.outTarget || 0;
    await chrome.storage.local.set(storagePatch);
    if (voiceManager?.loadLocalSettings) await voiceManager.loadLocalSettings();
    if (voiceManager?.applyLocalSettings) voiceManager.applyLocalSettings(patch);
    if (typeof syncChromeVoiceCommandHotkey === 'function' && patch.hotkey !== undefined) {
      await syncChromeVoiceCommandHotkey(patch.hotkey);
    }
  }

  async function chillicollectivoSyncFromWebMicPortal(voiceManager) {
    if (typeof chillicollectivoIsLicenseActivating === 'function' && await chillicollectivoIsLicenseActivating()) {
      return { ok: false, reason: 'activating' };
    }
    const deviceId = await chillicollectivoGetOrCreateDeviceId();
    let data = await chillicollectivoFetchWebMicSync(deviceId);
    if (!data) {
      const mainSettings = await chillicollectivoFetchMainPortalDeviceSettings(deviceId);
      if (mainSettings?.settings && Object.keys(mainSettings.settings).length) {
        await chillicollectivoApplyRemoteMicSettings(mainSettings.settings, voiceManager);
        return { ok: true, data: { settings: mainSettings.settings } };
      }
      return { ok: false, reason: 'fetch_failed' };
    }

    if ((!data.settings || !Object.keys(data.settings).length)) {
      const mainSettings = await chillicollectivoFetchMainPortalDeviceSettings(deviceId);
      if (mainSettings?.settings && Object.keys(mainSettings.settings).length) {
        data.settings = mainSettings.settings;
      }
    }

    if (data.settings && Object.keys(data.settings).length) {
      await chillicollectivoApplyRemoteMicSettings(data.settings, voiceManager);
    }
    const forceLocked = typeof chillicollectivoIsLicenseForceLocked === 'function'
      && await chillicollectivoIsLicenseForceLocked();
    if (data.license?.valid && !forceLocked) {
      await chillicollectivoApplyRemoteMicLicense(data.license);
      const state = typeof chillicollectivoBuildLicenseState === 'function'
        ? chillicollectivoBuildLicenseState({
          key: data.license.key,
          valid: true,
          email: data.license.email,
          plan: data.license.plan,
          expiresAt: data.license.expiresAt,
          source: data.license.source || 'portal',
          validatedAt: data.license.validatedAt,
        }, null)
        : null;
      if (state && typeof chillicollectivoBroadcastLicenseState === 'function') {
        await chillicollectivoBroadcastLicenseState(state);
      }
      if (voiceManager?.unlockTorchwoodTabsAfterLicense && state?.access === 'granted') {
        await voiceManager.unlockTorchwoodTabsAfterLicense(state);
      }
    }
    return { ok: true, data };
  }

  function chillicollectivoScheduleWebMicSync(voiceManager) {
    if (!chrome.alarms?.create) return;
    chrome.alarms.create(CHILLICOLLECTIVO_WEB_MIC.SYNC_ALARM, {
      periodInMinutes: CHILLICOLLECTIVO_WEB_MIC.SYNC_MINUTES,
    });
    if (globalThis.__CHILLICOLLECTIVO_WEB_MIC_ALARM) return;
    globalThis.__CHILLICOLLECTIVO_WEB_MIC_ALARM = true;
    chrome.alarms.onAlarm.addListener((alarm) => {
      if (alarm.name !== CHILLICOLLECTIVO_WEB_MIC.SYNC_ALARM) return;
      chillicollectivoSyncFromWebMicPortal(voiceManager).catch(() => {});
    });
  }

  global.CHILLICOLLECTIVO_WEB_MIC = CHILLICOLLECTIVO_WEB_MIC;
  global.chillicollectivoOpenWebMicOptions = chillicollectivoOpenWebMicOptions;
  global.chillicollectivoSyncFromWebMicPortal = chillicollectivoSyncFromWebMicPortal;
  global.chillicollectivoScheduleWebMicSync = chillicollectivoScheduleWebMicSync;
  global.chillicollectivoPushSettingsToWebMicPortal = chillicollectivoPushSettingsToWebMicPortal;
  global.chillicollectivoPushLicenseToWebMicPortal = chillicollectivoPushLicenseToWebMicPortal;
  global.chillicollectivoActivateLicenseViaWebMicPortal = chillicollectivoActivateLicenseViaWebMicPortal;
  global.chillicollectivoClearWebMicPortalLicense = chillicollectivoClearWebMicPortalLicense;
  global.chillicollectivoPingWebMicPortal = chillicollectivoPingWebMicPortal;
})(typeof globalThis !== 'undefined' ? globalThis : self);
