(function ($) {
    'use strict';

    console.log('WriteText.ai | Enhanced Idle Detection Controller for iPad/Mobile');

    // Enhanced Idle Detection Controller with iPad/Mobile fixes
    window.WTAIIdleController = {
        isIdle: false,
        idleTimer: null,
        idleTimeout: 60000, // 1 minute of inactivity
        wasPollingActive: false,
        lastActiveTime: Date.now(),
        backgroundTime: null,
        isBackground: false,
        
        // Events that indicate user activity (enhanced for mobile)
        activityEvents: [
            'mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click',
            'touchmove', 'touchend', 'gesturestart', 'gesturechange', 'gestureend',
            'orientationchange', 'resize', 'focus'
        ],
        
        init: function () {
            this.bindEvents();
            this.resetIdleTimer();
            
            // Enhanced visibility handling for iPad
            document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
            window.addEventListener('pageshow', this.handlePageShow.bind(this));
            window.addEventListener('pagehide', this.handlePageHide.bind(this));
            
            // iPad-specific events
            window.addEventListener('blur', this.handleWindowBlur.bind(this));
            window.addEventListener('focus', this.handleWindowFocus.bind(this));
            
            // Detect if app was suspended and resumed (iPad specific)
            this.setupBackgroundDetection();
        },
        
        bindEvents: function () {
            // Bind activity detection to multiple events
            this.activityEvents.forEach(event => {
                document.addEventListener(event, this.handleActivity.bind(this), {
                    passive: true,
                    capture: true
                });
            });
        },
        
        setupBackgroundDetection: function () {
            // Detect when the app was suspended (iPad/mobile specific)
            setInterval(() => {
                const now = Date.now();
                const timeDiff = now - this.lastActiveTime;
                
                // If more than 2 seconds have passed since last check and we're not idle,
                // the app was likely suspended
                if (timeDiff > 2000 && !this.isIdle && !this.isBackground) {
                    console.log('WriteText.ai: App suspension detected, handling as background');
                    this.handleAppSuspension();
                }
                this.lastActiveTime = now;
            }, 1000);
        },
        
        handleActivity: function () {
            this.lastActiveTime = Date.now();
            
            if (this.isIdle) {
                this.handleReturn();
            }
            this.resetIdleTimer();
        },
        
        handleVisibilityChange: function () {
            if (document.hidden) {
                this.isBackground = true;
                this.backgroundTime = Date.now();
                this.handleIdle();
            } else {
                this.isBackground = false;
                this.handleVisibilityReturn();
            }
        },
        
        handlePageShow: function (event) {
            // Fired when page becomes visible (including from cache)
            console.log('WriteText.ai: Page show event (from cache: ' + event.persisted + ')');
            this.isBackground = false;
            this.handleReturn();
        },
        
        handlePageHide: function () {
            // Fired when page is hidden/cached
            console.log('WriteText.ai: Page hide event');
            this.isBackground = true;
            this.handleIdle();
        },
        
        handleWindowBlur: function () {
            // Window lost focus (app switching on iPad)
            this.isBackground = true;
            this.backgroundTime = Date.now();
            this.handleIdle();
        },
        
        handleWindowFocus: function () {
            // Window gained focus
            this.isBackground = false;
            this.handleReturn();
        },
        
        handleAppSuspension: function () {
            // Handle app suspension/resume on iPad
            console.log('WriteText.ai: App suspension/resume detected');
            this.handleIdle();
            
            // Immediate check when resumed
            setTimeout(() => {
                if (!this.isBackground) {
                    this.handleReturn();
                }
            }, 100);
        },
        
        handleVisibilityReturn: function () {
            const now = Date.now();
            if (this.backgroundTime) {
                const backgroundDuration = now - this.backgroundTime;
                console.log('WriteText.ai: Was in background for ' + Math.round(backgroundDuration/1000) + ' seconds');
                
                // If was in background for more than 30 seconds, force a data refresh
                if (backgroundDuration > 30000) {
                    $(document).trigger('wtai:force-refresh');
                }
            }
            this.handleReturn();
        },
        
        handleIdle: function () {
            if (!this.isIdle) {
                console.log('WriteText.ai: User went idle.');
                this.isIdle = true;
                
                // Store current polling state
                this.wasPollingActive = (typeof pollBackgroundTimer !== 'undefined' && pollBackgroundTimer !== null);
                
                // Trigger custom idle event for other parts of your plugin
                $(document).trigger('wtai:user-idle');
            }
        },
        
        handleReturn: function () {
            if (this.isIdle) {
                console.log('WriteText.ai: User returned, resuming background operations');
                this.isIdle = false;
                
                // Trigger custom return event
                $(document).trigger('wtai:user-return');
            }
            this.resetIdleTimer();
        },
                
        resetIdleTimer: function () {
            clearTimeout(this.idleTimer);
            this.idleTimer = setTimeout(() => {
                this.handleIdle();
            }, this.idleTimeout);
        },
        
        // Force immediate resume (useful for critical operations)
        forceResume: function () {
            console.log('WriteText.ai: Forced resume');
            this.isIdle = false;
            this.isBackground = false;
            $(document).trigger('wtai:user-return');
            this.resetIdleTimer();
        },
        
        destroy: function () {
            // Clean up event listeners
            this.activityEvents.forEach(event => {
                document.removeEventListener(event, this.handleActivity.bind(this));
            });
            document.removeEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
            window.removeEventListener('pageshow', this.handlePageShow.bind(this));
            window.removeEventListener('pagehide', this.handlePageHide.bind(this));
            window.removeEventListener('blur', this.handleWindowBlur.bind(this));
            window.removeEventListener('focus', this.handleWindowFocus.bind(this));
            
            clearTimeout(this.idleTimer);
        }
    };

    // Initialize idle detection when DOM is ready
    $(document).ready(function () {
        if (typeof WTAIIdleController !== 'undefined') {
            WTAIIdleController.init();
            
            // iPad-specific: Force resume when user taps anywhere after being idle
            $(document).on('touchstart click', function () {
                if (WTAIIdleController.isIdle || WTAIIdleController.isBackground) {
                    setTimeout(() => WTAIIdleController.forceResume(), 50);
                }
            });
        }
    });

})(jQuery);