'use strict';

var i18next = require('i18next');
var require$$0 = require('react-dom');
var reactI18next = require('react-i18next');
var fuselage = require('@rocket.chat/fuselage');
var electron = require('electron');
var require$$0$1 = require('react');
var styled = require('@emotion/styled');

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

var i18next__default = /*#__PURE__*/_interopDefault(i18next);
var require$$0__default = /*#__PURE__*/_interopDefault(require$$0);
var require$$0__default$1 = /*#__PURE__*/_interopDefault(require$$0$1);
var styled__default = /*#__PURE__*/_interopDefault(styled);

var createRoot;

var m$1 = require$$0__default.default;
{
  createRoot = m$1.createRoot;
  m$1.hydrateRoot;
}

const useDialog = (visible, onClose = () => undefined) => {
  const dialogRef = require$$0$1.useRef(null);
  const onCloseRef = require$$0$1.useRef();
  require$$0$1.useEffect(() => {
    onCloseRef.current = onClose;
  });
  require$$0$1.useEffect(() => {
    const dialog = dialogRef.current;
    const onClose = onCloseRef.current;
    if (!dialog) {
      return;
    }
    if (!visible) {
      dialog.close();
      return;
    }
    dialog.showModal();
    dialog.onclose = () => {
      onClose === null || onClose === undefined || onClose();
    };
    dialog.onclick = ({
      clientX,
      clientY
    }) => {
      const {
        left,
        top,
        width,
        height
      } = dialog.getBoundingClientRect();
      const isInDialog = top <= clientY && clientY <= top + height && left <= clientX && clientX <= left + width;
      if (!isInDialog) {
        dialog.close();
      }
    };
  }, [visible]);
  return dialogRef;
};

const Wrapper = styled__default.default.dialog`
  z-index: 1000;
  top: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  cursor: default;
  user-select: none;
  border: 0;
  background-color: transparent;
  max-height: 90vh;

  &:not([open]) {
    display: none;
  }
`;

var jsxRuntime = {exports: {}};

var reactJsxRuntime_production_min = {};

/**
 * @license React
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var f = require$$0__default$1.default,
  k = Symbol.for("react.element"),
  l = Symbol.for("react.fragment"),
  m = Object.prototype.hasOwnProperty,
  n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,
  p = {
    key: true,
    ref: true,
    __self: true,
    __source: true
  };
function q(c, a, g) {
  var b,
    d = {},
    e = null,
    h = null;
  undefined !== g && (e = "" + g);
  undefined !== a.key && (e = "" + a.key);
  undefined !== a.ref && (h = a.ref);
  for (b in a) m.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]);
  if (c && c.defaultProps) for (b in a = c.defaultProps, a) undefined === d[b] && (d[b] = a[b]);
  return {
    $$typeof: k,
    type: c,
    key: e,
    ref: h,
    props: d,
    _owner: n.current
  };
}
reactJsxRuntime_production_min.Fragment = l;
reactJsxRuntime_production_min.jsx = q;
reactJsxRuntime_production_min.jsxs = q;

{
  jsxRuntime.exports = reactJsxRuntime_production_min;
}

var jsxRuntimeExports = jsxRuntime.exports;

const Dialog = ({
  children,
  isVisible = false,
  onClose
}) => {
  const dialogRef = useDialog(isVisible, onClose);
  return /*#__PURE__*/jsxRuntimeExports.jsx(Wrapper, {
    ref: dialogRef,
    children: /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Scrollable, {
      children: /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Tile, {
        elevation: "2",
        padding: "x32",
        display: "flex",
        flexDirection: "column",
        children: children
      })
    })
  });
};

const desktopCapturer = {
  getSources: opts => electron.ipcRenderer.invoke('desktop-capturer-get-sources', [opts])
};
function ScreenSharePicker({
  onMounted,
  responseChannel = 'video-call-window/screen-sharing-source-responded',
  permissionChannel = 'video-call-window/screen-recording-is-permission-granted',
  openUrlChannel = 'video-call-window/open-url',
  includeTheme = true
} = {}) {
  const {
    t
  } = reactI18next.useTranslation();
  const [visible, setVisible] = require$$0$1.useState(false);
  const [sources, setSources] = require$$0$1.useState([]);
  const [currentTab, setCurrentTab] = require$$0$1.useState('screen');
  const [selectedSourceId, setSelectedSourceId] = require$$0$1.useState(null);
  const [isScreenRecordingPermissionGranted, setIsScreenRecordingPermissionGranted] = require$$0$1.useState(false);

  // Track whether an IPC response has been sent for the current picker session.
  // This ensures cancellation is always sent regardless of how the dialog is dismissed
  // (click outside, ESC key, programmatic close, etc.).
  const responseSentRef = require$$0$1.useRef(false);
  const wasVisibleRef = require$$0$1.useRef(false);
  const fetchSources = require$$0$1.useCallback(async () => {
    try {
      const sources = await desktopCapturer.getSources({
        types: ['window', 'screen']
      });

      // Filter out sources that are not capturable
      const filteredSources = sources.filter(source => {
        // Only check for basic validity - thumbnail validation is already done by IPC handler
        if (!source.name || source.name.trim() === '') {
          return false;
        }
        return true;
      }).sort((a, b) => a.name.localeCompare(b.name));
      setSources(filteredSources);

      // If the currently selected source is no longer available, clear the selection
      if (selectedSourceId && !filteredSources.find(s => s.id === selectedSourceId)) {
        console.log('Previously selected source no longer available, clearing selection');
        setSelectedSourceId(null);
      }
    } catch (error) {
      console.error('Error fetching screen sharing sources:', error);
      setSources([]);
    }
  }, [selectedSourceId]);
  require$$0$1.useEffect(() => {
    const checkScreenRecordingPermission = async () => {
      const result = await electron.ipcRenderer.invoke(permissionChannel);
      setIsScreenRecordingPermissionGranted(result);
    };
    checkScreenRecordingPermission().catch(console.error);
  }, [visible, permissionChannel]);
  require$$0$1.useEffect(() => {
    fetchSources();
  }, [fetchSources]);
  require$$0$1.useEffect(() => {
    if (onMounted) {
      onMounted(setVisible);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Safety net: if the picker closes without handleShare or handleClose having sent a
  // response (e.g. due to dialog close event not firing correctly), send cancellation.
  require$$0$1.useEffect(() => {
    if (visible) {
      responseSentRef.current = false;
      wasVisibleRef.current = true;
    } else if (wasVisibleRef.current) {
      wasVisibleRef.current = false;
      if (!responseSentRef.current) {
        responseSentRef.current = true;
        electron.ipcRenderer.send(responseChannel, null);
      }
    }
  }, [visible, responseChannel]);
  require$$0$1.useEffect(() => {
    if (!visible) {
      return undefined;
    }
    fetchSources();
    const timer = setInterval(() => {
      fetchSources();
    }, 3000);
    return () => {
      clearInterval(timer);
    };
  }, [visible, fetchSources]);
  const handleScreenSharingSourceClick = id => () => {
    setSelectedSourceId(id);
  };
  const handleShare = () => {
    if (selectedSourceId) {
      // Validate that the selected source still exists in our current sources list
      const selectedSource = sources.find(s => s.id === selectedSourceId);
      if (!selectedSource) {
        console.error('Selected source no longer available:', selectedSourceId);
        // Refresh sources and clear selection
        fetchSources();
        setSelectedSourceId(null);
        return;
      }

      // Additional validation before sharing
      if (selectedSource.thumbnail.isEmpty()) {
        console.error('Selected source has empty thumbnail, cannot share:', selectedSourceId);
        setSelectedSourceId(null);
        return;
      }
      console.log('Sharing screen source:', {
        id: selectedSource.id,
        name: selectedSource.name
      });
      responseSentRef.current = true;
      setVisible(false);
      electron.ipcRenderer.send(responseChannel, selectedSourceId);
    }
  };
  const handleClose = () => {
    if (responseSentRef.current) {
      // Response already sent (e.g. handleShare ran first and triggered onclose via setVisible)
      return;
    }
    responseSentRef.current = true;
    setVisible(false);
    electron.ipcRenderer.send(responseChannel, null);
  };

  // Filter sources based on the current tab
  const filteredSources = sources.filter(source => {
    if (currentTab === 'screen') {
      return source.id.includes('screen');
    }
    return source.id.includes('window');
  });
  return /*#__PURE__*/jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, {
    children: [includeTheme && /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.PaletteStyleTag, {
      theme: "dark",
      selector: ":root"
    }), /*#__PURE__*/jsxRuntimeExports.jsx(Dialog, {
      isVisible: visible,
      onClose: handleClose,
      children: /*#__PURE__*/jsxRuntimeExports.jsxs(fuselage.Box, {
        width: "680px",
        margin: "auto",
        display: "flex",
        flexDirection: "column",
        height: "560px",
        backgroundColor: "light",
        color: "default",
        children: [/*#__PURE__*/jsxRuntimeExports.jsxs(fuselage.Box, {
          marginBlockEnd: "x12",
          children: [/*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Box, {
            fontScale: "h1",
            marginBlockEnd: "x12",
            children: t('screenSharing.title')
          }), /*#__PURE__*/jsxRuntimeExports.jsxs(fuselage.Tabs, {
            children: [/*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Tabs.Item, {
              selected: currentTab === 'screen',
              onClick: () => setCurrentTab('screen'),
              children: t('screenSharing.entireScreen')
            }), /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Tabs.Item, {
              selected: currentTab === 'window',
              onClick: () => setCurrentTab('window'),
              children: t('screenSharing.applicationWindow')
            })]
          })]
        }), /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Box, {
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
          marginBlockStart: "x10",
          marginBlockEnd: "x10",
          flexGrow: 1,
          children: !isScreenRecordingPermissionGranted ? /*#__PURE__*/jsxRuntimeExports.jsxs(fuselage.Callout, {
            title: t('screenSharing.permissionDenied'),
            type: "danger",
            margin: "x32",
            children: [t('screenSharing.permissionRequired'), /*#__PURE__*/jsxRuntimeExports.jsx("br", {}), t('screenSharing.permissionInstructions'), ' ', /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Box, {
              is: "a",
              href: "#",
              onClick: e => {
                e.preventDefault();
                const url = process.platform === 'darwin' ? 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture' : 'ms-settings:privacy-screencapture';
                electron.ipcRenderer.invoke(openUrlChannel, url);
              },
              style: {
                color: 'inherit',
                textDecoration: 'underline',
                cursor: 'pointer'
              },
              children: t('screenSharing.openSystemPreferences')
            })]
          }) : /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Scrollable, {
            vertical: true,
            children: /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Box, {
              padding: "x8",
              style: {
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fit, 208px)',
                gap: '16px',
                justifyContent: 'center'
              },
              children: filteredSources.length === 0 ? /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Box, {
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                width: "100%",
                p: "x16",
                style: {
                  gridColumn: '1 / -1'
                },
                children: /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Label, {
                  children: currentTab === 'screen' ? t('screenSharing.noScreensFound') : t('screenSharing.noWindowsFound')
                })
              }) : filteredSources.map(({
                id,
                name,
                thumbnail
              }) => /*#__PURE__*/jsxRuntimeExports.jsxs(fuselage.Box, {
                width: "x208",
                height: "x170",
                display: "flex",
                flexDirection: "column",
                onClick: handleScreenSharingSourceClick(id),
                bg: selectedSourceId === id ? 'selected' : 'light',
                border: selectedSourceId === id ? '2px solid var(--rcx-color-stroke-highlight)' : '1px solid var(--rcx-color-stroke-light)',
                borderRadius: "x2",
                cursor: "pointer",
                className: "screen-share-thumbnail",
                style: {
                  position: 'relative',
                  overflow: 'visible'
                },
                children: [/*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Box, {
                  flexGrow: 1,
                  display: "flex",
                  alignItems: "flex-start",
                  justifyContent: "flex-start",
                  overflow: "hidden",
                  style: {
                    minHeight: '120px',
                    backgroundColor: 'rgba(0, 0, 0, 0.1)'
                  },
                  children: /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Box, {
                    is: "img",
                    src: thumbnail.toDataURL(),
                    alt: name,
                    style: {
                      width: '100%',
                      height: 'auto',
                      objectFit: 'contain',
                      objectPosition: 'top',
                      display: 'block'
                    }
                  })
                }), /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Box, {
                  p: "x4",
                  style: {
                    position: 'absolute',
                    bottom: '0',
                    left: '0',
                    right: '0',
                    background: 'rgba(0, 0, 0, 0.5)',
                    backdropFilter: 'blur(4px)',
                    zIndex: 10,
                    minHeight: 'auto'
                  },
                  children: /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Label, {
                    title: name,
                    style: {
                      fontSize: '11px',
                      lineHeight: '1.2',
                      color: 'white',
                      textAlign: 'center',
                      width: '100%',
                      margin: 0,
                      wordBreak: 'break-word',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis'
                    },
                    children: name
                  })
                })]
              }, id))
            })
          })
        }), /*#__PURE__*/jsxRuntimeExports.jsxs(fuselage.Box, {
          display: "flex",
          justifyContent: "space-between",
          marginBlockStart: "auto",
          children: [/*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Button, {
            onClick: handleClose,
            children: t('screenSharing.cancel')
          }), /*#__PURE__*/jsxRuntimeExports.jsx(fuselage.Button, {
            primary: true,
            onClick: handleShare,
            disabled: !selectedSourceId,
            children: t('screenSharing.share')
          })]
        })]
      })
    })]
  });
}

let reactRoot = null;
let setVisibleCallback = null;
let shouldShowOnMount = false;
const mount = () => {
  const container = document.getElementById('screen-picker-root');
  if (!container) {
    console.error('Screen picker root container not found');
    return;
  }
  if (reactRoot) {
    return;
  }
  try {
    reactRoot = createRoot(container);
    reactRoot.render(/*#__PURE__*/jsxRuntimeExports.jsx(reactI18next.I18nextProvider, {
      i18n: i18next__default.default,
      children: /*#__PURE__*/jsxRuntimeExports.jsx(ScreenSharePicker, {
        onMounted: setVisible => {
          setVisibleCallback = setVisible;
          if (shouldShowOnMount) {
            setVisible(true);
            shouldShowOnMount = false;
          }
        }
      })
    }));
    if ("production" === 'development') ;
  } catch (error) {
    console.error('Failed to mount screen share picker:', error);
    reactRoot = null;
    setVisibleCallback = null;
    shouldShowOnMount = false;
  }
};
const show = () => {
  if (!reactRoot) {
    // Set flag BEFORE mounting so onMounted callback can see it during render
    shouldShowOnMount = true;
    mount();
    return;
  }
  if (setVisibleCallback) {
    setVisibleCallback(true);
  } else {
    shouldShowOnMount = true;
    setTimeout(() => {
      if (setVisibleCallback) {
        setVisibleCallback(true);
      }
      shouldShowOnMount = false;
    }, 0);
  }
};

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