'use strict';

var path = require('path');
var electron = require('electron');
var i18next = require('i18next');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var path__default = /*#__PURE__*/_interopDefault(path);
var i18next__default = /*#__PURE__*/_interopDefault(i18next);

const fallbackLng = 'en';
const byteUnits = ['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'petabyte'];
const formatBytes = bytes => {
  const order = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), byteUnits.length - 1);
  const unit = byteUnits[order];
  if (!unit) {
    return '???';
  }
  const formatter = new Intl.NumberFormat(undefined, {
    notation: 'compact',
    style: 'unit',
    unit,
    maximumFractionDigits: 1
  });
  return formatter.format(bytes / Math.pow(1024, order));
};
const formatByteSpeed = bytesPerSecond => {
  const order = Math.min(Math.floor(Math.log(bytesPerSecond) / Math.log(1024)), byteUnits.length - 1);
  const unit = byteUnits[order];
  if (!unit) {
    return '???';
  }
  const formatter = new Intl.NumberFormat(undefined, {
    notation: 'compact',
    style: 'unit',
    unit: `${unit}-per-second`,
    maximumFractionDigits: 1
  });
  return formatter.format(bytesPerSecond / Math.pow(1024, order));
};
const formatPercentage = ratio => {
  const formatter = new Intl.NumberFormat(undefined, {
    style: 'percent',
    maximumFractionDigits: 0
  });
  return formatter.format(ratio);
};
const formatDuration = duration => {
  const formatter = new Intl.RelativeTimeFormat(undefined, {
    style: 'narrow',
    numeric: 'always'
  });
  duration /= 1000;
  if (duration / 60 < 1) {
    return formatter.format(duration, 'second');
  }
  duration /= 60;
  if (duration / 60 < 1) {
    return formatter.format(duration, 'minute');
  }
  duration /= 60;
  if (duration / 24 < 1) {
    return formatter.format(duration, 'hour');
  }
  duration /= 24;
  if (duration / 7 < 1) {
    return formatter.format(duration, 'day');
  }
  duration /= 7;
  if (duration / 30 < 1) {
    return formatter.format(duration, 'week');
  }
  duration /= 30;
  if (duration / 12 < 1) {
    return formatter.format(duration, 'month');
  }
  duration /= 12;
  return formatter.format(duration, 'year');
};
const interpolation = {
  escapeValue: false,
  format: (value, format, lng) => {
    if (value instanceof Date && !Number.isNaN(value.getTime())) {
      return new Intl.DateTimeFormat(lng).format(value);
    }
    switch (format) {
      case 'byteSize':
        return formatBytes(value);
      case 'byteSpeed':
        return formatByteSpeed(value);
      case 'percentage':
        return formatPercentage(value);
      case 'duration':
        return formatDuration(value);
    }
    return String(value);
  }
};

var resources = {
  'de-DE': () => Promise.resolve().then(function () { return require('./de-DE.i18n-LjCz_6v_.js'); }),
  'en': () => Promise.resolve().then(function () { return require('./en.i18n-tSOW0b2p.js'); }),
  'es': () => Promise.resolve().then(function () { return require('./es.i18n-BPEvA6Eu.js'); }),
  'fi': () => Promise.resolve().then(function () { return require('./fi.i18n-c5J-X7bw.js'); }),
  'sv': () => Promise.resolve().then(function () { return require('./sv.i18n-DPPaCtsT.js'); }),
  'no': () => Promise.resolve().then(function () { return require('./no.i18n-DjEA_1t4.js'); }),
  'fr': () => Promise.resolve().then(function () { return require('./fr.i18n-CedrZv2y.js'); }),
  'hu': () => Promise.resolve().then(function () { return require('./hu.i18n-DjHjsJUq.js'); }),
  'it-IT': () => Promise.resolve().then(function () { return require('./it-IT.i18n-DF18Si-C.js'); }),
  'ja': () => Promise.resolve().then(function () { return require('./ja.i18n-DdfYsFJ2.js'); }),
  'pl': () => Promise.resolve().then(function () { return require('./pl.i18n-DgfYDbAT.js'); }),
  'pt-BR': () => Promise.resolve().then(function () { return require('./pt-BR.i18n-C8oYUcCz.js'); }),
  'ru': () => Promise.resolve().then(function () { return require('./ru.i18n-CE4cC6oZ.js'); }),
  'tr-TR': () => Promise.resolve().then(function () { return require('./tr-TR.i18n-CyxkAN-C.js'); }),
  'uk-UA': () => Promise.resolve().then(function () { return require('./uk-UA.i18n-BkqkMhw4.js'); }),
  'zh-CN': () => Promise.resolve().then(function () { return require('./zh-CN.i18n-C-Voh6oB.js'); }),
  'zh-TW': () => Promise.resolve().then(function () { return require('./zh-TW.i18n-BJUiDIeM.js'); })
};

const invokeWithRetry = (channel, retryOptions = {}, ...args) => {
  const {
    maxAttempts = 3,
    retryDelay = 1000,
    logRetries = true,
    shouldRetry = () => true
  } = retryOptions;
  const attemptInvoke = async attempt => {
    try {
      const result = await electron.ipcRenderer.invoke(channel, ...args);

      // Check if result indicates failure (for channels that return success flags)
      if (result && typeof result === 'object' && 'success' in result && result.success === false) {
        throw new Error(`IPC call failed: ${channel} returned success: false`);
      }
      return result;
    } catch (error) {
      const isLastAttempt = attempt >= maxAttempts;
      if (logRetries) {
        console.log(`IPC call failed: ${channel} (attempt ${attempt}/${maxAttempts})`, error);
      }
      if (isLastAttempt || !shouldRetry(error, attempt)) {
        if (logRetries) {
          console.error(`IPC call giving up: ${channel} after ${attempt} attempts`, error);
        }
        throw error;
      }
      if (logRetries) {
        console.log(`IPC call retrying: ${channel} in ${retryDelay}ms... (attempt ${attempt + 1}/${maxAttempts})`);
      }
      await new Promise(resolve => setTimeout(resolve, retryDelay));
      return attemptInvoke(attempt + 1);
    }
  };
  return attemptInvoke(1);
};

function _defineProperty(e, r, t) {
  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
    value: t,
    enumerable: true,
    configurable: true,
    writable: true
  }) : e[r] = t, e;
}
function _toPrimitive(t, r) {
  if ("object" != typeof t || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (undefined !== e) {
    var i = e.call(t, r || "default");
    if ("object" != typeof i) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r ? String : Number)(t);
}
function _toPropertyKey(t) {
  var i = _toPrimitive(t, "string");
  return "symbol" == typeof i ? i : i + "";
}

/**
 * Internal picker provider that uses the React UI and desktopCapturer cache.
 * This provider works in both main and renderer processes:
 * - handleDisplayMediaRequest: called from main process, uses ipc.ts state
 * - initialize: called from renderer process, preloads UI and cache
 *
 * Note: This provider needs access to state in ipc.ts. The factory will
 * pass a handler function that encapsulates the internal picker logic.
 */
class InternalPickerProvider {
  constructor() {
    _defineProperty(this, "type", 'internal');
    _defineProperty(this, "requiresInternalUI", true);
    _defineProperty(this, "requiresCacheWarming", true);
    _defineProperty(this, "isInitialized", false);
    _defineProperty(this, "handleRequestFn", null);
    _defineProperty(this, "initializeFn", null);
  }
  /**
   * Set the handler function from main process (ipc.ts)
   * This encapsulates all the internal picker logic with access to ipc.ts state
   */
  setHandleRequestHandler(handler) {
    this.handleRequestFn = handler;
  }

  /**
   * Set the initialize function from renderer process (video-call-window.ts)
   * This encapsulates the UI preload and cache warming logic
   */
  setInitializeHandler(handler) {
    this.initializeFn = handler;
  }
  handleDisplayMediaRequest(callback) {
    if (this.handleRequestFn) {
      this.handleRequestFn(callback);
    } else {
      console.error('InternalPickerProvider: handleRequest handler not set. This should be set by ipc.ts');
      callback({
        video: false
      });
    }
  }
  async initialize() {
    if (this.isInitialized) return;
    console.log('Screen picker [internal]: initializing cache and UI');
    if (this.initializeFn) {
      await this.initializeFn();
    } else {
      console.warn('InternalPickerProvider: initialize handler not set. Call setInitializeHandler() first.');
    }
    this.isInitialized = true;
  }
  cleanup() {
    // Clear caches, reset state
    this.isInitialized = false;
  }
}

class PortalPickerProvider {
  constructor() {
    _defineProperty(this, "type", 'portal');
    _defineProperty(this, "requiresInternalUI", false);
    _defineProperty(this, "requiresCacheWarming", false);
  }
  handleDisplayMediaRequest(callback) {
    // On Linux/Wayland, calling getSources() triggers the XDG portal picker.
    // The portal typically returns exactly one source on selection or an empty array
    // on cancellation; we defensively check for > 0 and use only the first source.
    console.log('Screen picker [portal]: triggering XDG portal picker via getSources()');
    electron.desktopCapturer.getSources({
      types: ['screen', 'window']
    }).then(sources => {
      if (sources.length > 0) {
        // User selected a source via portal picker
        callback({
          video: sources[0]
        });
      } else {
        // User cancelled or no source available
        console.warn('Screen picker [portal]: No source selected by user');
        callback({
          video: false
        });
      }
    }).catch(error => {
      console.error('Screen picker [portal]: Failed to get source from XDG portal:', error);
      callback({
        video: false
      });
    });
  }
  async initialize() {
    // Portal picker requires no initialization
    console.log('Screen picker [portal]: initialized (no-op)');
  }
  cleanup() {
    // Portal picker requires no cleanup
    console.log('Screen picker [portal]: cleanup (no-op)');
  }
}

function detectPickerType() {
  if (process.platform === 'linux') {
    const sessionType = process.env.XDG_SESSION_TYPE;
    const desktop = process.env.XDG_CURRENT_DESKTOP || '';
    const isWayland = sessionType === 'wayland';
    const hasPortal = /GNOME|KDE|XFCE|Cinnamon|MATE|Pantheon|Budgie|Unity/i.test(desktop);
    if (isWayland || hasPortal) {
      return 'portal';
    }
  }

  // Future: Add macOS native picker detection here
  // if (process.platform === 'darwin' && hasMacOSNativePicker()) {
  //   return 'native-macos';
  // }

  return 'internal';
}
let cachedProvider = null;
function createScreenPicker() {
  if (cachedProvider) return cachedProvider;
  const type = detectPickerType();
  switch (type) {
    case 'portal':
      cachedProvider = new PortalPickerProvider();
      break;
    case 'internal':
    default:
      cachedProvider = new InternalPickerProvider();
  }
  console.log(`Screen picker: using ${cachedProvider.type} provider`);
  return cachedProvider;
}

const MAX_INIT_ATTEMPTS = 10;
const MAX_RECOVERY_ATTEMPTS = 3;
const LOADING_TIMEOUT_MS = 15000;
const LOADING_SHOW_DELAY = 500;
const ERROR_SHOW_DELAY = 800;
const ERROR_SHOW_DELAY_404 = 1500;
const VIDEO_CALL_PRELOAD_RELATIVE_PATH = 'preload/preload.js';
const RECOVERY_DELAYS = {
  webviewReload: 1000,
  urlRefresh: 2000,
  fullReinitialize: 3000
};
let initAttempts = 0;
let isWindowDestroying = false;
let screenPickerModule = null;
let screenPickerModulePromise = null;
const state = {
  url: null,
  status: 'idle',
  recoveryAttempt: 0,
  webview: null,
  shouldAutoOpenDevtools: false,
  isReloading: false,
  hasInitialLoadCompleted: false,
  errorMessage: null
};
let loadingTimeout = null;
let recoveryTimeout = null;
let loadingDisplayTimeout = null;
let errorDisplayTimeout = null;
const initializeI18n = async () => {
  try {
    var _resources;
    const languageResult = await invokeWithRetry('video-call-window/get-language', {
      maxAttempts: 3,
      retryDelay: 500,
      logRetries: "production" === 'development'
    });
    const lng = (languageResult === null || languageResult === void 0 ? void 0 : languageResult.language) || fallbackLng;
    if ("production" === 'development') ;
    await i18next__default.default.init({
      lng,
      fallbackLng,
      resources: {
        ...(lng && lng !== fallbackLng && {
          [lng]: {
            translation: await ((_resources = resources[lng]) === null || _resources === void 0 ? void 0 : _resources.call(resources))
          }
        }),
        [fallbackLng]: {
          translation: await resources[fallbackLng]()
        }
      },
      interpolation,
      initImmediate: true
    });
    if ("production" === 'development') ;
  } catch (error) {
    console.error('Failed to initialize i18n for video call window:', error);
    throw error;
  }
};
const t = (key, defaultValue) => {
  return i18next__default.default.t(key, {
    defaultValue
  });
};
const clearAllTimeouts = () => {
  if (loadingTimeout) {
    clearTimeout(loadingTimeout);
    loadingTimeout = null;
  }
  if (recoveryTimeout) {
    clearTimeout(recoveryTimeout);
    recoveryTimeout = null;
  }
  if (loadingDisplayTimeout) {
    clearTimeout(loadingDisplayTimeout);
    loadingDisplayTimeout = null;
  }
  if (errorDisplayTimeout) {
    clearTimeout(errorDisplayTimeout);
    errorDisplayTimeout = null;
  }
};
const updateLoadingUI = (show, isReloading = false) => {
  const overlay = document.getElementById('loading-overlay-root');
  if (!overlay) return;
  if (show) {
    overlay.classList.add('show');
    const text = overlay.querySelector('.loading-text');
    const description = overlay.querySelector('.loading-description');
    if (text) {
      text.textContent = isReloading ? t('videoCall.loading.reloading', 'Reloading...') : t('videoCall.loading.initial', 'Loading video call...');
    }
    if (description) {
      description.textContent = t('videoCall.loading.description', 'Please wait while we connect you');
    }
    // Hide webview when showing loading
    if (state.webview) {
      state.webview.style.visibility = 'hidden';
    }
  } else {
    overlay.classList.remove('show');
  }
};
const updateErrorUI = (show, message = null) => {
  const overlay = document.getElementById('error-overlay-root');
  if (!overlay) return;
  if (show) {
    overlay.classList.add('show');
    const title = overlay.querySelector('.error-title');
    const announcement = overlay.querySelector('.error-announcement');
    const errorMsg = overlay.querySelector('.error-message');
    const reloadButton = overlay.querySelector('#error-reload-button');
    if (title) {
      title.textContent = t('videoCall.error.title', 'Connection Failed');
    }
    if (announcement) {
      announcement.textContent = t('videoCall.error.announcement', 'Unable to connect to video call');
    }
    if (errorMsg) {
      if (message) {
        errorMsg.textContent = message;
        errorMsg.classList.add('show');
      } else {
        errorMsg.classList.remove('show');
      }
    }
    if (reloadButton) {
      reloadButton.textContent = t('videoCall.error.reload', 'Reload');
    }
    // Hide webview when showing error
    if (state.webview) {
      state.webview.style.visibility = 'hidden';
    }
  } else {
    overlay.classList.remove('show');
  }
};
const showLoadingWithDelay = (isReloading = false) => {
  if (loadingDisplayTimeout) {
    clearTimeout(loadingDisplayTimeout);
  }
  loadingDisplayTimeout = setTimeout(() => {
    if (state.status === 'loading' && !state.errorMessage) {
      updateLoadingUI(true, isReloading);
    }
    loadingDisplayTimeout = null;
  }, LOADING_SHOW_DELAY);
};
const showErrorWithDelay = (message, is404Like = false) => {
  if (errorDisplayTimeout) {
    clearTimeout(errorDisplayTimeout);
  }
  const delay = is404Like ? ERROR_SHOW_DELAY_404 : ERROR_SHOW_DELAY;
  errorDisplayTimeout = setTimeout(() => {
    if (state.status === 'error') {
      updateErrorUI(true, message);
    }
    errorDisplayTimeout = null;
  }, delay);
};
const attemptAutoRecovery = () => {
  if (state.recoveryAttempt >= MAX_RECOVERY_ATTEMPTS) {
    state.status = 'error';
    state.errorMessage = t('videoCall.error.maxRetriesReached', 'Failed to load after multiple attempts');
    updateLoadingUI(false);
    updateErrorUI(true, state.errorMessage);
    return;
  }
  const currentAttempt = state.recoveryAttempt + 1;
  state.recoveryAttempt = currentAttempt;
  state.isReloading = true;
  let delay;
  switch (currentAttempt) {
    case 1:
      delay = RECOVERY_DELAYS.webviewReload;
      break;
    case 2:
      delay = RECOVERY_DELAYS.urlRefresh;
      break;
    case 3:
      delay = RECOVERY_DELAYS.fullReinitialize;
      break;
    default:
      return;
  }
  recoveryTimeout = setTimeout(() => {
    const webview = state.webview;
    switch (currentAttempt) {
      case 1:
        if (webview) {
          webview.reload();
        }
        break;
      case 2:
        if (webview && state.url) {
          try {
            const validatedUrl = validateVideoCallUrl(state.url);
            webview.src = 'about:blank';
            setTimeout(() => {
              if (webview) {
                webview.src = validatedUrl;
              }
            }, 500);
          } catch (error) {
            console.error('Video call window: URL validation failed during recovery:', error);
            console.error('Video call window: Skipping URL refresh recovery step, proceeding to next recovery attempt');
            if (recoveryTimeout) {
              clearTimeout(recoveryTimeout);
              recoveryTimeout = null;
            }
            state.recoveryAttempt = currentAttempt;
            attemptAutoRecovery();
            return;
          }
        }
        break;
      case 3:
        window.location.reload();
        break;
    }
    recoveryTimeout = null;
  }, delay);
};
const checkForClosePage = async url => {
  if (url.includes('/close.html') || url.includes('/close2.html')) {
    console.log('Video call window: Close page detected, scheduling window close:', url);
    state.status = 'closing';
    clearAllTimeouts();
    updateLoadingUI(false);
    updateErrorUI(false);
    setTimeout(async () => {
      try {
        await invokeWithRetry('video-call-window/close-requested', {
          maxAttempts: 2,
          retryDelay: 500,
          logRetries: "production" === 'development'
        });
        if ("production" === 'development') ;
      } catch (error) {
        console.error('Video call window: Failed to send close request:', error);
      }
    }, 1000);
  }
};
const setupWebviewEventHandlers = webview => {
  const webviewElement = webview;
  const handleLoadStart = () => {
    console.log('Video call window: Load started');
    if (state.status === 'closing') {
      console.log('Video call window: Skipping load start handling - window is closing');
      return;
    }
    if (state.hasInitialLoadCompleted && !state.isReloading && state.recoveryAttempt === 0) {
      console.log('Video call window: Skipping loading UI - initial load already completed');
      return;
    }
    state.status = 'loading';
    state.errorMessage = null;
    state.isReloading = false;
    clearAllTimeouts();
    showLoadingWithDelay(false);
    invokeWithRetry('video-call-window/webview-loading', {
      maxAttempts: 2,
      retryDelay: 500,
      logRetries: "production" === 'development'
    }).catch(error => {
      console.error('Video call window: Failed to send webview loading state:', error);
    });
    loadingTimeout = setTimeout(() => {
      loadingTimeout = null;
      attemptAutoRecovery();
    }, LOADING_TIMEOUT_MS);
  };
  const handleNavigate = event => {
    console.log('Video call window: Navigation event:', event.url);
    checkForClosePage(event.url);
  };
  const handleDomReady = () => {
    console.log('Video call window: Webview DOM ready');
    if (state.shouldAutoOpenDevtools) {
      console.log('Video call window: Auto-opening devtools for webview');
      invokeWithRetry('video-call-window/open-webview-dev-tools', {
        maxAttempts: 2,
        retryDelay: 500,
        logRetries: "production" === 'development'
      }).then(success => {
        if (success) {
          console.log('Video call window: Successfully auto-opened devtools');
        } else {
          console.warn('Video call window: Failed to auto-open devtools');
        }
      }).catch(error => {
        console.error('Video call window: Error auto-opening devtools:', error);
      });
    }
  };
  const handleFinishLoad = () => {
    console.log('Video call window: Webview finished loading (all resources loaded)');
    state.recoveryAttempt = 0;
    state.status = 'ready';
    state.hasInitialLoadCompleted = true;
    state.isReloading = false;
    clearAllTimeouts();
    updateLoadingUI(false);
    updateErrorUI(false);
    if (state.webview) {
      state.webview.style.visibility = 'visible';
    }
    invokeWithRetry('video-call-window/webview-ready', {
      maxAttempts: 2,
      retryDelay: 500,
      logRetries: "production" === 'development'
    }).catch(error => {
      console.error('Video call window: Failed to send webview ready state:', error);
    });

    // Initialize the screen picker (provider handles its own needs)
    const provider = createScreenPicker();

    // Set initialize handler for internal picker
    if (provider instanceof InternalPickerProvider) {
      provider.setInitializeHandler(async () => {
        await preloadScreenSharePicker();
        electron.ipcRenderer.invoke('video-call-window/prewarm-capturer-cache').catch(() => {
          // Silent failure - cache warming is optional optimization
        });
      });
    }
    provider.initialize().catch(error => {
      console.error('Screen picker initialization failed:', error);
    });
  };
  const handleDidFailLoad = event => {
    const errorInfo = {
      errorCode: event.errorCode,
      errorDescription: event.errorDescription,
      validatedURL: event.validatedURL,
      isMainFrame: event.isMainFrame
    };
    console.error('Video call window: Webview failed to load:', errorInfo);
    if (event.isMainFrame) {
      clearAllTimeouts();
      state.status = 'error';
      state.errorMessage = `${event.errorDescription} (${event.errorCode})`;
      updateLoadingUI(false);
      const is404LikeError = [-6, -105, -106].includes(event.errorCode);
      showErrorWithDelay(state.errorMessage, is404LikeError);
      electron.ipcRenderer.invoke('video-call-window/webview-failed', `${event.errorDescription} (${event.errorCode})`).catch(error => {
        console.error('Video call window: Failed to send webview failed state:', error);
      });
    }
  };
  const handleCrashed = () => {
    console.error('Video call window: Webview crashed');
    clearAllTimeouts();
    state.status = 'error';
    state.errorMessage = t('videoCall.error.crashed', 'Webview crashed');
    updateLoadingUI(false);
    updateErrorUI(true, state.errorMessage);
    invokeWithRetry('video-call-window/webview-failed', {
      maxAttempts: 2,
      retryDelay: 500,
      logRetries: "production" === 'development'
    }, 'Webview crashed').catch(error => {
      console.error('Video call window: Failed to send webview failed state:', error);
    });
  };
  const handleWebviewAttached = () => {
    console.log('Video call window: Webview attached');
    invokeWithRetry('video-call-window/webview-created', {
      maxAttempts: 2,
      retryDelay: 500,
      logRetries: "production" === 'development'
    }).catch(error => {
      console.error('Video call window: Failed to send webview created state:', error);
    });
    if (state.shouldAutoOpenDevtools) {
      setTimeout(() => {
        invokeWithRetry('video-call-window/open-webview-dev-tools', {
          maxAttempts: 2,
          retryDelay: 500,
          logRetries: "production" === 'development'
        }).then(success => {
          if (success) {
            console.log('Video call window: Successfully auto-opened devtools on attach');
          }
        }).catch(error => {
          console.error('Video call window: Error auto-opening devtools on attach:', error);
        });
      }, 100);
    }
  };
  webviewElement.addEventListener('webview-attached', handleWebviewAttached);
  webviewElement.addEventListener('did-start-loading', handleLoadStart);
  webviewElement.addEventListener('did-navigate', handleNavigate);
  webviewElement.addEventListener('dom-ready', handleDomReady);
  webviewElement.addEventListener('did-finish-load', handleFinishLoad);
  webviewElement.addEventListener('did-fail-load', handleDidFailLoad);
  webviewElement.addEventListener('crashed', handleCrashed);
};
const validateVideoCallUrl = url => {
  try {
    const parsedUrl = new URL(url);
    const allowedProtocols = ['http:', 'https:'];
    if (!allowedProtocols.includes(parsedUrl.protocol)) {
      throw new Error(`Invalid URL protocol: ${parsedUrl.protocol}. Only http: and https: are allowed.`);
    }
    return parsedUrl.href;
  } catch (error) {
    if (error instanceof TypeError) {
      throw new Error(`Invalid URL format: ${url}`);
    }
    throw error;
  }
};
const createWebview = url => {
  const container = document.getElementById('webview-container');
  if (!container) {
    throw new Error('Webview container not found');
  }
  const validatedUrl = validateVideoCallUrl(url);
  const htmlPath = window.location.pathname;
  const appDir = path__default.default.posix.dirname(htmlPath);
  const preloadRelativePath = path__default.default.posix.join(appDir, VIDEO_CALL_PRELOAD_RELATIVE_PATH);

  // Convert to file:// URL format required by Electron webview preload attribute
  // window.location.origin is 'file://' on all platforms
  // path.posix.join produces absolute paths starting with '/'
  // Combining them: 'file://' + '/path' = 'file:///path' (correct format)
  // Works on Linux: file:///home/user/app/preload/preload.js
  // Works on macOS: file:///Users/user/app/preload/preload.js
  // Works on Windows: file:///C:/Users/user/app/preload/preload.js
  const preloadPath = `${window.location.origin}${preloadRelativePath}`;
  const webview = document.createElement('webview');
  webview.setAttribute('preload', preloadPath);
  webview.setAttribute('webpreferences', 'nodeIntegration,nativeWindowOpen=true');
  webview.setAttribute('allowpopups', 'true');
  webview.setAttribute('partition', 'persist:jitsi-session');
  webview.src = validatedUrl;
  webview.style.cssText = `
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    visibility: hidden;
    z-index: 0;
  `;
  container.appendChild(webview);
  state.webview = webview;
  state.url = url;
  setupWebviewEventHandlers(webview);
};
const preloadScreenSharePicker = async () => {
  if (screenPickerModule) {
    return;
  }
  try {
    if ("production" === 'development') ;
    // Track import promise to prevent concurrent imports
    if (!screenPickerModulePromise) {
      screenPickerModulePromise = Promise.resolve().then(function () { return require('./screenSharePickerMount-AQNjhJHk.js'); });
    }
    screenPickerModule = await screenPickerModulePromise;
    screenPickerModulePromise = null;
    screenPickerModule.mount(); // Mount only (stays hidden until IPC event)
    if ("production" === 'development') ;
  } catch (error) {
    console.error('Video call window: Failed to preload React:', error);
    screenPickerModulePromise = null;
  }
};
const handleReload = () => {
  console.log('Video call window: Manual reload requested');
  state.isReloading = true;
  state.status = 'loading';
  state.errorMessage = null;
  state.hasInitialLoadCompleted = false;
  state.recoveryAttempt = 0;
  clearAllTimeouts();
  updateErrorUI(false);
  updateLoadingUI(true, true);
  const webview = state.webview;
  if (webview) {
    webview.reload();
  }
};
const FALLBACK_RELOAD_KEY = 'video-call-fallback-reloads';
const MAX_FALLBACK_RELOADS = 3;
const showFallbackUI = () => {
  const reloadCount = parseInt(sessionStorage.getItem(FALLBACK_RELOAD_KEY) || '0', 10);
  const canAutoReload = reloadCount < MAX_FALLBACK_RELOADS;
  const fallbackContainer = document.createElement('div');
  fallbackContainer.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #2f343d;
    color: white;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Helvetica Neue', Arial, sans-serif;
    z-index: 9999;
  `;
  fallbackContainer.innerHTML = `
    <div style="text-align: center;">
      <h2 style="color: #fff; margin: 0;">Video Call Unavailable</h2>
      <p style="color: #ccc; margin: 10px 0;">Unable to initialize video call window</p>
      <p style="color: #999; margin: 10px 0; font-size: 14px;">${canAutoReload ? 'Retrying automatically in 3 seconds...' : 'Please close and reopen the video call.'}</p>
    </div>
  `;
  document.body.appendChild(fallbackContainer);
  if (canAutoReload) {
    sessionStorage.setItem(FALLBACK_RELOAD_KEY, String(reloadCount + 1));
    setTimeout(() => {
      window.location.reload();
    }, 3000);
  }
};
const start = async () => {
  if (isWindowDestroying) {
    console.log('Video call window: Skipping initialization - window is being destroyed');
    return;
  }
  initAttempts++;
  if (initAttempts > 1 || "production" === 'development') {
    console.log(`Video call window initialization attempt ${initAttempts}/${MAX_INIT_ATTEMPTS}`);
  }
  try {
    if (document.readyState === 'loading') {
      if ("production" === 'development') ;
      return new Promise(resolve => {
        document.addEventListener('DOMContentLoaded', () => {
          start().then(resolve).catch(resolve);
        });
      });
    }
    await initializeI18n();
    const params = new URLSearchParams(window.location.search);
    let url = params.get('url');
    const autoOpenDevtools = params.get('autoOpenDevtools') === 'true';
    state.shouldAutoOpenDevtools = autoOpenDevtools;
    if (!url) {
      // Try to get URL via IPC if not provided in query params
      try {
        const urlResult = await invokeWithRetry('video-call-window/request-url', {
          maxAttempts: 2,
          retryDelay: 500,
          logRetries: "production" === 'development'
        });
        if (urlResult !== null && urlResult !== void 0 && urlResult.success && urlResult !== null && urlResult !== void 0 && urlResult.url) {
          url = urlResult.url;
          if (urlResult.autoOpenDevtools !== undefined) {
            state.shouldAutoOpenDevtools = urlResult.autoOpenDevtools;
          }
        }
      } catch (error) {
        console.error('Video call window: Failed to request URL via IPC:', error);
      }
    }
    if (!url) {
      // No URL available - show error state instead of stuck loading screen
      state.status = 'error';
      state.errorMessage = t('videoCall.error.noUrl', 'No video call URL provided');
      updateLoadingUI(false);
      showErrorWithDelay(state.errorMessage, false);
      return;
    }
    createWebview(url);
    await invokeWithRetry('video-call-window/url-received', {
      maxAttempts: 2,
      retryDelay: 500,
      logRetries: "production" === 'development'
    });
    state.status = 'loading';
    // Show loading immediately for initial load
    updateLoadingUI(true, false);
    const handshakeRetryOptions = {
      maxAttempts: 3,
      retryDelay: 1000,
      logRetries: "production" === 'development'
    };
    await invokeWithRetry('video-call-window/handshake', handshakeRetryOptions);
    await invokeWithRetry('video-call-window/renderer-ready', handshakeRetryOptions);
    if ("production" === 'development') ;
  } catch (error) {
    console.error(`Video call window initialization failed (attempt ${initAttempts}):`, error);
    if (initAttempts < MAX_INIT_ATTEMPTS && !isWindowDestroying) {
      console.log('Video call window: Retrying initialization in 1 second...');
      setTimeout(() => {
        if (!isWindowDestroying) {
          start().catch(retryError => {
            console.error('Video call window retry also failed:', retryError);
          });
        }
      }, 1000);
    } else if (!isWindowDestroying) {
      console.error('Video call window: Max initialization attempts reached, showing fallback UI');
      showFallbackUI();
    }
  }
};
window.addEventListener('error', event => {
  console.error('Video call window global error:', event.error);
});
window.addEventListener('unhandledrejection', event => {
  console.error('Video call window unhandled rejection:', event.reason);
  event.preventDefault();
});

// IPC listener for screen picker (with cleanup on page unload)
const handleOpenScreenPicker = () => {
  (async () => {
    try {
      if (!screenPickerModule) {
        // Track import promise to prevent concurrent imports
        if (!screenPickerModulePromise) {
          screenPickerModulePromise = Promise.resolve().then(function () { return require('./screenSharePickerMount-AQNjhJHk.js'); });
        }
        screenPickerModule = await screenPickerModulePromise;
        screenPickerModulePromise = null;
      }
      screenPickerModule.show();
    } catch (error) {
      screenPickerModulePromise = null;
      console.error('Video call window: Failed to open screen picker:', error);
    }
  })();
};
electron.ipcRenderer.on('video-call-window/open-screen-picker', handleOpenScreenPicker);
window.addEventListener('beforeunload', () => {
  isWindowDestroying = true;
  clearAllTimeouts();
  // Clean up IPC listener to prevent memory leaks on reload
  electron.ipcRenderer.removeListener('video-call-window/open-screen-picker', handleOpenScreenPicker);
});

// Setup reload button handler when DOM is ready
const setupReloadButton = () => {
  const reloadButton = document.getElementById('error-reload-button');
  if (reloadButton) {
    reloadButton.addEventListener('click', handleReload);
  }
};
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', setupReloadButton);
} else {
  setupReloadButton();
}
start().catch(error => {
  console.error('Video call window: Fatal initialization error:', error);
  showFallbackUI();
});

exports.preloadScreenSharePicker = preloadScreenSharePicker;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 97672 characters]
