/**
 * CLAWS Core Module
 * Handles application initialization, configuration, and core utilities
 */

(function($) {
    'use strict';

    // Core CLAWS App Object
    window.CLAWSApp = {
        
        // Initialization protection
        _initialized: false,
        _initializationCount: 0,
        _pageLoadTime: Date.now(),
        
        // Debug flag (kept lightweight on purpose)
        _debugMode: false,
        
        // App state
        currentTab: 'colony',
        currentVolunteerSubTab: 'mytime',
        colonies: [],
        intakeRecords: [],
        dischargeRecords: [],
        feedingRecords: [],
        babyKittens: [],
        
        // Map and chart objects
        colonyMap: null,
        colonyChart: null,
        colonyMarkers: [],
        
        // Intake/Discharge chart objects
        intakeTypeChart: null,
        intakeGenderChart: null,
        intakeAgeChart: null,
        activeIntakesByUserChart: null,
        dischargeOutcomeChart: null,
        
        // Neonate care objects
        neonateChart: null,
        babyChart: null,
        feedingChart: null,
        dailyLogChart: null,
        
        // Chart preferences
        selectedChartType: 'bar',
        
        // Configuration
        config: {
            apiUrl: '',
            nonce: '',
            defaultLatitude: 39.8283,
            defaultLongitude: -98.5795
        },

        /**
         * Get master theme colors from CSS variables
         */
        getMasterColors: function() {
            const computedStyle = getComputedStyle(document.documentElement);
            return {
                primary: computedStyle.getPropertyValue('--claws-master-bg-primary').trim(),
                secondary: computedStyle.getPropertyValue('--claws-master-bg-secondary').trim(),
                textColor: computedStyle.getPropertyValue('--claws-master-text-color').trim(),
                accentColor: computedStyle.getPropertyValue('--claws-master-accent-color').trim(),
                background: computedStyle.getPropertyValue('--claws-master-bg').trim()
            };
        },

        /**
         * Initialize the CLAWS app with protection against multiple calls
         */
        initialize: function() {
            this._initializationCount++;
            
            // PROTECTION: Only allow one initialization per page load
            if (this._initialized) {
                return false;
            }
            
            // PREVENT SCROLL on reload (if coming from colony tab switch)
            if (sessionStorage.getItem('claws_no_scroll') === 'true') {
                sessionStorage.removeItem('claws_no_scroll');
                // Scroll to top immediately
                window.scrollTo(0, 0);
                // Keep scrolled to top
                setTimeout(() => window.scrollTo(0, 0), 100);
            }
            
            // Load configuration from WordPress
            this.loadConfig();
            
            // Initialize components
            this.initializeEventListeners();
            this.initializeIcons();
            
            // CRITICAL: Load My Time data immediately on page load
            // This ensures pending/approved tasks are loaded even before tab switch
            if (typeof CLAWSApp.loadPendingItems === 'function') {
                CLAWSApp.loadPendingItems();
            }
            if (typeof CLAWSApp.loadApprovedItems === 'function') {
                CLAWSApp.loadApprovedItems();
            }
            
            // Set default tab
            this.switchTab('colony');
            
            // Mark as initialized
            this._initialized = true;
            
            return true;
        },

        /**
         * Load configuration from WordPress localized data with access protection
         */
        loadConfig: function() {
            if (typeof clawsData !== 'undefined') {
                this.config.apiUrl = clawsData.apiUrl || '/wp-json/claws/v1/';
                this.config.nonce = clawsData.nonce || '';
                this.config.defaultLatitude = parseFloat(clawsData.defaultLatitude) || 39.8283;
                this.config.defaultLongitude = parseFloat(clawsData.defaultLongitude) || -98.5795;
            }
        },
        
        /**
         * Safe access to clawsData with protection against external abuse
         */
        getCurrentClawsData: function() {
            return null; // Block external access
        },

        /**
         * Update login status display
         */
        updateLoginStatus: function() {
            const loginStatus = document.querySelector('.claws-login-status');
            if (loginStatus && typeof clawsData !== 'undefined') {
                if (clawsData.isLoggedIn) {
                    loginStatus.innerHTML = `
                        <span style="color: ${CLAWS_CONSTANTS.COLORS.SUCCESS};">✓ Logged in as ${clawsData.currentUser}</span>
                        <br><small style="color: ${CLAWS_CONSTANTS.COLORS.GRAY_600};">Roles: ${clawsData.userRoles ? clawsData.userRoles.join(', ') : 'None'}</small>
                    `;
                } else {
                    loginStatus.innerHTML = `<span style="color: ${CLAWS_CONSTANTS.COLORS.ERROR};">⚠ Please log in to use this application</span>`;
                }
            }
        },

        /**
         * Initialize Font Awesome icons
         */
        initializeIcons: function() {
            if (typeof FontAwesome !== 'undefined' && FontAwesome.dom) {
                FontAwesome.dom.i2svg();
            }
        },

        /**
         * Initialize event listeners
         */
        initializeEventListeners: function() {
            // Modal backdrop click handler
            document.addEventListener('click', (e) => {
                if (e.target.matches('.claws-modal-backdrop') || e.target.id === 'claws-add-colony-modal') {
                    if (typeof this.hideAddColonyForm === 'function') {
                        this.hideAddColonyForm();
                    }
                }
            });
        },

        /**
         * Get chart color by index
         */
        getChartColor: function(index) {
            return CLAWS_CONSTANTS.COLORS.CHART_COLORS[index % CLAWS_CONSTANTS.COLORS.CHART_COLORS.length];
        },

        /**
         * Get progress color based on percentage
         */
        getProgressColor: function(percentage) {
            if (percentage >= CLAWS_CONSTANTS.HEALTH_THRESHOLDS.EXCELLENT) return CLAWS_CONSTANTS.COLORS.EXCELLENT;
            if (percentage >= CLAWS_CONSTANTS.HEALTH_THRESHOLDS.GOOD) return CLAWS_CONSTANTS.COLORS.FAIR;
            if (percentage >= CLAWS_CONSTANTS.HEALTH_THRESHOLDS.FAIR) return CLAWS_CONSTANTS.COLORS.POOR;
            return CLAWS_CONSTANTS.COLORS.CRITICAL;
        },

        /**
         * Get security color based on level
         */
        getSecurityColor: function(level) {
            const colors = {
                'Very Good': CLAWS_CONSTANTS.COLORS.EXCELLENT, 'Very Safe': CLAWS_CONSTANTS.COLORS.EXCELLENT,
                'Good': CLAWS_CONSTANTS.COLORS.GOOD, 'Safe': CLAWS_CONSTANTS.COLORS.GOOD,
                'Sufficient': CLAWS_CONSTANTS.COLORS.POOR, 'Somewhat Safe': CLAWS_CONSTANTS.COLORS.POOR,
                'Marginal': '#fb7185', 'Unsafe': '#fb7185',
                'Insufficient': CLAWS_CONSTANTS.COLORS.CRITICAL, 'Dangerous': CLAWS_CONSTANTS.COLORS.CRITICAL
            };
            return colors[level] || CLAWS_CONSTANTS.COLORS.GRAY_600;
        },

    };

    // SILENT BLOCKING SYSTEM - PREVENT INFINITE LOOPS FROM EXTERNAL MONITORING
    let hasBlockedOnce = false;
    console.log = (function(originalLog) {
        return function(...args) {
            // Silently block any console.log that mentions clawsData to prevent hook-triggered loops
            const message = args.join(' ');
            if (message.includes('Current clawsData') || (message.includes('clawsData') && message.includes('Proxy'))) {
                if (!hasBlockedOnce) {
                    hasBlockedOnce = true;
                }
                return; // Silently block the problematic logging
            }
            return originalLog.apply(console, args);
        };
    })(console.log);

    // GLOBAL CLAWSDATA ACCESS INTERCEPTOR
    if (typeof window.clawsData !== 'undefined') {
        const originalClawsData = window.clawsData;
        let accessCount = 0;
        
        // Simplified proxy - just prevent hook loops, no debugging popups
        window.clawsData = new Proxy(originalClawsData, {
            get: function(target, property, receiver) {
                accessCount++;
                
                // Silent access - no logging to prevent triggering external hooks
                return Reflect.get(target, property, receiver);
            }
        });
        
    }

    // EXTERNAL CALL PROTECTION: Block repeated external access attempts
    if (window.CLAWSApp) {
        // Create protected wrapper for commonly abused functions
        const originalForceColorUpdate = window.CLAWSApp.forceColorUpdate;
        if (typeof originalForceColorUpdate === 'function') {
            window.CLAWSApp.forceColorUpdate = function() {
                return false;
            };
        }
        
        // Global protection wrapper
        window._CLAWSProtection = {
            callCount: 0,
            maxCalls: 3,
            blockedFunctions: ['forceColorUpdate', 'getCurrentClawsData'],
            
            wrapFunction: function(obj, funcName) {
                if (typeof obj[funcName] === 'function') {
                    const originalFunc = obj[funcName];
                    obj[funcName] = function() {
                        this.callCount++;
                        if (this.callCount > this.maxCalls) {
                            return false;
                        }
                        return originalFunc.apply(obj, arguments);
                    }.bind(this);
                }
            }
        };
        
        // Apply protection to commonly abused functions
        window._CLAWSProtection.blockedFunctions.forEach(funcName => {
            if (window.CLAWSApp[funcName]) {
                window._CLAWSProtection.wrapFunction(window.CLAWSApp, funcName);
            }
        });
    }

    // Auto-initialize when DOM is ready (only once)
    $(document).ready(function() {
        if (window.CLAWSApp) {
            CLAWSApp.initialize();
        }
    });

})(jQuery);