/**
 * HVAC Profile Sharing JavaScript
 *
 * @package HVAC_Community_Events
 * @version 1.0.0
 */

(function($) {
    'use strict';

    /**
     * Profile Sharing Handler
     */
    var ProfileSharing = {
        
        /**
         * Initialize the profile sharing system
         */
        init: function() {
            this.bindEvents();
        },
        
        /**
         * Bind event handlers
         */
        bindEvents: function() {
            // Share Profile button click
            $(document).on('click', '.hvac-share-profile-btn', this.openShareModal);
            
            // Modal close events
            $(document).on('click', '.hvac-modal-close', this.closeShareModal);
            $(document).on('click', '.hvac-share-modal', function(e) {
                if (e.target === this) {
                    ProfileSharing.closeShareModal();
                }
            });
            
            // Copy URL button
            $(document).on('click', '.hvac-copy-url-btn', this.copyShareUrl);
            
            // Escape key to close modal
            $(document).on('keydown', function(e) {
                if (e.keyCode === 27 && $('.hvac-share-modal:visible').length) {
                    ProfileSharing.closeShareModal();
                }
            });
        },
        
        /**
         * Open the share profile modal
         */
        openShareModal: function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var profileId = $button.data('profile-id');
            
            if (!profileId) {
                console.error('No profile ID found');
                return;
            }
            
            // Show the modal
            var $modal = $('#hvac-share-profile-modal');
            $modal.fadeIn(300);
            
            // Prevent body scroll
            $('body').addClass('modal-open').css('overflow', 'hidden');
            
            // Load the share data
            ProfileSharing.loadShareData(profileId);
        },
        
        /**
         * Close the share profile modal
         */
        closeShareModal: function(e) {
            if (e) {
                e.preventDefault();
            }
            
            var $modal = $('#hvac-share-profile-modal');
            $modal.fadeOut(300);
            
            // Restore body scroll
            $('body').removeClass('modal-open').css('overflow', '');
            
            // Reset modal content
            setTimeout(function() {
                ProfileSharing.resetModal();
            }, 300);
        },
        
        /**
         * Load share data via AJAX
         */
        loadShareData: function(profileId) {
            var $urlInput = $('#hvac-share-url');
            var $cardContainer = $('#hvac-share-card-container');
            
            // Reset loading states
            $urlInput.val('Loading...');
            $cardContainer.removeClass('loaded').html(
                '<div class="hvac-share-card-loading">' +
                    '<span class="dashicons dashicons-update spin"></span>' +
                    '<p>Loading profile card...</p>' +
                '</div>'
            );
            
            // Make AJAX request
            $.ajax({
                url: hvac_sharing.ajax_url,
                type: 'POST',
                data: {
                    action: 'hvac_get_profile_share_data',
                    profile_id: profileId,
                    nonce: hvac_sharing.nonce
                },
                success: function(response) {
                    if (response.success && response.data) {
                        ProfileSharing.populateShareData(response.data);
                    } else {
                        ProfileSharing.showError(response.data ? response.data.message : 'Unknown error occurred');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', error);
                    ProfileSharing.showError('Network error occurred. Please try again.');
                }
            });
        },
        
        /**
         * Populate the modal with share data
         */
        populateShareData: function(data) {
            var $urlInput = $('#hvac-share-url');
            var $cardContainer = $('#hvac-share-card-container');
            
            // Set the share URL
            $urlInput.val(data.share_url || '');
            
            // Create the profile card HTML
            var cardHtml = ProfileSharing.createProfileCardHtml(data);
            
            // Update the card container
            $cardContainer.addClass('loaded').html(cardHtml);
        },
        
        /**
         * Create profile card HTML
         */
        createProfileCardHtml: function(data) {
            var avatarHtml = '';
            if (data.profile_image) {
                avatarHtml = '<img src="' + data.profile_image + '" alt="' + data.trainer_name + '">';
            } else {
                var initial = data.trainer_name ? data.trainer_name.charAt(0).toUpperCase() : '?';
                avatarHtml = '<div class="hvac-share-avatar-placeholder">' + initial + '</div>';
            }
            
            // Add mQ badge for certified trainers
            var badgeHtml = '';
            if (data.certification_type === 'Certified measureQuick Trainer') {
                badgeHtml = '<div class="hvac-mq-badge-overlay">' +
                    '<img src="/wp-content/uploads/2025/08/mQ-Certified-trainer.png" alt="measureQuick Certified Trainer" class="hvac-mq-badge">' +
                '</div>';
            }
            
            var businessNameHtml = data.business_name ? 
                '<p class="hvac-share-business-name">' + data.business_name + '</p>' : '';
            
            var certificationHtml = data.certification_type ? 
                '<p class="hvac-share-certification">' + data.certification_type + '</p>' : '';
            
            var qrCodeHtml = data.qr_code_url ? 
                '<div class="hvac-share-qr"><img src="' + data.qr_code_url + '" alt="QR Code"></div>' : '';
            
            return '<div class="hvac-share-profile-card">' +
                '<div class="hvac-share-avatar">' +
                    avatarHtml +
                    badgeHtml +
                '</div>' +
                '<div class="hvac-share-details">' +
                    '<h2>' + (data.trainer_name || 'Trainer') + '</h2>' +
                    businessNameHtml +
                    '<p class="hvac-share-location">' + (data.trainer_city || '') + 
                    (data.trainer_city && data.trainer_state ? ', ' : '') + (data.trainer_state || '') + '</p>' +
                    certificationHtml +
                '</div>' +
                qrCodeHtml +
            '</div>';
        },
        
        /**
         * Show error message
         */
        showError: function(message) {
            var $urlInput = $('#hvac-share-url');
            var $cardContainer = $('#hvac-share-card-container');
            
            $urlInput.val('Error loading URL');
            $cardContainer.html(
                '<div class="hvac-share-card-loading">' +
                    '<span class="dashicons dashicons-warning" style="color: #dc3545;"></span>' +
                    '<p style="color: #dc3545;">' + message + '</p>' +
                '</div>'
            );
        },
        
        /**
         * Copy share URL to clipboard
         */
        copyShareUrl: function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var $input = $('#hvac-share-url');
            var url = $input.val();
            
            if (!url || url === 'Loading...' || url === 'Error loading URL') {
                return;
            }
            
            // Try to copy to clipboard
            if (navigator.clipboard && window.isSecureContext) {
                // Use modern clipboard API
                navigator.clipboard.writeText(url).then(function() {
                    ProfileSharing.showCopySuccess($button);
                }).catch(function(err) {
                    console.error('Clipboard API failed:', err);
                    ProfileSharing.fallbackCopy($input, $button);
                });
            } else {
                // Fallback for older browsers
                ProfileSharing.fallbackCopy($input, $button);
            }
        },
        
        /**
         * Fallback copy method for older browsers
         */
        fallbackCopy: function($input, $button) {
            try {
                $input.select();
                $input[0].setSelectionRange(0, 99999); // For mobile devices
                
                var successful = document.execCommand('copy');
                if (successful) {
                    ProfileSharing.showCopySuccess($button);
                } else {
                    ProfileSharing.showCopyError($button);
                }
            } catch (err) {
                console.error('Fallback copy failed:', err);
                ProfileSharing.showCopyError($button);
            }
        },
        
        /**
         * Show copy success feedback
         */
        showCopySuccess: function($button) {
            var originalText = $button.text();
            
            $button.addClass('copied')
                   .text(hvac_sharing.strings.copied);
            
            setTimeout(function() {
                $button.removeClass('copied')
                       .text(originalText);
            }, 2000);
        },
        
        /**
         * Show copy error feedback
         */
        showCopyError: function($button) {
            var originalText = $button.text();
            
            $button.text(hvac_sharing.strings.copy_error)
                   .css('background-color', '#dc3545');
            
            setTimeout(function() {
                $button.text(originalText)
                       .css('background-color', '');
            }, 3000);
        },
        
        /**
         * Reset modal to initial state
         */
        resetModal: function() {
            $('#hvac-share-url').val('');
            $('#hvac-share-card-container').removeClass('loaded').html(
                '<div class="hvac-share-card-loading">' +
                    '<span class="dashicons dashicons-update spin"></span>' +
                    '<p>Loading profile card...</p>' +
                '</div>'
            );
        }
    };

    /**
     * Initialize when document is ready
     */
    $(document).ready(function() {
        ProfileSharing.init();
    });

})(jQuery);