/**
 * File Path: assets/js/adminjs/mbs-admin-onix-settings.js
 *
 * ONIX Settings Tab -- Required-field tip popover
 *
 * Click a .mbs-onix-required indicator to show a .mbs-onix-tip popover
 * with the element's title text. Clicking again or clicking elsewhere
 * closes the popover. Enter/Space also activates the indicator.
 *
 * @package    My_Book_Showroom
 * @subpackage Assets/JS/AdminJS
 * @since      1.3.0
 */
(function() {
    'use strict';

    document.addEventListener('DOMContentLoaded', function() {
        var triggers = document.querySelectorAll('.mbs-onix-required');
        var activeTip = null;

        /**
         * Remove the active tip from the DOM.
         */
        function closeTip() {
            if (activeTip && activeTip.parentNode) {
                activeTip.parentNode.removeChild(activeTip);
            }
            activeTip = null;
        }

        /**
         * Build and insert a tip span inside the trigger element.
         *
         * @param {Element} el Trigger element (.mbs-onix-required).
         */
        function openTip(el) {
            var tip = document.createElement('span');
            tip.className = 'mbs-onix-tip';
            tip.textContent = el.getAttribute('title') || '';
            el.appendChild(tip);
            activeTip = tip;
        }

        [].forEach.call(triggers, function(el) {

            // Click: toggle the tip open/closed.
            el.addEventListener('click', function(e) {
                e.stopPropagation();
                if (activeTip && activeTip.parentNode === el) {
                    closeTip();
                    return;
                }
                closeTip();
                openTip(el);
            });

            // Keyboard: Enter or Space activates like a click.
            el.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    el.click();
                }
            });
        });

        // Clicking anywhere outside a trigger closes the active tip.
        document.addEventListener('click', closeTip);
    });
})();
