(function($) {
    'use strict';
    
    class HvnlyPropertyGlobalShareManager {
        constructor() {
            this.isOpen = false;
            this.currentPropertyId = null;
            this.currentShareData = null;
            this.autoCloseTimeout = null;
            this.countdownInterval = null;
            this.secondsLeft = 15;
            this.init();
        }
        
        init() {
            this.bindEvents();
        }
        
        bindEvents() {
            const self = this;
            
            // Share trigger - click only (no hover)
            $(document).on('click', '.hvnly-property-share-trigger', function(e) {
                e.stopPropagation();
                const propertyId = $(this).data('property-id');
                const shareField = $(this).closest('.hvnly-property-share-field');
                const shareData = JSON.parse(shareField.attr('data-share-config'));
                
                self.openPopup(propertyId, shareData);
            });
            
            // Close popup
            $(document).on('click', '.hvnly-property-popup-close', function() {
                self.closePopup();
            });
            
            // Close on overlay click
            $(document).on('click', '.hvnly-property-share-popup-overlay', function(e) {
                if (e.target === this) {
                    self.closePopup();
                }
            });
            
            // Copy link
            $(document).on('click', '.hvnly-property-copy-btn', function() {
                self.copyToClipboard(this);
            });
            
            // Platform clicks
            $(document).on('click', '.hvnly-property-share-platform', function(e) {
                const platform = $(this).data('platform');
                self.handlePlatformClick(e, platform, this);
            });
            
            // Email back button
            $(document).on('click', '.hvnly-property-email-back', function() {
                self.showCopySection();
            });
            
            // Escape key to close
            $(document).on('keyup', function(e) {
                if (e.key === 'Escape' && self.isOpen) {
                    self.closePopup();
                }
            });
        }
        
        openPopup(propertyId, shareData) {
            if (this.isOpen) return;
            
            this.isOpen = true;
            this.currentPropertyId = propertyId;
            this.currentShareData = shareData;
            
            // Disable all other share buttons
            $('.hvnly-property-share-trigger').addClass('disabled');
            
            // Add open class to body
            $('body').addClass('hvnly-property-share-popup-open');
            
            // Show overlay
            $('#hvnly-property-global-share-popup').addClass('active');
            
            // Populate popup content
            this.populatePopupContent(shareData);
            
            // Start auto-close timer
            this.startAutoCloseTimer();
            
            // Show copy section by default
            this.showCopySection();
        }
        
        closePopup() {
            if (!this.isOpen) return;
            
            this.isOpen = false;
            this.currentPropertyId = null;
            this.currentShareData = null;
            
            // Re-enable all share buttons
            $('.hvnly-property-share-trigger').removeClass('disabled');
            
            // Remove open class from body
            $('body').removeClass('hvnly-property-share-popup-open');
            
            // Hide overlay
            $('#hvnly-property-global-share-popup').removeClass('active');
            
            // Clear auto-close timer
            this.clearAutoCloseTimer();
            
            // Reset copy button state
            this.resetCopyButton();
        }
        
        populatePopupContent(shareData) {
            // Update link input
            $('.hvnly-property-link-input').val(shareData.url);
            
            // Update share count
            $('.hvnly-property-count-number').text(shareData.share_count || '0');
            
            // Populate platforms
            this.populatePlatforms(shareData);
        }
        
        populatePlatforms(shareData) {
            const platformsContainer = $('#hvnly-property-share-platforms-container');
            platformsContainer.empty();
            
            const platformConfigs = {
                'facebook': { name: 'Facebook', icon: 'fab fa-facebook-f', color: '#1877f2', url: 'https://www.facebook.com/sharer/sharer.php?u={url}' },
                'twitter': { name: 'Twitter', icon: 'fab fa-twitter', color: '#1da1f2', url: 'https://twitter.com/intent/tweet?url={url}&text={title}' },
                'linkedin': { name: 'LinkedIn', icon: 'fab fa-linkedin-in', color: '#0a66c2', url: 'https://www.linkedin.com/sharing/share-offsite/?url={url}' },
                'pinterest': { name: 'Pinterest', icon: 'fab fa-pinterest-p', color: '#bd081c', url: 'https://pinterest.com/pin/create/button/?url={url}&media={image}&description={title}' },
                'email': { name: 'Email', icon: 'fas fa-envelope', color: '#666666', url: '#' },
                'whatsapp': { name: 'WhatsApp', icon: 'fab fa-whatsapp', color: '#25d366', url: 'https://api.whatsapp.com/send?text={title} {url}' }
            };
            
            shareData.platforms.forEach(platform => {
                if (platformConfigs[platform]) {
                    const config = platformConfigs[platform];
                    let shareUrl = config.url;
                    
                    if (platform !== 'email') {
                        shareUrl = shareUrl
                            .replace('{url}', encodeURIComponent(shareData.url))
                            .replace('{title}', encodeURIComponent(shareData.title))
                            .replace('{image}', encodeURIComponent(shareData.image || ''));
                    }
                    
                    const platformHtml = `
                        <a href="${shareUrl}" 
                           class="hvnly-property-share-platform hvnly-property-share-${platform}" 
                           data-platform="${platform}"
                           ${platform !== 'email' ? 'target="_blank" rel="noopener noreferrer"' : ''}
                           title="Share on ${config.name}">
                            <div class="hvnly-property-platform-icon" style="background-color: ${config.color}">
                                <i class="${config.icon}"></i>
                            </div>
                            <span class="hvnly-property-platform-name">${config.name}</span>
                        </a>
                    `;
                    
                    platformsContainer.append(platformHtml);
                }
            });
        }
        
        startAutoCloseTimer() {
            this.secondsLeft = 15;
            this.updateTimerText();
            
            this.countdownInterval = setInterval(() => {
                this.secondsLeft--;
                this.updateTimerText();
                
                if (this.secondsLeft <= 5) {
                    $('.hvnly-property-auto-close-timer').addClass('timer-warning');
                }
                
                if (this.secondsLeft <= 0) {
                    this.closePopup();
                }
            }, 1000);
            
            this.autoCloseTimeout = setTimeout(() => this.closePopup(), 15000);
        }
        
        clearAutoCloseTimer() {
            if (this.autoCloseTimeout) {
                clearTimeout(this.autoCloseTimeout);
            }
            if (this.countdownInterval) {
                clearInterval(this.countdownInterval);
            }
            $('.hvnly-property-auto-close-timer').removeClass('timer-warning');
        }
        
        updateTimerText() {
            $('.hvnly-property-timer-text').text('Auto-close in ' + this.secondsLeft + 's');
        }
        
        copyToClipboard(copyBtn) {
            const input = $('.hvnly-property-link-input')[0];
            const textToCopy = input.value;
            
            // Store original readonly state
            const originalReadonly = input.readOnly;
            
            // Temporarily remove readonly to allow selection
            input.readOnly = false;
            
            // Select the text
            input.focus();
            input.select();
            input.setSelectionRange(0, 99999);
            
            // Try using the modern clipboard API first
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(textToCopy).then(() => {
                    this.showCopySuccess(copyBtn);
                }).catch(() => {
                    // Fallback to execCommand if clipboard API fails
                    this.fallbackCopyTextToClipboard(textToCopy, copyBtn);
                }).finally(() => {
                    // Restore readonly state
                    input.readOnly = originalReadonly;
                });
            } else {
                // Use fallback for older browsers
                this.fallbackCopyTextToClipboard(textToCopy, copyBtn);
                // Restore readonly state
                input.readOnly = originalReadonly;
            }
        }
        
        fallbackCopyTextToClipboard(text, copyBtn) {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            
            // Avoid scrolling to bottom
            textArea.style.top = "0";
            textArea.style.left = "0";
            textArea.style.position = "fixed";
            
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    this.showCopySuccess(copyBtn);
                }
            } catch (err) {
                // console.error('Fallback: Oops, unable to copy', err);
            }
            
            document.body.removeChild(textArea);
        }
        
        showCopySuccess(copyBtn) {
            // Show success check icon
            $('.hvnly-property-copy-success').addClass('show');
            
            // Update copy button state
            $(copyBtn).addClass('copied');
            
            setTimeout(() => {
                $('.hvnly-property-copy-success').removeClass('show');
                this.resetCopyButton();
            }, 2000);
            
            // Track copy event
            this.trackShare('copy');
        }
        
        resetCopyButton() {
            $('.hvnly-property-copy-btn').removeClass('copied');
        }
        
        handlePlatformClick(e, platform, element) {
            if (platform === 'email') {
                e.preventDefault();
                this.showEmailSection();
                this.clearAutoCloseTimer();
            } else {
                // Track social share
                this.trackShare(platform);
                
                // Reset timer on interaction
                this.clearAutoCloseTimer();
                this.startAutoCloseTimer();
            }
        }
        
        showCopySection() {
            $('.hvnly-property-copy-link-section').addClass('hvnly-property-active-section');
            $('.hvnly-property-email-share-section').removeClass('hvnly-property-active-section');
        }
        
        showEmailSection() {
            $('.hvnly-property-copy-link-section').removeClass('hvnly-property-active-section');
            $('.hvnly-property-email-share-section').addClass('hvnly-property-active-section');
        }
        
        trackShare(platform) {
            // Implement your analytics tracking here
            if (typeof gtag !== 'undefined') {
                gtag('event', 'share', {
                    'method': platform,
                    'content_type': 'property',
                    'content_id': this.currentPropertyId
                });
            }
            
            // Update share count locally
            const countElement = $('.hvnly-property-count-number');
            let currentCount = parseInt(countElement.text());
            countElement.text(currentCount + 1);
        }
    }
    
    // Initialize global share manager when DOM is ready
    $(document).ready(function() {
        window.hvnlyPropertyShareManager = new HvnlyPropertyGlobalShareManager();
    });
    
})(jQuery);