/**
 * InsertrAuth - Authentication and state management
 * Handles user authentication, edit mode, and visual state changes
 */
export class InsertrAuth {
    constructor(options = {}) {
        this.options = {
            mockAuth: options.mockAuth !== false, // Enable mock auth by default
            hideGatesAfterAuth: options.hideGatesAfterAuth === true, // Keep gates visible by default
            ...options
        };

        // Authentication state
        this.state = {
            isAuthenticated: false,
            editMode: false,
            currentUser: null,
            activeEditor: null,
            isInitialized: false,
            isAuthenticating: false
        };

        this.statusIndicator = null;
    }

    /**
     * Initialize gate system (called on page load)
     */
    init() {
        console.log('🔧 Insertr: Scanning for editor gates');
        
        this.setupEditorGates();
    }

    /**
     * Initialize full editing system (called after successful OAuth)
     */
    initializeFullSystem() {
        if (this.state.isInitialized) {
            return; // Already initialized
        }

        console.log('🔐 Initializing Insertr Editing System');
        
        this.createAuthControls();
        this.setupAuthenticationControls();
        this.createStatusIndicator();
        this.updateBodyClasses();
        
        // Auto-enable edit mode after OAuth
        this.state.editMode = true;
        this.state.isInitialized = true;
        
        // Start the editor system
        if (window.Insertr && window.Insertr.startEditor) {
            window.Insertr.startEditor();
        }
        
        this.updateButtonStates();
        this.updateStatusIndicator();
        
        console.log('📱 Editing system active - Controls in bottom-right corner');
        console.log('✏️ Edit mode enabled - Click elements to edit');
    }

    /**
     * Setup editor gate click handlers for any .insertr-gate elements
     */
    setupEditorGates() {
        const gates = document.querySelectorAll('.insertr-gate');
        
        if (gates.length === 0) {
            console.log('ℹ️  No .insertr-gate elements found - editor access disabled');
            return;
        }

        console.log(`🚪 Found ${gates.length} editor gate(s)`);
        
        // Add gate styles
        this.addGateStyles();
        
        gates.forEach((gate, index) => {
            // Store original text for later restoration
            if (!gate.hasAttribute('data-original-text')) {
                gate.setAttribute('data-original-text', gate.textContent);
            }
            
            gate.addEventListener('click', (e) => {
                e.preventDefault();
                this.handleGateClick(gate, index);
            });
            
            // Add subtle styling to indicate it's clickable
            gate.style.cursor = 'pointer';
        });
    }

    /**
     * Handle click on an editor gate element
     */
    async handleGateClick(gateElement, gateIndex) {
        // Prevent multiple simultaneous authentication attempts
        if (this.state.isAuthenticating) {
            console.log('⏳ Authentication already in progress...');
            return;
        }

        console.log(`🚀 Editor gate activated (gate ${gateIndex + 1})`);
        this.state.isAuthenticating = true;
        
        // Store original text and show loading state
        const originalText = gateElement.textContent;
        gateElement.setAttribute('data-original-text', originalText);
        gateElement.textContent = '⏳ Signing in...';
        gateElement.style.pointerEvents = 'none';
        
        try {
            // Perform OAuth authentication
            await this.performOAuthFlow();
            
            // Initialize full editing system
            this.initializeFullSystem();
            
            // Conditionally hide gates based on options
            if (this.options.hideGatesAfterAuth) {
                this.hideAllGates();
            } else {
                this.updateGateState();
            }
            
        } catch (error) {
            console.error('❌ Authentication failed:', error);
            
            // Restore clicked gate to original state
            const originalText = gateElement.getAttribute('data-original-text');
            if (originalText) {
                gateElement.textContent = originalText;
            }
            gateElement.style.pointerEvents = '';
        } finally {
            this.state.isAuthenticating = false;
        }
    }

    /**
     * Perform OAuth authentication flow
     */
    async performOAuthFlow() {
        // In development, simulate OAuth flow
        if (this.options.mockAuth) {
            console.log('🔐 Mock OAuth: Simulating authentication...');
            
            // Simulate network delay
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            // Set authenticated state
            this.state.isAuthenticated = true;
            this.state.currentUser = {
                name: 'Site Owner',
                email: 'owner@example.com',
                role: 'admin'
            };
            
            console.log('✅ Mock OAuth: Authentication successful');
            return;
        }
        
        // TODO: In production, implement real OAuth flow
        // This would redirect to OAuth provider, handle callback, etc.
        throw new Error('Production OAuth not implemented yet');
    }

    /**
     * Hide all editor gates after successful authentication (optional)
     */
    hideAllGates() {
        document.body.classList.add('insertr-hide-gates');
        console.log('🚪 Editor gates hidden (hideGatesAfterAuth enabled)');
    }

    /**
     * Update gate state after authentication (restore normal appearance)
     */
    updateGateState() {
        const gates = document.querySelectorAll('.insertr-gate');
        gates.forEach(gate => {
            // Restore original text if it was saved
            const originalText = gate.getAttribute('data-original-text');
            if (originalText) {
                gate.textContent = originalText;
            }
            
            // Restore interactive state
            gate.style.pointerEvents = '';
            gate.style.opacity = '';
        });
        
        console.log('🚪 Editor gates restored to original state');
    }

    /**
     * Create authentication control buttons (bottom-right positioned)
     */
    createAuthControls() {
        // Check if controls already exist
        if (document.getElementById('insertr-auth-controls')) {
            return;
        }

        const controlsHtml = `
            <div id="insertr-auth-controls" class="insertr-auth-controls">
                <button id="insertr-auth-toggle" class="insertr-auth-btn">Login as Client</button>
                <button id="insertr-edit-toggle" class="insertr-auth-btn" style="display: none;">Edit Mode: Off</button>
            </div>
        `;

        // Add controls to page
        document.body.insertAdjacentHTML('beforeend', controlsHtml);
        
        // Add styles for controls
        this.addControlStyles();
    }

    /**
     * Setup event listeners for authentication controls
     */
    setupAuthenticationControls() {
        const authToggle = document.getElementById('insertr-auth-toggle');
        const editToggle = document.getElementById('insertr-edit-toggle');

        if (authToggle) {
            authToggle.addEventListener('click', () => this.toggleAuthentication());
        }

        if (editToggle) {
            editToggle.addEventListener('click', () => this.toggleEditMode());
        }


    }

    /**
     * Toggle authentication state
     */
    toggleAuthentication() {
        this.state.isAuthenticated = !this.state.isAuthenticated;
        this.state.currentUser = this.state.isAuthenticated ? { 
            name: 'Demo User', 
            email: 'demo@example.com',
            role: 'editor'
        } : null;

        // Reset edit mode when logging out
        if (!this.state.isAuthenticated) {
            this.state.editMode = false;
        }

        this.updateBodyClasses();
        this.updateButtonStates();
        this.updateStatusIndicator();

        console.log(this.state.isAuthenticated 
            ? '✅ Authenticated as Demo User' 
            : '❌ Logged out');
    }

    /**
     * Toggle edit mode (only when authenticated)
     */
    toggleEditMode() {
        if (!this.state.isAuthenticated) {
            console.warn('❌ Cannot enable edit mode - not authenticated');
            return;
        }

        this.state.editMode = !this.state.editMode;

        // Cancel any active editing when turning off edit mode
        if (!this.state.editMode && this.state.activeEditor) {
            // This would be handled by the main editor
            this.state.activeEditor = null;
        }

        this.updateBodyClasses();
        this.updateButtonStates();
        this.updateStatusIndicator();

        console.log(this.state.editMode 
            ? '✏️ Edit mode ON - Click elements to edit' 
            : '👀 Edit mode OFF - Read-only view');
    }

    /**
     * Update body CSS classes based on authentication state
     */
    updateBodyClasses() {
        document.body.classList.toggle('insertr-authenticated', this.state.isAuthenticated);
        document.body.classList.toggle('insertr-edit-mode', this.state.editMode);
    }

    /**
     * Update button text and visibility
     */
    updateButtonStates() {
        const authBtn = document.getElementById('insertr-auth-toggle');
        const editBtn = document.getElementById('insertr-edit-toggle');

        if (authBtn) {
            authBtn.textContent = this.state.isAuthenticated ? 'Logout' : 'Login as Client';
            authBtn.className = `insertr-auth-btn ${this.state.isAuthenticated ? 'insertr-authenticated' : ''}`;
        }

        if (editBtn) {
            editBtn.style.display = this.state.isAuthenticated ? 'inline-block' : 'none';
            editBtn.textContent = `Edit Mode: ${this.state.editMode ? 'On' : 'Off'}`;
            editBtn.className = `insertr-auth-btn ${this.state.editMode ? 'insertr-edit-active' : ''}`;
        }

        // Update enhance button visibility
        this.updateEnhanceButtonVisibility();
    }

    /**
     * Create status indicator
     */
    createStatusIndicator() {
        // Check if already exists
        if (document.getElementById('insertr-status')) {
            return;
        }

        const statusHtml = `
            <div id="insertr-status-controls" class="insertr-status-controls">
                <div id="insertr-status" class="insertr-status">
                    <div class="insertr-status-content">
                        <span class="insertr-status-text">Visitor Mode</span>
                        <span class="insertr-status-dot"></span>
                    </div>
                </div>
                <button id="insertr-enhance-btn" class="insertr-auth-btn" style="display: none;" title="Enhance files with latest content">🔄 Enhance</button>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', statusHtml);
        this.statusIndicator = document.getElementById('insertr-status');
        this.setupEnhanceButton();
        this.updateStatusIndicator();
    }

    /**
     * Update status indicator text and style
     */
    updateStatusIndicator() {
        const statusText = document.querySelector('.insertr-status-text');
        const statusDot = document.querySelector('.insertr-status-dot');
        
        if (!statusText || !statusDot) return;

        if (!this.state.isAuthenticated) {
            statusText.textContent = 'Visitor Mode';
            statusDot.className = 'insertr-status-dot insertr-status-visitor';
        } else if (this.state.editMode) {
            statusText.textContent = 'Editing';
            statusDot.className = 'insertr-status-dot insertr-status-editing';
        } else {
            statusText.textContent = 'Authenticated';
            statusDot.className = 'insertr-status-dot insertr-status-authenticated';
        }


    }

    /**
     * Check if user is authenticated
     */
    isAuthenticated() {
        return this.state.isAuthenticated;
    }

    /**
     * Check if edit mode is enabled
     */
    isEditMode() {
        return this.state.editMode;
    }

    /**
     * Get current user info
     */
    getCurrentUser() {
        return this.state.currentUser;
    }

    /**
     * Add minimal styles for editor gates
     */
    addGateStyles() {
        const styles = `
            .insertr-gate {
                transition: opacity 0.2s ease;
                user-select: none;
            }

            .insertr-gate:hover {
                opacity: 0.7;
            }

            /* Optional: Hide gates when authenticated (only if hideGatesAfterAuth option is true) */
            body.insertr-hide-gates .insertr-gate {
                display: none !important;
            }
        `;

        const styleSheet = document.createElement('style');
        styleSheet.type = 'text/css';
        styleSheet.innerHTML = styles;
        document.head.appendChild(styleSheet);
    }

    /**
     * Add styles for authentication controls
     */
    addControlStyles() {
        const styles = `
            .insertr-auth-controls {
                position: fixed;
                bottom: 20px;
                right: 20px;
                z-index: 9999;
                display: flex;
                flex-direction: column;
                gap: 8px;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }

            .insertr-auth-btn {
                background: #4f46e5;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                transition: all 0.2s;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }

            .insertr-auth-btn:hover {
                background: #4338ca;
                transform: translateY(-1px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            }

            .insertr-auth-btn.insertr-authenticated {
                background: #059669;
            }

            .insertr-auth-btn.insertr-authenticated:hover {
                background: #047857;
            }

            .insertr-auth-btn.insertr-edit-active {
                background: #dc2626;
            }

            .insertr-auth-btn.insertr-edit-active:hover {
                background: #b91c1c;
            }

            .insertr-status-controls {
                position: fixed;
                bottom: 20px;
                left: 20px;
                z-index: 9999;
                display: flex;
                flex-direction: column;
                gap: 8px;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }

            .insertr-status {
                background: white;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                padding: 8px 12px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                max-width: 200px;
            }

            .insertr-status-content {
                display: flex;
                align-items: center;
                gap: 8px;
            }

            .insertr-status-text {
                font-size: 12px;
                font-weight: 500;
                color: #374151;
            }

            .insertr-status-dot {
                width: 8px;
                height: 8px;
                border-radius: 50%;
                background: #9ca3af;
            }

            .insertr-status-dot.insertr-status-visitor {
                background: #9ca3af;
            }

            .insertr-status-dot.insertr-status-authenticated {
                background: #059669;
            }

            .insertr-status-dot.insertr-status-editing {
                background: #dc2626;
                animation: insertr-pulse 2s infinite;
            }

            @keyframes insertr-pulse {
                0%, 100% { opacity: 1; }
                50% { opacity: 0.5; }
            }

            /* Hide editing interface when not in edit mode */
            body:not(.insertr-edit-mode) .insertr:hover::after {
                display: none !important;
            }

            /* Only show editing features when in edit mode */
            .insertr-authenticated.insertr-edit-mode .insertr {
                cursor: pointer;
            }

            .insertr-authenticated.insertr-edit-mode .insertr:hover {
                outline: 2px dashed #007cba !important;
                outline-offset: 2px !important;
                background-color: rgba(0, 124, 186, 0.05) !important;
            }
        `;

        const styleSheet = document.createElement('style');
        styleSheet.type = 'text/css';
        styleSheet.innerHTML = styles;
        document.head.appendChild(styleSheet);
    }

    /**
     * OAuth integration placeholder
     * In production, this would handle real OAuth flows
     */
    async authenticateWithOAuth(provider = 'google') {
        // Mock OAuth flow for now
        console.log(`🔐 Mock OAuth login with ${provider}`);
        
        // Simulate OAuth callback
        setTimeout(() => {
            this.state.isAuthenticated = true;
            this.state.currentUser = {
                name: 'OAuth User',
                email: 'user@example.com',
                provider: provider,
                role: 'editor'
            };
            
            this.updateBodyClasses();
            this.updateButtonStates();
            this.updateStatusIndicator();
            
            console.log('✅ OAuth authentication successful');
        }, 1000);
    }

    /**
     * Setup enhance button functionality
     */
    setupEnhanceButton() {
        const enhanceBtn = document.getElementById('insertr-enhance-btn');
        if (!enhanceBtn) return;

        enhanceBtn.addEventListener('click', async () => {
            await this.enhanceFiles();
        });

        // Show enhance button only in development/authenticated mode
        this.updateEnhanceButtonVisibility();
    }

    /**
     * Update enhance button visibility based on authentication state
     */
    updateEnhanceButtonVisibility() {
        const enhanceBtn = document.getElementById('insertr-enhance-btn');
        if (!enhanceBtn) return;

        // Show enhance button when authenticated (indicates dev mode)
        if (this.state.isAuthenticated) {
            enhanceBtn.style.display = 'inline-block';
        } else {
            enhanceBtn.style.display = 'none';
        }
    }

    /**
     * Trigger manual file enhancement
     */
    async enhanceFiles() {
        const enhanceBtn = document.getElementById('insertr-enhance-btn');
        if (!enhanceBtn) return;

        // Get site ID from window context or configuration
        const siteId = window.insertrConfig?.siteId || this.options.siteId || 'demo';

        try {
            // Show loading state
            enhanceBtn.textContent = '⏳ Enhancing...';
            enhanceBtn.disabled = true;

            // Smart server detection for enhance API (same logic as ApiClient)
            const isDevelopment = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
            const enhanceUrl = isDevelopment 
                ? `http://localhost:8080/api/enhance?site_id=${siteId}`  // Development: separate API server
                : `/api/enhance?site_id=${siteId}`;                     // Production: same-origin API

            // Call enhance API
            const response = await fetch(enhanceUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${this.state.currentUser?.token || 'mock-token'}`
                }
            });

            if (!response.ok) {
                throw new Error(`Enhancement failed: ${response.status} ${response.statusText}`);
            }

            const result = await response.json();
            console.log('✅ Files enhanced successfully:', result);

            // Show success state briefly
            enhanceBtn.textContent = '✅ Enhanced!';
            
            // Optional: Trigger page reload to show enhanced files
            setTimeout(() => {
                window.location.reload();
            }, 1000);

        } catch (error) {
            console.error('❌ Enhancement failed:', error);
            enhanceBtn.textContent = '❌ Failed';
            
            // Reset button after error
            setTimeout(() => {
                enhanceBtn.textContent = '🔄 Enhance';
                enhanceBtn.disabled = false;
            }, 2000);
        }
    }
}