'use strict';

angular.module('sentinelConsoleApp').component('a3wPopover', {
  bindings: {
    /**
     * @ngdoc attribute
     * @name iconClass
     * @type {string}
     * @description
     * CSS class for the icon to be displayed in the popover.
     */
    iconClass: '@',

    /**
     * @ngdoc attribute
     * @name popoverHtmlContent
     * @type {string}
     * @description
     * HTML content to be displayed inside the popover. It will be HTML without Angular content.
     */
    popoverHtmlContent: '<',

    /**
     * @ngdoc attribute
     * @name position
     * @type {string}
     * @description
     * Popover position (e.g., 'top', 'right', 'bottom', 'left').
     */
    position: '@',

    /**
     * @ngdoc attribute
     * @name color
     * @type {string}
     * @description
     * Popover color
     */
    color: '@',

    /**
     * @ngdoc attribute
     * @name size
     * @type {string}
     * @description
     * Popover size
     */
    size: '@'
  },
  templateUrl: 'scripts/components/a3wPopover/a3wPopover.template.html',
  controller: function($timeout, $element) {
    var ctrl = this;

    /**
     * @ngdoc property
     * @name isPopoverVisible
     * @type {boolean}
     * @description
     * Indicates whether the popover is visible or not.
     */
    ctrl.isPopoverVisible = false;
    var hideTimeout;

    /**
     * @ngdoc method
     * @name showPopover
     * @description
     * Displays the popover and cancels any hide timer.
     */
    ctrl.showPopover = function() {
      if (hideTimeout) {
        $timeout.cancel(hideTimeout);
      }
      ctrl.isPopoverVisible = true;
    };

    /**
     * @ngdoc method
     * @name hidePopover
     * @description
     * Hides the popover after a delay of 200 ms.
     */
    ctrl.hidePopover = function() {
      hideTimeout = $timeout(function() {
        ctrl.isPopoverVisible = false;
      }, 200);
    };

    var popoverElement = $element[0].querySelector('.custom-popover');

    if (popoverElement) {
      /**
       * @ngdoc event
       * @name mouseenter
       * @description
       * Displays the popover when the mouse enters the popover element.
       */
      angular.element(popoverElement).on('mouseenter', function() {
        if (hideTimeout) {
          $timeout.cancel(hideTimeout);
        }
        ctrl.isPopoverVisible = true;
      });

      /**
       * @ngdoc event
       * @name mouseleave
       * @description
       * Hides the popover when the mouse leaves the popover element.
       */
      angular.element(popoverElement).on('mouseleave', function() {
        ctrl.hidePopover();
      });
    }
  }
});
