'use strict';

var RCV = require('@progress/telerik-common-report-viewer');
var utils = require('./utils.js');
var stringResources = require('./stringResources.js');
var history = require('./history.js');
var binder = require('./binder.js');
var commandSet = require('./commandSet.js');
var uiController = require('./uiController.js');
var accessibility = require('./accessibility.js');
var documentMapArea = require('./documentMapArea.js');
var parametersArea = require('./parametersArea.js');
var search = require('./search.js');
var sendEmail = require('./sendEmail.js');
var events = require('./events.js');
var perspectives = require('./perspectives.js');
var enums = require('./enums.js');
var notificationService = require('./notificationService.js');
var memStorage = require('./mem-storage.js');
var templateCache = require('./template-cache.js');
var reportViewerSettings = require('./report-viewer/report-viewer-settings.js');
var linkButton = require('./toolbar/link-button.js');
var pageNumberInput = require('./toolbar/page-number-input.js');
var pageCountLabel = require('./toolbar/page-count-label.js');
var touch = require('./touch.js');
var toolbar = require('./toolbar.js');
var aiPrompt = require('./aiPrompt.js');

function _interopNamespaceDefault(e) {
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n.default = e;
    return Object.freeze(n);
}

var RCV__namespace = /*#__PURE__*/_interopNamespaceDefault(RCV);

var viewModeReverseMap = {
  [RCV__namespace.ViewMode.Interactive]: enums.ViewModes.INTERACTIVE,
  [RCV__namespace.ViewMode.PrintPreview]: enums.ViewModes.PRINT_PREVIEW
};
var viewModeMap = {
  [enums.ViewModes.INTERACTIVE]: RCV__namespace.ViewMode.Interactive,
  [enums.ViewModes.PRINT_PREVIEW]: RCV__namespace.ViewMode.PrintPreview
};
var pageModeReverseMap = {
  [RCV__namespace.PageMode.SinglePage]: enums.PageModes.SINGLE_PAGE,
  [RCV__namespace.PageMode.ContinuousScroll]: enums.PageModes.CONTINUOUS_SCROLL
};
var pageModeMap = {
  [enums.PageModes.SINGLE_PAGE]: RCV__namespace.PageMode.SinglePage,
  [enums.PageModes.CONTINUOUS_SCROLL]: RCV__namespace.PageMode.ContinuousScroll
};
var scaleModeReverseMap = {
  [RCV__namespace.ScaleMode.FitPageWidth]: enums.ScaleModes.FIT_PAGE_WIDTH,
  [RCV__namespace.ScaleMode.FitPage]: enums.ScaleModes.FIT_PAGE,
  [RCV__namespace.ScaleMode.Specific]: enums.ScaleModes.SPECIFIC
};
var scaleModeMap = {
  [enums.ScaleModes.FIT_PAGE_WIDTH]: RCV__namespace.ScaleMode.FitPageWidth,
  [enums.ScaleModes.FIT_PAGE]: RCV__namespace.ScaleMode.FitPage,
  [enums.ScaleModes.SPECIFIC]: RCV__namespace.ScaleMode.Specific
};
var printModeReverseMap = {
  [RCV__namespace.PrintMode.AutoSelect]: enums.PrintModes.AUTO_SELECT,
  [RCV__namespace.PrintMode.ForcePDFPlugin]: enums.PrintModes.FORCE_PDF_PLUGIN,
  [RCV__namespace.PrintMode.ForcePDFFile]: enums.PrintModes.FORCE_PDF_FILE
};
var printModeMap = {
  [enums.PrintModes.AUTO_SELECT]: RCV__namespace.PrintMode.AutoSelect,
  [enums.PrintModes.FORCE_PDF_PLUGIN]: RCV__namespace.PrintMode.ForcePDFPlugin,
  [enums.PrintModes.FORCE_PDF_FILE]: RCV__namespace.PrintMode.ForcePDFFile
};
var commonMessages = parseMessages();
var TOOLIP_SHOW_TIMEOUT = 100;
function parseMessages() {
  var result = {};
  Object.keys(stringResources.stringResources).forEach((key) => {
    let firstLetter = key.charAt(0).toUpperCase();
    result[`ReportViewer_${firstLetter}${key.slice(1)}`] = stringResources.stringResources[key];
  });
  return result;
}
function getDefaultOptions(serviceUrl, version) {
  return {
    id: null,
    serviceUrl: null,
    templateUrl: utils.rTrim(serviceUrl, "\\/") + "/resources/templates/telerikReportViewerTemplate-" + version + ".html/",
    reportSource: null,
    reportServer: null,
    authenticationToken: null,
    sendEmail: null,
    scale: 1,
    scaleMode: enums.ScaleModes.SPECIFIC,
    viewMode: enums.ViewModes.INTERACTIVE,
    pageMode: enums.PageModes.CONTINUOUS_SCROLL,
    parametersAreaPosition: enums.ParametersAreaPositions.RIGHT,
    documentMapAreaPosition: enums.DocumentMapAreaPositions.LEFT,
    parameters: {
      editors: {
        multiSelect: enums.ParameterEditorTypes.LIST_VIEW,
        singleSelect: enums.ParameterEditorTypes.LIST_VIEW
      }
    },
    persistSession: false,
    parameterEditors: [],
    disabledButtonClass: null,
    checkedButtonClass: null,
    parametersAreaVisible: true,
    documentMapVisible: true,
    enableAccessibility: false,
    searchMetadataOnDemand: false,
    initialPageAreaImageUrl: null,
    keepClientAlive: true,
    webDesignerPreview: false,
    serverPreview: false
  };
}
function ReportViewer(dom, options) {
  var svcApiUrl = options.serviceUrl;
  var reportServerUrlSVCApiUrl = "";
  if (options.reportServer) {
    reportServerUrlSVCApiUrl = utils.rTrim(options.reportServer.url, "\\/");
    svcApiUrl = reportServerUrlSVCApiUrl + "/api/reports";
  }
  var $placeholder = $(dom);
  var templates = {};
  var persistanceKey = options.id || "#" + $placeholder.attr("id");
  var accessibility$1;
  var settings = {};
  var notificationService$1 = {};
  var client = {};
  var controller = {};
  var perspectiveManager;
  var history$1 = {};
  var commands = {};
  var viewer = {};
  options.viewerSelector = "reportViewer-" + utils.generateGuidString();
  $placeholder.attr("data-selector", options.viewerSelector);
  if (!validateOptions(options)) {
    return;
  }
  var version = "20.0.26.211";
  options = $.extend({}, getDefaultOptions(svcApiUrl, version), options);
  settings = new reportViewerSettings.ReportViewerSettings(
    persistanceKey,
    options.persistSession ? window.sessionStorage : new memStorage.MemStorage(),
    {
      scale: options.scale,
      scaleMode: options.scaleMode,
      printMode: options.printMode ? options.printMode : options.directPrint,
      enableAccessibility: options.enableAccessibility,
      searchMetadataOnDemand: options.searchMetadataOnDemand,
      sendEmail: options.sendEmail,
      parametersAreaPosition: options.parametersAreaPosition,
      documentMapAreaPosition: options.documentMapAreaPosition,
      keepClientAlive: options.keepClientAlive,
      webDesignerPreview: options.webDesignerPreview,
      serverPreview: options.serverPreview
    }
  );
  notificationService$1 = new notificationService.NotificationService();
  client = new RCV__namespace.ServiceClient(options);
  controller = new RCV__namespace.ReportController(
    client,
    new RCV__namespace.ReportControllerOptions(
      options.keepClientAlive,
      options.authenticationToken,
      options.reportSource,
      printModeMap[options.printMode],
      pageModeMap[options.pageMode],
      viewModeMap[options.viewMode],
      scaleModeMap[options.scaleMode],
      options.scale,
      commonMessages,
      options.enableAccessibility,
      options.searchMetadataOnDemand
    )
  );
  history$1 = new history.HistoryManager({
    controller,
    settings
  });
  commands = new commandSet.CommandSet({
    controller,
    notificationService: notificationService$1,
    history: history$1
  });
  new uiController.UIController({
    controller,
    notificationService: notificationService$1,
    history: history$1,
    commands
  });
  viewer = {
    /**
     * String resources used by the viewer for localization and UI text.
     * Contains key-value pairs for all UI strings, supporting localization and customization.
     * @type {Object.<string, string>}
     */
    stringResources: stringResources.stringResources,
    /**
     * Refreshes the currently loaded report.
     * Forces the viewer to reload the report from the server. Optionally ignores the cache.
     * @function
     * @param {boolean} [ignoreCache=true] - If true, the report is reloaded from the server, bypassing any cached data.
     * @returns {ReportViewerInstance} Returns the viewer instance for chaining.
     * @example // Refresh the report, ignoring cache (default)
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.refreshReport();
     * @example // Refresh the report, using cache if available
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.refreshReport(false);
     */
    refreshReport: (ignoreCache) => {
      if (arguments.length === 0) {
        ignoreCache = true;
      }
      controller.refreshReport(ignoreCache, "", true);
      return viewer;
    },
    /**
     * Gets or sets the report source for the viewer.
     * When called with an argument, sets the report source
     * When called without arguments, gets the current report source - report and parameters. The viewer's report source is updated dynamically as the users navigate between reports and change parameter values.
     * @function
     * @param {ReportSource|null} [rs] - The report source object to set, or null to clear. If omitted, acts as a getter.
     * @returns {ReportSource} Returns the viewer instance for chaining when setting, or the current report source when getting.
     * @example // Get the current report source
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var currentSource = viewer.reportSource();
     * @example // Set a new report source
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.reportSource({
     *   report: "MyReport",
     *   parameters: { StartDate: "2024-01-01", EndDate: "2024-12-31" }
     * });
     * @example // Clear the report source
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.reportSource(null);
     */
    reportSource: (rs) => {
      if (rs || rs === null) {
        controller.setReportSource(rs);
        controller.refreshReport(false, "", true);
        return viewer;
      }
      return controller.getReportSource();
    },
    /**
     * Clears the current reportSource from the viewer's internal state and its persisted session in the browser.
     * Called in order to force the viewer to respect the newly set reportSource on a server postback.
     * @function
     * @returns {ReportViewerInstance} Returns the viewer instance for chaining.
     * @example // Clear the report source and force the viewer to respect a new reportSource on postback
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.clearReportSource();
     */
    clearReportSource: () => {
      controller.setReportSource(new RCV__namespace.ReportSourceOptions());
      return viewer;
    },
    /**
     * Gets or sets the view mode of the viewer (e.g., Interactive or Print Preview).
     * @function
     * @param {ViewModes} [vm] - The view mode to set. If omitted, returns the current view mode.
     * @returns {string} Returns the viewer instance for chaining when setting, or the current view mode string when getting.
     * @example // Get the current view mode
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var mode = viewer.viewMode();
     * @example // Set the view mode to Print Preview
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.viewMode(telerikReportViewer.ViewModes.PRINT_PREVIEW);
     */
    viewMode: (vm) => {
      if (vm) {
        controller.setViewMode(viewModeMap[vm]);
        return viewer;
      }
      return viewModeReverseMap[controller.getViewMode()];
    },
    /**
     * Gets or sets the page mode (e.g., Single Page or Continuous Scroll).
     * @function
     * @param {PageModes} [psm] - The page mode to set. If omitted, returns the current page mode.
     * @returns {string} Returns the viewer instance for chaining when setting, or the current page mode string when getting.
     * @example // Get the current page mode
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var pageMode = viewer.pageMode();
     * @example // Set the page mode to Single Page
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.pageMode(telerikReportViewer.PageModes.SINGLE_PAGE);
     */
    pageMode: (psm) => {
      if (psm) {
        controller.setPageMode(pageModeMap[psm]);
        return viewer;
      }
      return pageModeReverseMap[controller.getPageMode()];
    },
    /**
     * Gets or sets the print mode for the viewer.
     * @function
     * @param {PrintModes} [pm] - The print mode to set. If omitted, returns the current print mode.
     * @returns {string} Returns the viewer instance for chaining when setting, or the current print mode string when getting.
     * @example // Get the current print mode
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var printMode = viewer.printMode();
     * @example // Set the print mode to Force PDF File
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.printMode(telerikReportViewer.PrintModes.FORCE_PDF_FILE);
     */
    printMode: (pm) => {
      if (pm) {
        controller.setPrintMode(printModeMap[pm]);
        return viewer;
      }
      return printModeReverseMap[controller.getPrintMode()];
    },
    /**
     * Gets or sets the scale and scale mode for the viewer.
     * @function
     * @param {Object} [args] - The scale settings to apply. Should contain 'scale' (number) and 'scaleMode' (string).
     * @param {number} [args.scale] - The zoom scale (e.g., 1.0 for 100%).
     * @param {ScaleModes} [args.scaleMode] - The scale mode (e.g., 'FIT_PAGE', 'FIT_PAGE_WIDTH', 'SPECIFIC').
     * @returns {Object} Returns the viewer instance for chaining when setting, or an object with current scale and scaleMode when getting.
     * @example // Get the current scale and scale mode
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var scaleInfo = viewer.scale();
     * @example // Set scale to 1.2 and scale mode to FIT_PAGE_WIDTH
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.scale({ scale: 1.2, scaleMode: telerikReportViewer.ScaleModes.FIT_PAGE_WIDTH });
     */
    scale: (args) => {
      if (args) {
        controller.setScale(args.scale);
        controller.setScaleMode(scaleModeMap[args.scaleMode]);
        return viewer;
      }
      return {
        scale: controller.getScale(),
        scaleMode: scaleModeReverseMap[controller.getScaleMode()]
      };
    },
    /**
     * Gets the viewer’s current page that is displayed.
     * @function
     * @returns {number} The current page number (1-based).
     * @example // Get the current page number
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var page = viewer.currentPage();
     */
    currentPage: () => {
      return controller.getCurrentPageNumber();
    },
    /**
     * Gets the total page count of the viewer’s currently displayed report.
     * @function
     * @returns {number} The total page count.
     * @example // Get the total number of pages in the current report
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var totalPages = viewer.pageCount();
     */
    pageCount: () => {
      return controller.getPageCount();
    },
    /**
     * Shows or hides the parameters area in the viewer UI.
     * @function
     * @param {boolean} visible - True to show, false to hide the parameters area.
     * @returns {void}
     * @example // Show the parameters area
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.parametersAreaVisible(true);
     * @example // Hide the parameters area
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.parametersAreaVisible(false);
     */
    parametersAreaVisible: (visible) => {
      notificationService$1.setParametersAreaVisible({ visible });
    },
    /**
     * Returns an object with properties, the names of which are the report parameters’ IDs, and values - the report parameters’ values. The values of multivalue parameters include their display and value members.
     * @function
     * @returns {Array<Object>} An array of report parameter objects.
     * @example // Get all report parameters and log them
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var parameters = viewer.getReportParameters();
     * console.log(parameters);
     */
    getReportParameters: () => {
      return controller.getReportParameters();
    },
    /**
     * Returns whether auto-run is enabled for the report (i.e., whether the report runs automatically when parameters change).
     * @function
     * @returns {boolean} True if auto-run is enabled, false otherwise.
     * @example // Check if auto-run is enabled for the report
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var isReportAutoRun = viewer.isReportAutoRun();
     */
    isReportAutoRun: () => {
      return controller.autoRunEnabled;
    },
    /**
     * Sets the authentication token. Used for service requests.
     * @function
     * @param {string} [token] - The authentication token to set.
     * @returns {ReportViewerInstance} Returns the viewer instance for chaining.
     * @example // Set the authentication token for the viewer
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.authenticationToken("YOUR_AUTH_TOKEN");
     */
    authenticationToken: (token) => {
      if (token) {
        controller.setAuthenticationToken(token);
      }
      return viewer;
    },
    /**
     * Binds event handlers to the specified event.
     * @function
     * @param {string} eventName - The name of the event to bind to (see Events constants).
     * @param {function} eventHandler - The handler function to invoke when the event occurs.
     * @returns {void}
     * @example // Bind to the 'pageReady' event
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.bind(telerikReportViewer.Events.PAGE_READY, function(e, args) {
     *   console.log("Page is ready!", args);
     * });
     * @example // Bind to the 'error' event
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.bind(telerikReportViewer.Events.ERROR, function(e, args) {
     *   alert("An error occurred: " + args);
     * });
     */
    bind: (eventName, eventHandler) => {
      eventBinder(eventName, eventHandler, true);
    },
    /**
     * Unbinds an event handler from a viewer event.
     * @function
     * @param {string} eventName - The name of the event to unbind from.
     * @param {function} [eventHandler] - The handler function to remove. If omitted, all handlers for the event are removed.
     * @returns {void}
     * @example // Unbind all handlers from the 'error' event
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.unbind(telerikReportViewer.Events.ERROR);
     */
    unbind: (eventName, eventHandler) => {
      eventBinder(eventName, eventHandler, false);
    },
    /**
     * Gets or sets the accessibility key map for keyboard navigation.
     * Allows customization of keyboard shortcuts for accessibility features.
     * @function
     * @param {Object} [keyMap] - The key map object to set. If omitted, acts as a getter.
     * @returns {Object} Returns the viewer instance for chaining when setting, the current key map when getting, or undefined if accessibility is not enabled.
     * @example // Get the current accessibility key map
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * var keyMap = viewer.accessibilityKeyMap();
     *
     * @example // Set a custom accessibility key map
     * var reportViewer = $("#reportViewer1").data("telerik_ReportViewer");
     * reportViewer.accessibilityKeyMap(
     * {
     *     CONFIRM_KEY: 32,
     *     CONTENT_AREA_KEY: 82, //R
     *     DOCUMENT_MAP_AREA_KEY: 77, //M
     *     MENU_AREA_KEY: 85, //U
     *     PARAMETERS_AREA_KEY: 80 //P
     * });
     */
    accessibilityKeyMap: (keyMap) => {
      if (accessibility$1) {
        if (keyMap) {
          accessibility$1.setKeyMap(keyMap);
          return viewer;
        }
        return accessibility$1.getKeyMap();
      }
      return void 0;
    },
    /**
     * The command set for the viewer, providing programmatic access to built-in commands (e.g., navigation, export).
     * @type {ReportViewerCommands}
     */
    commands,
    /**
     * Disposes the viewer instance, cleaning up resources and event handlers.
     * After calling this method, the viewer instance should not be used.
     * Stops sending keep alive requests to the server, if keep client alive was enabled.
     * @function
     * @returns {void}
     * @example
     *  // Dispose the viewer instance when it is no longer needed
     * var viewer = $("#reportViewer1").data("telerik_ReportViewer");
     * viewer.dispose();
     */
    dispose: () => {
      clearTooltipTimeout();
      controller.disposeSentinel();
      controller.destroy();
      if (perspectiveManager && typeof perspectiveManager.dispose === "function") {
        perspectiveManager.dispose();
      }
    }
  };
  function validateOptions(options2) {
    if (!options2) {
      $placeholder.text("The report viewer configuration options are not initialized.");
      return false;
    }
    if (options2.reportServer) {
      if (!options2.reportServer.url) {
        $placeholder.text("The report server URL is not specified.");
        return false;
      }
    } else {
      if (!options2.serviceUrl) {
        $placeholder.text("The serviceUrl is not specified.");
        return false;
      }
    }
    return true;
  }
  function eventBinder(eventName, eventHandler, bind) {
    if (typeof eventHandler === "function") {
      if (bind) {
        $(viewer).on(eventName, { sender: viewer }, eventHandler);
      } else {
        $(viewer).off(eventName, eventHandler);
      }
    } else if (!eventHandler && !bind) {
      $(viewer).off(eventName);
    }
  }
  function attachEvents() {
    const viewerEventsMapping = {
      [events.Events.EXPORT_BEGIN]: "exportStarted",
      [events.Events.EXPORT_END]: "exportDocumentReady",
      [events.Events.PRINT_BEGIN]: "printStarted",
      [events.Events.PRINT_END]: "printDocumentReady",
      [events.Events.SEND_EMAIL_BEGIN]: "sendEmailStarted",
      [events.Events.SEND_EMAIL_END]: "sendEmailDocumentReady",
      [events.Events.PAGE_READY]: "pageReady",
      [events.Events.ERROR]: "error",
      [events.Events.INTERACTIVE_ACTION_EXECUTING]: "interactiveActionExecuting",
      [events.Events.INTERACTIVE_ACTION_ENTER]: "interactiveActionEnter",
      [events.Events.INTERACTIVE_ACTION_LEAVE]: "interactiveActionLeave",
      [events.Events.PARAMETERS_LOADED]: "parametersLoaded"
      // UPDATE_UI, // Raised below by notificationService
      // VIEWER_TOOLTIP_OPENING // Raised in showTooltip() method
    };
    var viewerAsyncEventsMapping = {
      [events.Events.RENDERING_BEGIN]: "beforeLoadReport",
      [events.Events.RENDERING_END]: "reportLoadComplete"
    };
    var $viewer = $(viewer);
    const eventProxy = (eventName) => async (args) => {
      $viewer.trigger(
        {
          type: eventName,
          data: { sender: viewer }
        },
        args
      );
    };
    for (let eventName in viewerEventsMapping) {
      let controllerEventName = viewerEventsMapping[eventName];
      controller.on(controllerEventName, (args) => {
        if (eventName === events.Events.PAGE_READY) {
          args.pageActions = JSON.stringify(args.pageActions);
        }
        eventProxy(eventName)(args);
      });
    }
    for (let eventName in viewerAsyncEventsMapping) {
      let controllerEventName = viewerAsyncEventsMapping[eventName];
      controller.onAsync(controllerEventName, eventProxy(eventName));
    }
    notificationService$1.on(notificationService$1.Events.UPDATE_UI, function($viewer2) {
      return function(e, args) {
        $viewer2.trigger(
          {
            type: events.Events.UPDATE_UI,
            data: e.data
          },
          args
        );
      };
    }($viewer));
  }
  function attachEventHandlers() {
    eventBinder(events.Events.EXPORT_BEGIN, options.exportBegin, true);
    eventBinder(events.Events.EXPORT_END, options.exportEnd, true);
    eventBinder(events.Events.PRINT_BEGIN, options.printBegin, true);
    eventBinder(events.Events.PRINT_END, options.printEnd, true);
    eventBinder(events.Events.SEND_EMAIL_BEGIN, options.sendEmailBegin, true);
    eventBinder(events.Events.SEND_EMAIL_END, options.sendEmailEnd, true);
    eventBinder(events.Events.RENDERING_BEGIN, options.renderingBegin, true);
    eventBinder(events.Events.RENDERING_END, options.renderingEnd, true);
    eventBinder(events.Events.PAGE_READY, options.pageReady, true);
    eventBinder(events.Events.ERROR, options.error, true);
    eventBinder(events.Events.UPDATE_UI, options.updateUi, true);
    eventBinder(events.Events.INTERACTIVE_ACTION_EXECUTING, options.interactiveActionExecuting, true);
    eventBinder(events.Events.INTERACTIVE_ACTION_ENTER, options.interactiveActionEnter, true);
    eventBinder(events.Events.INTERACTIVE_ACTION_LEAVE, options.interactiveActionLeave, true);
    eventBinder(events.Events.VIEWER_TOOLTIP_OPENING, options.viewerToolTipOpening, true);
    eventBinder(events.Events.PARAMETERS_LOADED, options.parametersLoaded, true);
  }
  function init() {
    $placeholder.html(templates["trv-report-viewer"]);
    binder.Binder.bind(
      $placeholder,
      {
        controller,
        notificationService: notificationService$1,
        commands,
        templates
      },
      options
    );
    new RCV__namespace.ContentArea($placeholder[0], controller, commonMessages, {
      enableAccessibility: options.enableAccessibility,
      initialPageAreaImageUrl: options.initialPageAreaImageUrl
    });
    perspectiveManager = new perspectives.PerspectiveManager(dom, controller, notificationService$1);
    perspectiveManager.attach();
    enableTouch($placeholder.find(".trv-page-container"));
    initSplitter();
    attachEvents();
    attachEventHandlers();
    initFromStorage();
    initAccessibility(options);
  }
  function enableTouch(dom2) {
    var allowSwipeLeft;
    var allowSwipeRight;
    function isMobileDevice() {
      return /Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini|Windows Phone/i.test(navigator.userAgent) || /Macintosh/i.test(navigator.userAgent) && navigator.maxTouchPoints && navigator.maxTouchPoints > 0;
    }
    touch.TouchBehavior(
      dom2,
      {
        swipe: function(e) {
          var pageNumber = controller.getCurrentPageNumber();
          if (allowSwipeLeft && e.direction === "left") {
            if (pageNumber < controller.getPageCount()) {
              controller.navigateToPage(pageNumber + 1);
            }
          } else if (allowSwipeRight && e.direction === "right") {
            if (pageNumber > 1) {
              controller.navigateToPage(pageNumber - 1);
            }
          }
        },
        pinch: function(e) {
          var scale = controller.getScale();
          var f = e.distance / e.lastDistance;
          controller.setScaleMode(RCV__namespace.ScaleMode.Specific);
          controller.setScale(scale * f);
        },
        doubletap: function() {
          if (isMobileDevice()) {
            commands.toggleZoomMode.exec();
          }
        },
        touchstart: function() {
          var el = dom2.find(".trv-page-wrapper")[0];
          allowSwipeRight = 0 === el.scrollLeft;
          allowSwipeLeft = el.scrollWidth - el.offsetWidth === el.scrollLeft;
        }
      }
    );
  }
  function initSplitter() {
    var parameterAreaPaneOptions = {
      max: "500px",
      min: "50px",
      size: "300",
      collapsible: true,
      scrollable: false
    };
    var parameterAreaTemplate = $placeholder.find(".trv-parameters-area");
    var parameterAreaPanes = [{}];
    var documentMapPaneOptions = {
      max: "500px",
      min: "50px",
      size: "300",
      collapsible: true,
      collapsed: true,
      scrollable: false
    };
    var documentMapTemplate = $placeholder.find(".trv-document-map");
    var documentMapPanes = [{}];
    var orientation = "horizontal";
    if (options.documentMapAreaPosition === enums.DocumentMapAreaPositions.RIGHT) {
      documentMapTemplate.insertAfter($placeholder.find(".trv-pages-area"));
      documentMapPanes.push(documentMapPaneOptions);
    } else {
      documentMapPanes.unshift(documentMapPaneOptions);
    }
    if (options.parametersAreaPosition === enums.ParametersAreaPositions.TOP || options.parametersAreaPosition === enums.ParametersAreaPositions.BOTTOM) {
      orientation = "vertical";
      parameterAreaTemplate.addClass("-vertical");
      parameterAreaPaneOptions.size = "130px";
    }
    if (options.parametersAreaPosition === enums.ParametersAreaPositions.LEFT || options.parametersAreaPosition === enums.ParametersAreaPositions.TOP) {
      parameterAreaTemplate.insertBefore($placeholder.find(".trv-document-map-splitter"));
      parameterAreaPanes.unshift(parameterAreaPaneOptions);
    } else {
      parameterAreaPanes.push(parameterAreaPaneOptions);
    }
    try {
      $placeholder.find(".trv-document-map-splitter").attr("id", options.viewerSelector + "-document-map-splitter").kendoSplitter({
        panes: documentMapPanes,
        expand: (e) => {
          setSplitterPaneVisibility(e.pane, true);
        },
        collapse: (e) => {
          setSplitterPaneVisibility(e.pane, false);
        },
        resize: (e) => {
        }
      }).data("kendoSplitter");
    } catch (e) {
      console.error("Instantiation of Kendo Splitter as Document Map splitter threw an exception", e);
      throw e;
    }
    try {
      $placeholder.find(".trv-parameters-splitter").attr("id", options.viewerSelector + "-parameters-splitter").kendoSplitter({
        panes: parameterAreaPanes,
        orientation,
        expand: (e) => {
          setSplitterPaneVisibility(e.pane, true);
        },
        collapse: (e) => {
          setSplitterPaneVisibility(e.pane, false);
        },
        resize: (e) => {
        }
      }).data("kendoSplitter");
    } catch (e) {
      console.error("Instantiation of Kendo Splitter as Parameters area splitter threw an exception", e);
      throw e;
    }
  }
  function setSplitterPaneVisibility(pane, visible) {
    var paneID = $(pane).attr("data-id");
    switch (paneID) {
      case "trv-document-map":
        notificationService$1.setDocumentMapVisible({
          visible
        });
        break;
      case "trv-parameters-area":
        notificationService$1.setParametersAreaVisible({
          visible
        });
        break;
    }
  }
  function initFromStorage() {
    var vm = settings.getViewMode();
    var psm = settings.getPageMode();
    var pm = settings.getPrintMode();
    var s = settings.getScale();
    var sm = settings.getScaleMode();
    var dm = settings.getDocumentMapVisible();
    var pa = settings.getParametersAreaVisible();
    settings.getAccessibilityKeyMap();
    controller.setViewMode(viewModeMap[vm ? vm : options.viewMode]);
    controller.setPageMode(pageModeMap[psm ? psm : options.pageMode]);
    controller.setPrintMode(printModeMap[pm ? pm : options.printMode]);
    controller.setScaleMode(scaleModeMap[sm ? sm : options.scaleMode]);
    controller.setScale(s ? s : options.scale);
    notificationService$1.setDocumentMapVisible({
      visible: dm ? dm : options.documentMapVisible
    });
    notificationService$1.setParametersAreaVisible({
      visible: pa ? pa : options.parametersAreaVisible
    });
    controller.on("viewModeChanged", () => {
      settings.setViewMode(viewModeReverseMap[controller.getViewMode()]);
    }).on("pageModeChanged", () => {
      settings.setPageMode(pageModeReverseMap[controller.getPageMode()]);
    }).on("printModeChanged", () => {
      settings.setPrintMode(printModeReverseMap[controller.getPrintMode()]);
    }).on("scaleModeChanged", (scaleMode) => {
      settings.setScaleMode(scaleModeReverseMap[scaleMode]);
    }).on("scaleChanged", (scale) => {
      settings.setScale(scale);
    }).on("clientIdChanged", (clientId) => {
      settings.setClientId(clientId);
    }).on("currentPageChanged", (args) => {
      settings.setPageNumber(args.page);
    }).on("reportSourceChanged", (rs) => {
      settings.setReportSource(rs);
    });
    notificationService$1.setDocumentMapVisible(() => {
      var args = {};
      notificationService$1.getDocumentMapState(args);
      settings.setDocumentMapVisible(args.visible);
    });
    notificationService$1.setParametersAreaVisible(() => {
      var args = {};
      notificationService$1.getParametersAreaState(args);
      settings.setParametersAreaVisible(args.visible);
    });
  }
  function initAccessibility(options2) {
    if (options2.enableAccessibility) {
      accessibility$1 = new accessibility.Accessibility({
        controller,
        notificationService: notificationService$1,
        templates
      });
      var am = options2.accessibilityKeyMap;
      if (am) {
        accessibility$1.setKeyMap(am);
      }
      controller.setContentTabIndex(getTemplateContentTabIndex());
    }
  }
  function getTemplateContentTabIndex() {
    var pageAreaSelector = "div.trv-pages-area";
    try {
      var $pagesArea = $placeholder.find(pageAreaSelector);
      if ($pagesArea.length === 0) {
        throw "Selector " + pageAreaSelector + " did not return a result.";
      }
      return parseInt($pagesArea.attr("tabindex"));
    } catch (e) {
      if (console)
        console.log(e);
      return 0;
    }
  }
  function start() {
    var pendingRefresh = false;
    init();
    if (!(options.webDesignerPreview || options.serverPreview)) {
      if (controller.shouldShowLicenseBanner()) {
        $(".trv-content-wrapper")?.prepend('<span class="trv-license-banner"></span>');
        const licenseBanner = $(".trv-license-banner").kendoNotification({
          appendTo: ".trv-license-banner",
          hideOnClick: false,
          autoHideAfter: 0,
          button: true,
          hide: () => {
            controller.saveToSessionStorage("hideBanner", "true");
          }
        }).data("kendoNotification");
        const licenseData = controller.getConfigurationInfo()?.license;
        licenseBanner.show(`<span class='trv-license-message'>${licenseData?.title || licenseData?.message} ${licenseData?.actionMessage}</span>
                                    <a class='trv-license-link' target='_blank' href='${licenseData?.actionLink}'>
                                        <span class='k-icon k-i-question-circle'></span>
                                    </a>`, "warning");
      }
      if (controller.shouldShowLicenseOverlay()) {
        $(".trv-content-wrapper")?.prepend('<div class="trv-license-overlay"></div>');
      }
    }
    controller.onAsync("reportLoadComplete", async () => {
      if (options.documentMapVisible === false) {
        notificationService$1.setDocumentMapVisible({ visible: false });
      }
    }).on("navigateToReport", (args) => {
      controller.setReportSource(args);
      controller.refreshReport(false);
    }).on("toolTipOpening", (args) => {
      showTooltip(args);
    }).on("toolTipClosing", (args) => {
      hideTooltip(args);
    });
    var rs = settings.getReportSource();
    if (rs !== void 0) {
      controller.setReportSource(rs);
      var pageNumber = settings.getPageNumber();
      if (pageNumber !== void 0) {
        controller.navigateToPage(pageNumber);
      }
      pendingRefresh = true;
    } else {
      if (options.viewMode) {
        controller.setViewMode(viewModeMap[options.viewMode]);
      }
      if (options.pageMode) {
        controller.setPageMode(pageModeMap[options.pageMode]);
      }
      if (options.reportSource) {
        controller.setReportSource(options.reportSource);
        pendingRefresh = true;
      }
    }
    if (typeof options.ready === "function") {
      options.ready.call(viewer);
    }
    if (pendingRefresh) {
      controller.refreshReport(false, "", true);
    }
  }
  function showTooltip(args) {
    var $element = $(args.element);
    var toolTipArgs = {
      element: args.element,
      toolTip: {
        title: args.title,
        text: args.text
      },
      cancel: false
    };
    clearTooltipTimeout();
    $(viewer).trigger({ type: events.Events.VIEWER_TOOLTIP_OPENING }, toolTipArgs);
    if (toolTipArgs.cancel) {
      return;
    }
    var content = applyToolTipTemplate(toolTipArgs);
    var viewportElement = args.element.viewportElement;
    var ktt = getToolTip($element, content);
    viewer._tooltipShowTimeout = setTimeout(() => {
      ktt.show($element);
      if (viewportElement && viewportElement.nodeName === "svg") {
        positionToolTip(ktt, args);
      }
    }, TOOLIP_SHOW_TIMEOUT);
  }
  function hideTooltip(args) {
    var $t = $(args.element);
    var toolTip = $t.data("kendoTooltip");
    clearTooltipTimeout();
    if (toolTip) {
      toolTip.hide();
    }
  }
  function clearTooltipTimeout() {
    if (viewer._tooltipShowTimeout) {
      clearTimeout(viewer._tooltipShowTimeout);
      viewer._tooltipShowTimeout = null;
    }
  }
  function applyToolTipTemplate(toolTipArgs) {
    var toolTipTemplate = templates["trv-pages-area-kendo-tooltip"];
    var $container = $(toolTipTemplate);
    var $titleSpan = $container.find(".trv-pages-area-kendo-tooltip-title");
    var $textSpan = $container.find(".trv-pages-area-kendo-tooltip-text");
    $titleSpan.text(toolTipArgs.toolTip.title);
    $textSpan.text(toolTipArgs.toolTip.text);
    return $container.clone().wrap("<p>").parent().html();
  }
  function getToolTip(target, toolTipContent) {
    var ktt = target.data("kendoTooltip");
    if (!ktt) {
      try {
        ktt = target.kendoTooltip({
          content: toolTipContent,
          autohide: true,
          callout: true,
          position: "top"
        }).data("kendoTooltip");
      } catch (e) {
        console.error("Instantiation of Kendo Tooltip threw an exception", e);
        throw e;
      }
    }
    return ktt;
  }
  function positionToolTip(toolTip, e) {
    var x = e.pageX;
    var y = e.pageY;
    toolTip.popup.element.parent().css({
      left: x + 10,
      top: y + 5
    });
  }
  function loadStyleSheets(styleSheets) {
    if (!styleSheets)
      return Promise.resolve();
    var $head = $("head");
    var currentStyleLinks = $head.find("link").map((i, e) => {
      return e.outerHTML;
    }).toArray();
    var promises = [];
    Array.from(styleSheets).forEach((element) => {
      if (currentStyleLinks.indexOf(element) === -1) {
        promises.push(
          new Promise((resolve, reject) => {
            var $link = $(element);
            $link.on("load", resolve);
            $link.on("onerror", () => {
              utils.logError("error loading stylesheet " + element);
              resolve();
            });
            $head.append($link);
          })
        );
      }
    });
    return Promise.all(promises).then(notificationService$1.cssLoaded.bind(notificationService$1));
  }
  function browserSupportsAllFeatures() {
    return window.Promise;
  }
  function ensureKendo(version2) {
    if (window.kendo) {
      return Promise.resolve();
    }
    var kendoUrl = utils.rTrim(svcApiUrl, "\\/") + "/resources/js/telerikReportViewer.kendo-" + version2 + ".min.js/";
    return fetch(kendoUrl).then((response) => {
      if (!response.ok) {
        return Promise.reject({ error: "Failed to fetch data - status code " + response.status });
      }
      return response.text();
    }).then((kendoScript) => {
      const scriptElement = document.createElement("script");
      scriptElement.textContent = kendoScript;
      document.head.appendChild(scriptElement);
    }).catch((errorData) => {
      utils.logError("Kendo could not be loaded automatically. Make sure 'options.serviceUrl' / 'options.reportServer.url' is correct and accessible. The error is: " + errorData.error);
    });
  }
  function main(version2) {
    ensureKendo(version2).then(() => {
      viewer.authenticationToken(options.authenticationToken);
      controller.getServiceConfiguration().catch((ex) => {
        var errorOutput = utils.isApplicationExceptionInstance(ex) ? ex.exceptionMessage : utils.stringFormat(stringResources.stringResources.errorServiceUrl, [utils.escapeHtml(svcApiUrl)]);
        $placeholder.text(errorOutput);
        return Promise.reject(errorOutput);
      }).then((configurationInfo) => {
        controller.setConfigurationInfo(configurationInfo);
        if (configurationInfo.version !== version2) {
          var errorOutput = utils.stringFormat(stringResources.stringResources.errorServiceVersion, [configurationInfo.version, version2]);
          $placeholder.text(errorOutput);
          return Promise.reject(errorOutput);
        }
        templateCache.TemplateCache.load(options.templateUrl, svcApiUrl, client).catch(() => {
          var errorOutput2 = utils.stringFormat(stringResources.stringResources.errorLoadingTemplates, [utils.escapeHtml(options.templateUrl)]);
          $placeholder.text(errorOutput2);
          return Promise.reject(errorOutput2);
        }).then((result) => {
          templates = result.templates;
          return loadStyleSheets(result.styleSheets);
        }).then(start);
      }).catch((reason) => {
        $(viewer).trigger({
          type: events.Events.ERROR,
          data: { sender: viewer }
        }, reason);
      });
    });
  }
  if (browserSupportsAllFeatures()) {
    main(version);
  } else {
    throw "The current browser does not support the Promise feature which is required for using the Report Viewer.";
  }
  return viewer;
}
function ReportViewerServiceClient(serviceClientOptions) {
  return new RCV__namespace.ServiceClient(serviceClientOptions);
}
function ReportViewerController(controllerOptions) {
  return new RCV__namespace.ReportController(controllerOptions?.serviceClient, controllerOptions?.settings);
}
function ReportViewerNotificationService() {
  return new notificationService.NotificationService();
}
var pluginName = "telerik_ReportViewer";
$.fn[pluginName] = function(options) {
  if (this.selector && !options.selector) {
    options.selector = this.selector;
  }
  return this.each(function() {
    if (!$.data(this, pluginName)) {
      $.data(this, pluginName, new ReportViewer(this, options));
    }
  });
};
const plugins = [
  {
    name: "telerik_ReportViewer_DocumentMapArea",
    constructor: documentMapArea.DocumentMapArea
  },
  {
    name: "telerik_ReportViewer_ParametersArea",
    constructor: parametersArea.ParametersArea
  },
  {
    name: "telerik_ReportViewer_SearchDialog",
    constructor: search.Search
  },
  {
    name: "telerik_ReportViewer_SendEmail",
    constructor: sendEmail.SendEmail
  },
  {
    name: "telerik_ReportViewer_LinkButton",
    constructor: linkButton.LinkButton
  },
  {
    name: "telerik_ReportViewer_PageNumberInput",
    constructor: pageNumberInput.PageNumberInput
  },
  {
    name: "telerik_ReportViewer_PageCountLabel",
    constructor: pageCountLabel.PageCountLabel
  },
  {
    name: "telerik_ReportViewer_Toolbar",
    constructor: toolbar.Toolbar
  },
  {
    name: "telerik_ReportViewer_AiPromptDialog",
    constructor: aiPrompt.AiPrompt
  }
];
plugins.forEach((plugin) => {
  $.fn[plugin.name] = function(options, otherOptions) {
    return this.each(function() {
      if (!$.data(this, plugin.name)) {
        $.data(this, plugin.name, new plugin.constructor(this, options, otherOptions));
      }
    });
  };
});

exports.ReportViewer = ReportViewer;
exports.ReportViewerController = ReportViewerController;
exports.ReportViewerNotificationService = ReportViewerNotificationService;
exports.ReportViewerServiceClient = ReportViewerServiceClient;
