/**
 * Guard Dog Temporary Access Page JavaScript
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        // Tabbed interface logic for temp access page.
        // Scoped to prevent conflicts with parent/sibling tab interfaces
        // on consolidated pages like Users & Sessions.
        var STORAGE_KEY = 'guard_dog_temp_access_active_tab';
        var QUERY_PARAM = 'temp_access_tab';
        var PARENT_QUERY_PARAM = 'users_sessions_tab';
        var PARENT_TAB = 'temporary_access';

        $('.guard-dog-tabbed-interface').each(function() {
            var $container = $(this);
            var $tabNav = $container.children('.guard-dog-tab-nav').add($container.children('nav'));
            var $tabLinks = $tabNav.find('.guard-dog-tab-link');
            var $tabContent = $container.children('.guard-dog-tab-content');
            var $tabPanels = $tabContent.children('.guard-dog-tab-panel');
            var containerKey = $tabLinks.first().data('storage-key') || '';

            // Only handle containers matching the temp access storage key
            if (containerKey !== STORAGE_KEY) {
                return;
            }

            // Restore active tab from sessionStorage
            var savedTab = sessionStorage.getItem(STORAGE_KEY);

            // Check URL parameter as override
            var urlParams = new URLSearchParams(window.location.search);
            var tabParam = urlParams.get(QUERY_PARAM) || urlParams.get('tab');
            if (tabParam && $tabPanels.filter('#' + tabParam).length > 0) {
                savedTab = tabParam;
            }

            if (savedTab && $tabPanels.filter('#' + savedTab).length > 0) {
                $tabLinks.removeClass('active');
                $tabPanels.removeClass('active');
                $tabLinks.filter('[data-tab="' + savedTab + '"]').addClass('active');
                $tabPanels.filter('#' + savedTab).addClass('active');
            } else if ($tabLinks.filter('.active').length === 0) {
                $tabLinks.first().addClass('active');
                $tabPanels.first().addClass('active');
            }

            $tabLinks.on('click', function(e) {
                e.preventDefault();
                var tabId = $(this).data('tab');
                $tabLinks.removeClass('active');
                $(this).addClass('active');
                $tabPanels.removeClass('active');
                $tabPanels.filter('#' + tabId).addClass('active');
                sessionStorage.setItem(STORAGE_KEY, tabId);
                updateUrl(tabId);
            });
        });

        function updateUrl(activeTab) {
            if (!window.history || !window.history.replaceState) {
                return;
            }

            var url = new URL(window.location.href);
            url.searchParams.set(QUERY_PARAM, activeTab);
            url.searchParams.set(PARENT_QUERY_PARAM, PARENT_TAB);
            url.searchParams.delete('tab');
            url.searchParams.delete('_wpnonce');

            window.history.replaceState({}, '', url.toString());
        }

        // Handle expiry dropdown
        $('#expiry').change(function() {
            if ($(this).val() === 'custom') {
                $('#custom_date').show();
            } else {
                $('#custom_date').hide();
            }
        });

        // Enhanced delete button functionality
        $('.button-link-delete').on('click', function(e) {
            e.preventDefault(); // Prevent immediate form submission
            
            var confirmMessage = 'Are you sure you want to delete this temporary user?';
            
            if (confirm(confirmMessage)) {
                console.log('Delete confirmed, proceeding with form submission');
                // Submit the form
                $(this).closest('form').submit();
            } else {
                console.log('Delete cancelled by user');
            }
        });

        // Copy to clipboard functionality for temporary access links
        $('.guard-dog-copy-link').on('click', function() {
            var $button = $(this);
            var link = $button.data('link');
            var $input = $button.siblings('.guard-dog-access-link');

            // Select the text
            $input.select();

            // Copy to clipboard
            if (navigator.clipboard && window.isSecureContext) {
                // Use modern clipboard API
                navigator.clipboard.writeText(link).then(function() {
                    showCopySuccess($button);
                }).catch(function() {
                    fallbackCopy($input, $button);
                });
            } else {
                // Fallback for older browsers
                fallbackCopy($input, $button);
            }
        });

        function fallbackCopy($input, $button) {
            try {
                document.execCommand('copy');
                showCopySuccess($button);
            } catch (err) {
                console.error('Failed to copy: ', err);
                showCopyError($button);
            }
        }

        function showCopySuccess($button) {
            var $icon = $button.find('.dashicons');
            var originalClass = $icon.attr('class');

            $icon.removeClass('dashicons-clipboard').addClass('dashicons-yes');
            $button.addClass('copied');

            setTimeout(function() {
                $icon.attr('class', originalClass);
                $button.removeClass('copied');
            }, 2000);
        }

        function showCopyError($button) {
            var $icon = $button.find('.dashicons');
            var originalClass = $icon.attr('class');

            $icon.removeClass('dashicons-clipboard').addClass('dashicons-no');
            $button.addClass('error');

            setTimeout(function() {
                $icon.attr('class', originalClass);
                $button.removeClass('error');
            }, 2000);
        }

        // Show/hide form sections
        $('.guard-dog-toggle-section').on('click', function(e) {
            e.preventDefault();
            var target = $(this).data('target');
            $('#' + target).slideToggle();
        });

        // Username generation functionality
        function updateGeneratedUsername() {
            var firstName = $('#first_name').val().trim();
            var lastName = $('#last_name').val().trim();

            if (firstName) {
                // Create base username from first and last name
                var baseUsername = firstName.toLowerCase();
                if (lastName) {
                    baseUsername += '.' + lastName.toLowerCase();
                }

                // Remove any non-alphanumeric characters except dots and hyphens
                baseUsername = baseUsername.replace(/[^a-z0-9.-]/g, '');

                // Ensure it's not empty
                if (baseUsername === '') {
                    baseUsername = 'tempuser';
                }

                $('#generated_username').val(baseUsername);
            } else {
                $('#generated_username').val('');
            }
        }

        // Update on input
        $('#first_name, #last_name').on('input', updateGeneratedUsername);

        // Initial update
        updateGeneratedUsername();
    });

})(jQuery); 
