/**
 * Role-Based Email Templates – Admin UI
 *
 * Handles dynamic addition/removal of role-based template blocks,
 * "All Roles" checkbox toggling, QuickTags editor initialisation,
 * and block re-indexing after removal.
 *
 * @package WP User Frontend Pro
 * @since   4.2.14
 */
(function($) {
    'use strict';

    /**
     * Escape a plain-text string for safe insertion into HTML.
     *
     * @param {*} str
     * @return {string}
     */
    function escapeHtml(str) {
        return $('<span>').text(String(str)).html();
    }

    /**
     * Handle "All Roles" checkbox - disable/enable specific roles
     */
    $(document).on('change', '.wpuf-role-all-checkbox', function() {
        var $checkbox = $(this);
        var $wrapper = $checkbox.closest('.wpuf-roles-checkbox-wrapper');
        var $specificRoles = $wrapper.find('.wpuf-specific-roles');
        var $specificCheckboxes = $wrapper.find('.wpuf-role-specific-checkbox');

        if ($checkbox.is(':checked')) {
            // Disable and uncheck all specific role checkboxes.
            // Note: disabled inputs are NOT submitted with the form, so any previously saved
            // specific-role selections will be absent from the POST data on save. This is
            // intentional — "All Roles" supersedes individual role selections.
            $specificRoles.css({ opacity: 0.5, pointerEvents: 'none' });
            $specificCheckboxes.prop('checked', false).prop('disabled', true);
        } else {
            // Enable specific role checkboxes
            $specificRoles.css({ opacity: 1, pointerEvents: 'auto' });
            $specificCheckboxes.prop('disabled', false);
        }
    });

    /**
     * Handle specific role checkbox - uncheck "All Roles" when a specific role is selected
     */
    $(document).on('change', '.wpuf-role-specific-checkbox', function() {
        var $checkbox = $(this);
        var $wrapper = $checkbox.closest('.wpuf-roles-checkbox-wrapper');
        var $allRolesCheckbox = $wrapper.find('.wpuf-role-all-checkbox');

        // If any specific role is checked, ensure "All Roles" is unchecked
        if ($checkbox.is(':checked')) {
            $allRolesCheckbox.prop('checked', false);
        }
    });

    /**
     * Add new role-based template block
     */
    $(document).on('click', '.wpuf-add-role-template', function(e) {
        e.preventDefault();

        var emailType = $(this).data('email-type');
        var $wrapper = $('#wpuf_role_templates_' + emailType);
        var newIndex = $wrapper.find('.wpuf-role-template-block').length;

        var blockHtml = buildTemplateBlock(emailType, newIndex);
        $wrapper.append(blockHtml);

        // Initialize quicktags for the new editor
        var editorId = 'wpuf_role_body_' + emailType + '_' + newIndex;
        initQuicktags(editorId);

        return false;
    });

    /**
     * Initialize quicktags for an editor
     *
     * @param {string} editorId
     */
    function initQuicktags(editorId) {
        if (typeof QTags !== 'undefined') {
            new QTags({
                id: editorId,
                buttons: 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close'
            });
            QTags._buttonsInit();
        }
    }

    /**
     * Remove role-based template block
     */
    $(document).on('click', '.wpuf-remove-role-template', function(e) {
        e.preventDefault();

        var confirmMsg = (typeof wpufRoleTemplates !== 'undefined' && wpufRoleTemplates.i18n)
            ? wpufRoleTemplates.i18n.confirmDelete
            : 'Are you sure you want to remove this template?';

        if (!confirm(confirmMsg)) {
            return false;
        }

        var $block = $(this).closest('.wpuf-role-template-block');
        var $wrapper = $block.closest('.wpuf-role-templates-wrapper');

        $block.remove();
        reindexBlocks($wrapper);

        return false;
    });

    /**
     * Build HTML for a new template block
     *
     * @param {string} emailType
     * @param {number} index
     * @return {string}
     */
    function buildTemplateBlock(emailType, index) {
        var i18n = (typeof wpufRoleTemplates !== 'undefined' && wpufRoleTemplates.i18n) ? wpufRoleTemplates.i18n : {};
        var fieldName = 'wpuf_role_email_templates[' + escapeHtml(emailType) + '][' + index + ']';
        var editorId = 'wpuf_role_body_' + escapeHtml(emailType) + '_' + index;

        var labelSelectRoles    = i18n.selectRoles    || 'Select Roles';
        var labelEmailSubject   = i18n.emailSubject   || 'Email Subject';
        var labelEmailBody      = i18n.emailBody      || 'Email Body';
        var labelRemove         = i18n.removeTemplate || 'Remove Template';
        var labelCodeBtn        = i18n.codeEditorBtn  || 'Code';
        var labelYouMayUse      = i18n.youMayUse      || 'You may use:';

        var html = '<div class="wpuf-role-template-block" data-index="' + index + '">';
        html += '<button type="button" class="wpuf-remove-role-template" title="' + escapeHtml(labelRemove) + '">';
        html += '<span class="dashicons dashicons-no-alt"></span></button>';

        // Table structure matching WordPress settings
        html += '<table class="form-table wpuf-role-form-table">';

        // Roles field – checkboxes
        html += '<tr>';
        html += '<th scope="row">' + escapeHtml(labelSelectRoles) + '</th>';
        html += '<td>';
        html += '<div class="wpuf-roles-checkbox-wrapper">';
        html += getRolesCheckboxes(fieldName);
        html += '</div>';
        html += '</td>';
        html += '</tr>';

        // Subject field
        html += '<tr>';
        html += '<th scope="row">' + escapeHtml(labelEmailSubject) + '</th>';
        html += '<td>';
        html += '<input type="text" name="' + escapeHtml(fieldName) + '[subject]" value="" class="regular-text">';
        html += '</td>';
        html += '</tr>';

        // Placeholder list (per email type)
        var placeholders = [];
        if (typeof wpufRoleTemplates !== 'undefined' && wpufRoleTemplates.placeholders) {
            placeholders = wpufRoleTemplates.placeholders[emailType] || wpufRoleTemplates.placeholders['default'] || [];
        }

        var placeholderHtml = '';
        if (placeholders.length) {
            placeholderHtml = '<p class="description">' + escapeHtml(labelYouMayUse);
            $.each(placeholders, function(i, tag) {
                placeholderHtml += ' <code>' + escapeHtml(tag) + '</code>';
            });
            placeholderHtml += '</p>';
        }

        // Body field with quicktags editor structure
        html += '<tr>';
        html += '<th scope="row">' + escapeHtml(labelEmailBody) + '</th>';
        html += '<td>';
        html += '<div class="wpuf-role-editor-wrapper">';
        html += '<div class="wp-core-ui wp-editor-wrap html-active">';
        html += '<div class="wp-editor-tools">';
        html += '<div class="wp-editor-tabs">';
        html += '<button type="button" class="wp-switch-editor switch-html" data-editor="' + escapeHtml(editorId) + '">' + escapeHtml(labelCodeBtn) + '</button>';
        html += '</div>';
        html += '</div>';
        html += '<div class="wp-editor-container">';
        html += '<div id="qt_' + escapeHtml(editorId) + '_toolbar" class="quicktags-toolbar"></div>';
        html += '<textarea id="' + escapeHtml(editorId) + '" name="' + escapeHtml(fieldName) + '[body]" rows="8" class="wp-editor-area wpuf-role-email-body" style="width: 100%;"></textarea>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += placeholderHtml;
        html += '</td>';
        html += '</tr>';

        html += '</table>';
        html += '</div>';

        return html;
    }

    /**
     * Get roles checkboxes HTML – matches PHP template structure.
     *
     * Role names are rendered via DOM text nodes to prevent XSS.
     *
     * @param {string} fieldName
     * @return {string}
     */
    function getRolesCheckboxes(fieldName) {
        var i18n = (typeof wpufRoleTemplates !== 'undefined' && wpufRoleTemplates.i18n) ? wpufRoleTemplates.i18n : {};
        var labelAllRoles = i18n.allRoles || 'All Roles';

        // Build using DOM elements to safely handle role names
        var $wrapper = $('<div>');

        // "All Roles" checkbox – checked by default for new templates
        var $allLabel = $('<label class="wpuf-role-checkbox wpuf-role-checkbox-all">');
        $('<input>').attr({
            type: 'checkbox',
            name: fieldName + '[roles][]',
            value: 'all_roles',
            class: 'wpuf-role-all-checkbox',
            checked: true,
        }).appendTo($allLabel);
        $allLabel.append(' ').append(document.createTextNode(labelAllRoles));
        $wrapper.append($allLabel);

        // Specific roles wrapper – disabled by default since "All Roles" is checked
        var $rolesDiv = $('<div class="wpuf-specific-roles">').css({ opacity: 0.5, pointerEvents: 'none' });

        // Use localized roles data from PHP (always available via wp_localize_script)
        var roles = (typeof wpufRoleTemplates !== 'undefined' && wpufRoleTemplates.roles)
            ? wpufRoleTemplates.roles
            : {};

        $.each(roles, function(key, name) {
            var $label = $('<label class="wpuf-role-checkbox">');
            $('<input>').attr({
                type: 'checkbox',
                name: fieldName + '[roles][]',
                value: key,
                class: 'wpuf-role-specific-checkbox',
                disabled: true,
            }).appendTo($label);
            $label.append(' ').append(document.createTextNode(name));
            $rolesDiv.append($label);
        });

        $wrapper.append($rolesDiv);
        return $wrapper.html();
    }

    /**
     * Re-index all blocks after removal
     *
     * @param {jQuery} $wrapper
     */
    function reindexBlocks($wrapper) {
        var emailType = $wrapper.data('email-type');

        $wrapper.find('.wpuf-role-template-block').each(function(index) {
            var $block = $(this);
            var fieldName = 'wpuf_role_email_templates[' + emailType + '][' + index + ']';

            $block.attr('data-index', index);
            // Update checkbox names for roles
            $block.find('.wpuf-role-all-checkbox, .wpuf-role-specific-checkbox').attr('name', fieldName + '[roles][]');
            $block.find('input[type="text"]').attr('name', fieldName + '[subject]');
            $block.find('textarea.wpuf-role-email-body, textarea.wp-editor-area').attr('name', fieldName + '[body]');
        });
    }

})(jQuery);
