/**
 * UM Elementor Editor Script
 * Handles:
 *   1. Pro-layout lock: intercepts CHOOSE control clicks, reverts value, shows tooltip.
 *   2. Admin notice dismiss.
 */
( function ( $ ) {
    'use strict';

    /* -- Constants -------------------------------------------------------- */

    var PRO_LAYOUTS  = [ 'table_pro', 'carousel_pro' ];
    var PRO_URL      = 'https://userelements.com/ultimate-member-elementor/';
    var WIDGET_NAMES = [ 'ele-um-user-list' ];

    var LAYOUT_LABELS = {
        table_pro:    'Sortable Table',
        carousel_pro: 'User Carousel'
    };

    /* -- Tooltip ---------------------------------------------------------- */

    function buildTooltip( layoutKey ) {
        var label = LAYOUT_LABELS[ layoutKey ] || 'Pro Layout';
        return $(
            '<div class="um-pro-tooltip" role="dialog" aria-label="Pro feature">' +
                '<div class="um-pro-tooltip-header">' +
                    '<span class="um-pro-tooltip-title">\uD83D\uDD12 Pro Feature</span>' +
                    '<button class="um-pro-tooltip-close" aria-label="Close">\u2715</button>' +
                '</div>' +
                '<div class="um-pro-tooltip-body">' +
                    '<strong>' + label + '</strong>' +
                    '<p>This layout is available in the Pro version. Upgrade to unlock:</p>' +
                '</div>' +
                '<ul class="um-pro-features">' +
                    '<li>Sortable &amp; searchable user table</li>' +
                    '<li>Swiper carousel / slider</li>' +
                    '<li>Advanced AJAX filters</li>' +
                    '<li>Profile Page Builder (9 widgets)</li>' +
                    '<li>2-col, 3-col &amp; zigzag layouts</li>' +
                '</ul>' +
                '<a href="' + PRO_URL + '" target="_blank" class="um-pro-tooltip-btn">Upgrade to Pro \u2192</a>' +
            '</div>'
        );
    }

    function removeTooltip() {
        $( '.um-pro-tooltip' ).remove();
        $( document ).off( 'click.umProTooltip keydown.umProTooltip' );
    }

    function positionTooltip( $tooltip, $anchor ) {
        var offset     = $anchor.offset();
        var anchorH    = $anchor.outerHeight();
        var tooltipW   = $tooltip.outerWidth();
        var tooltipH   = $tooltip.outerHeight();
        var anchorW    = $anchor.outerWidth();
        var viewportW  = $( window ).width();

        var top  = offset.top - tooltipH - 10;
        var left = offset.left + ( anchorW / 2 ) - ( tooltipW / 2 );

        if ( left < 8 ) {
            left = 8;
        }
        if ( left + tooltipW > viewportW - 8 ) {
            left = viewportW - tooltipW - 8;
        }
        if ( top < 8 ) {
            top = offset.top + anchorH + 10;
        }

        $tooltip.css( { top: top, left: left } );
    }

    function showTooltip( $anchor, layoutKey ) {
        removeTooltip();

        var $tooltip = buildTooltip( layoutKey );
        $( 'body' ).append( $tooltip );
        positionTooltip( $tooltip, $anchor );

        $tooltip.find( '.um-pro-tooltip-close' ).on( 'click', removeTooltip );

        setTimeout( function () {
            $( document ).on( 'click.umProTooltip', function ( e ) {
                if (
                    ! $( e.target ).closest( '.um-pro-tooltip' ).length &&
                    ! $( e.target ).closest( '.elementor-control-user_layout' ).length
                ) {
                    removeTooltip();
                }
            } );
            $( document ).on( 'keydown.umProTooltip', function ( e ) {
                if ( e.key === 'Escape' ) {
                    removeTooltip();
                }
            } );
        }, 50 );
    }

    /* -- Lock via Elementor channels API (authoritative revert) ---------- */

    var _previousLayout = '1';

    function initEditorChannelListener() {
        if (
            typeof elementor === 'undefined' ||
            ! elementor.channels ||
            ! elementor.channels.editor
        ) {
            return;
        }

        elementor.channels.editor.on( 'change', function ( controlView ) {
            if ( ! controlView || ! controlView.container ) {
                return;
            }

            var model      = controlView.container.model;
            var widgetType = model && model.get( 'widgetType' );
            if ( ! widgetType || WIDGET_NAMES.indexOf( widgetType ) === -1 ) {
                return;
            }

            var settings  = controlView.container.settings;
            var layoutVal = String( settings.get( 'user_layout' ) || '' );

            if ( PRO_LAYOUTS.indexOf( layoutVal ) === -1 ) {
                _previousLayout = layoutVal || '1';
                return;
            }

            settings.set( 'user_layout', _previousLayout );

            var $anchor = $( '.elementor-panel' ).find(
                '.elementor-control-user_layout input[value="' + layoutVal + '"] + label'
            );
            if ( ! $anchor.length ) {
                $anchor = $( '.elementor-panel .elementor-control-user_layout' );
            }

            showTooltip( $anchor, layoutVal );
        } );
    }

    /* -- DOM-level intercept (first line of defense on label click) ------- */

    function initDomIntercept() {
        $( document ).on(
            'click.umProLock',
            '.elementor-control-user_layout label[for$="table_pro"],' +
            '.elementor-control-user_layout label[for$="carousel_pro"]',
            function ( e ) {
                e.preventDefault();
                e.stopImmediatePropagation();

                var forAttr   = $( this ).attr( 'for' ) || '';
                var layoutKey = forAttr.indexOf( 'carousel_pro' ) !== -1 ? 'carousel_pro' : 'table_pro';

                showTooltip( $( this ), layoutKey );
            }
        );
    }

    /* -- Boot -------------------------------------------------------------- */

    $( document ).ready( initDomIntercept );

    $( window ).on( 'elementor:init', initEditorChannelListener );

    if ( typeof elementor !== 'undefined' ) {
        initEditorChannelListener();
    }

}( jQuery ) );