// mobile.js - Fixed fullscreen sidebar behavior with textbox preservation

class MobileManager {
    constructor() {
        this.breakpoints = {
            desktop: 1024,
            tablet: 768,
            mobile: 480,
            narrow: 320,
            superNarrow: 280
        };
        this.currentBreakpoint = this.getCurrentBreakpoint();
        this.sidebarOpen = false;
        this.peopleSidebarOpen = false;
        this.init();
    }

    getCurrentBreakpoint() {
        const width = window.innerWidth;
        if (width >= this.breakpoints.desktop) return 'desktop';
        if (width >= this.breakpoints.tablet) return 'tablet';
        if (width >= this.breakpoints.mobile) return 'mobile';
        if (width >= this.breakpoints.narrow) return 'narrow';
        return 'super-narrow';
    }

    init() {
        console.log('Initializing mobile interface for:', this.currentBreakpoint);
        this.createMobileOverlay();
        this.createMobileHeader();
        this.setupEventListeners();
        this.overrideCollapseButtons();
        this.applyResponsiveStyles();
        this.handleResize();
        this.enhanceTouchInteractions();
    }

    createMobileOverlay() {
        const overlay = document.createElement('div');
        overlay.className = 'mobile-overlay';
        overlay.id = 'mobileOverlay';
        document.body.appendChild(overlay);

        overlay.addEventListener('click', () => {
            this.closeAllSidebars();
        });
    }

    createMobileHeader() {
        const mainContent = document.querySelector('.main-content');
        if (!mainContent) return;

        const header = document.createElement('div');
        header.className = 'mobile-header';
        header.innerHTML = `
            <button class="mobile-menu-button" id="mobileMenuButton" aria-label="Toggle channels">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M3 12H21M3 6H21M3 18H21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </button>
            <h1 class="mobile-title" id="mobileTitle">IRCD</h1>
            <button class="mobile-menu-button" id="mobilePeopleButton" aria-label="Toggle people list">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M17 21V19C17 17.9391 16.5786 16.9217 15.8284 16.1716C15.0783 15.4214 14.0609 15 13 15H5C3.93913 15 2.92172 15.4214 2.17157 16.1716C1.42143 16.9217 1 17.9391 1 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    <circle cx="9" cy="7" r="4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </button>
        `;

        mainContent.insertBefore(header, mainContent.firstChild);
    }

    overrideCollapseButtons() {
        // Override the channels sidebar toggle button (left sidebar)
        const sidebarToggle = document.getElementById('toggleSidebar');
        if (sidebarToggle) {
            const newToggle = sidebarToggle.cloneNode(true);
            sidebarToggle.parentNode.replaceChild(newToggle, sidebarToggle);
            
            newToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                if (this.isMobile()) {
                    // On mobile: close the channels sidebar instead of collapsing
                    this.closeSidebar();
                } else {
                    // On desktop: use original collapse behavior for channels sidebar
                    if (typeof window.toggleSidebar === 'function') {
                        window.toggleSidebar();
                    }
                }
            });
        }

        // Override the people sidebar toggle button (right sidebar)
        const peopleToggle = document.getElementById('togglePeopleSidebar');
        if (peopleToggle) {
            const newPeopleToggle = peopleToggle.cloneNode(true);
            peopleToggle.parentNode.replaceChild(newPeopleToggle, peopleToggle);
            
            newPeopleToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                if (this.isMobile()) {
                    // On mobile: close the people sidebar instead of collapsing
                    this.closePeopleSidebar();
                } else {
                    // On desktop: use original collapse behavior for people sidebar
                    if (typeof window.togglePeopleSidebar === 'function') {
                        window.togglePeopleSidebar();
                    }
                }
            });
        }

        this.updateToggleButtonIcons();
    }

    updateToggleButtonIcons() {
        const sidebarToggle = document.getElementById('toggleSidebar');
        const peopleToggle = document.getElementById('togglePeopleSidebar');
        
        if (sidebarToggle) {
            const icon = sidebarToggle.querySelector('svg');
            if (icon) {
                if (this.isMobile() && this.sidebarOpen) {
                    // Show close icon (X) when channels sidebar is open on mobile
                    icon.innerHTML = '<path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
                } else {
                    // Show collapse icon (chevron)
                    icon.innerHTML = '<path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
                }
            }
        }
        
        if (peopleToggle) {
            const icon = peopleToggle.querySelector('svg');
            if (icon) {
                if (this.isMobile() && this.peopleSidebarOpen) {
                    // Show close icon (X) when people sidebar is open on mobile
                    icon.innerHTML = '<path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
                } else {
                    // Show collapse icon (chevron)
                    icon.innerHTML = '<path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
                }
            }
        }
    }

    setupEventListeners() {
        // Mobile menu buttons - only control channels and people sidebars
        document.getElementById('mobileMenuButton')?.addEventListener('click', (e) => {
            e.stopPropagation();
            this.toggleSidebar();
        });

        document.getElementById('mobilePeopleButton')?.addEventListener('click', (e) => {
            e.stopPropagation();
            this.togglePeopleSidebar();
        });

        // Touch events
        this.setupTouchEvents();

        // Orientation and resize
        window.addEventListener('orientationchange', () => {
            setTimeout(() => this.handleResize(), 150);
        });

        window.addEventListener('resize', () => this.throttle(this.handleResize.bind(this), 250));

        // Fixed: Don't close sidebars when clicking on form elements
        document.addEventListener('click', (e) => {
            if (this.isMobile() && 
                !e.target.closest('#channels') && 
                !e.target.closest('#peopleSidebar') && 
                !e.target.closest('.mobile-menu-button') &&
                // Don't close sidebars when clicking on form inputs
                !e.target.matches('input, textarea, select')) {
                this.closeAllSidebars();
            }
        });

        // Keyboard handling
        this.setupKeyboardHandling();
    }

    setupTouchEvents() {
        let touchStartX = 0;
        let touchStartY = 0;

        document.addEventListener('touchstart', (e) => {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
        });

        document.addEventListener('touchend', (e) => {
            if (!this.isMobile()) return;

            const touchEndX = e.changedTouches[0].clientX;
            const touchEndY = e.changedTouches[0].clientY;
            const diffX = touchEndX - touchStartX;
            const diffY = touchEndY - touchStartY;

            // Only handle horizontal swipes with minimal vertical movement
            if (Math.abs(diffX) > 50 && Math.abs(diffY) < 30) {
                if (diffX > 0) {
                    // Swipe right - open channels sidebar
                    this.toggleSidebar();
                } else {
                    // Swipe left - open people sidebar or close open ones
                    if (this.sidebarOpen) {
                        this.closeSidebar();
                    } else {
                        this.togglePeopleSidebar();
                    }
                }
            }
        });

        // Better touch feedback
        document.querySelectorAll('button, .channel-item, .people-item, .tab').forEach(element => {
            element.addEventListener('touchstart', function() {
                this.classList.add('touch-active');
            });
            
            element.addEventListener('touchend', function() {
                this.classList.remove('touch-active');
            });
            
            element.addEventListener('touchcancel', function() {
                this.classList.remove('touch-active');
            });
        });
    }

    setupKeyboardHandling() {
        if ('visualViewport' in window) {
            const visualViewport = window.visualViewport;
            
            visualViewport.addEventListener('resize', () => {
                this.handleKeyboardResize(visualViewport);
            });

            visualViewport.addEventListener('scroll', () => {
                this.handleKeyboardScroll(visualViewport);
            });
        }

        // Fixed: Only auto-close sidebars when focusing on main message input
        document.addEventListener('focusin', (e) => {
            if (this.isMobile() && e.target.id === 'messageInput') {
                this.closeAllSidebars();
            }
            // Don't close sidebars for other input types (connection form, etc.)
        });
    }

    handleKeyboardResize(viewport) {
        // Handle virtual keyboard appearance
        if (this.isMobile()) {
            const composer = document.querySelector('.composer');
            if (composer) {
                composer.style.marginBottom = '0px';
            }
        }
    }

    handleKeyboardScroll(viewport) {
        // Adjust scroll when keyboard appears
        if (this.isMobile()) {
            setTimeout(() => {
                const messages = document.querySelector('.messages');
                if (messages) {
                    messages.scrollTop = messages.scrollHeight;
                }
            }, 100);
        }
    }

    toggleSidebar() {
        const sidebar = document.getElementById('channels');
        const overlay = document.getElementById('mobileOverlay');
        
        if (!sidebar || !overlay) return;

        if (this.sidebarOpen) {
            this.closeSidebar();
        } else {
            this.closeAllSidebars();
            sidebar.classList.add('active');
            overlay.classList.add('active');
            this.sidebarOpen = true;
            this.updateMobileTitle('Channels');
            this.updateToggleButtonIcons();
        }
    }

    togglePeopleSidebar() {
        const peopleSidebar = document.getElementById('peopleSidebar');
        const overlay = document.getElementById('mobileOverlay');
        
        if (!peopleSidebar || !overlay) return;

        if (this.peopleSidebarOpen) {
            this.closePeopleSidebar();
        } else {
            this.closeAllSidebars();
            peopleSidebar.classList.add('active');
            overlay.classList.add('active');
            this.peopleSidebarOpen = true;
            this.updateMobileTitle('People');
            this.updateToggleButtonIcons();
        }
    }

    closeSidebar() {
        const sidebar = document.getElementById('channels');
        const overlay = document.getElementById('mobileOverlay');
        
        if (sidebar) sidebar.classList.remove('active');
        if (overlay) overlay.classList.remove('active');
        this.sidebarOpen = false;
        this.updateMobileTitle();
        this.updateToggleButtonIcons();
    }

    closePeopleSidebar() {
        const peopleSidebar = document.getElementById('peopleSidebar');
        const overlay = document.getElementById('mobileOverlay');
        
        if (peopleSidebar) peopleSidebar.classList.remove('active');
        if (overlay) overlay.classList.remove('active');
        this.peopleSidebarOpen = false;
        this.updateMobileTitle();
        this.updateToggleButtonIcons();
    }

    closeAllSidebars() {
        this.closeSidebar();
        this.closePeopleSidebar();
    }

    updateMobileTitle(title = '') {
        const mobileTitle = document.getElementById('mobileTitle');
        if (!mobileTitle) return;

        if (title) {
            mobileTitle.textContent = this.truncateText(title, this.getMaxTitleLength());
        } else {
            const activeTab = document.querySelector('.tab.active');
            if (activeTab) {
                const tabText = activeTab.textContent.replace('×', '').trim();
                mobileTitle.textContent = this.truncateText(tabText, this.getMaxTitleLength());
            } else {
                mobileTitle.textContent = 'IRCD';
            }
        }
    }

    truncateText(text, maxLength) {
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength - 3) + '...';
    }

    getMaxTitleLength() {
        const width = window.innerWidth;
        if (width < this.breakpoints.superNarrow) return 12;
        if (width < this.breakpoints.narrow) return 15;
        if (width < this.breakpoints.mobile) return 20;
        return 25;
    }

    applyResponsiveStyles() {
        const style = document.createElement('style');
        style.textContent = this.generateResponsiveCSS();
        document.head.appendChild(style);

        this.updateResponsiveClasses();
    }

    updateResponsiveClasses() {
        const breakpoint = this.currentBreakpoint;
        document.body.className = document.body.className.replace(/\b(desktop|tablet|mobile|narrow-screen|super-narrow)\b/g, '');
        document.body.classList.add(breakpoint === 'narrow' ? 'narrow-screen' : breakpoint);
        document.body.classList.add('mobile-device');
    }

    handleResize() {
        const previousBreakpoint = this.currentBreakpoint;
        this.currentBreakpoint = this.getCurrentBreakpoint();
        
        if (previousBreakpoint !== this.currentBreakpoint) {
            console.log('Breakpoint changed:', previousBreakpoint, '→', this.currentBreakpoint);
            this.updateResponsiveClasses();
            this.updateMobileTitle();
            this.adjustLayoutForBreakpoint();
            this.updateToggleButtonIcons();
            
            // Close sidebars when switching to mobile layout
            if (this.isMobile() && !previousBreakpoint.includes('mobile') && !previousBreakpoint.includes('narrow')) {
                this.closeAllSidebars();
            }
        }
        
        this.adjustComposerForMobile();
    }

    adjustLayoutForBreakpoint() {
        const breakpoint = this.currentBreakpoint;
        
        // Adjust tab bar for narrow screens
        const tabs = document.querySelector('.tabs');
        if (tabs) {
            if (breakpoint === 'super-narrow') {
                tabs.style.flexWrap = 'nowrap';
                tabs.style.overflowX = 'auto';
            } else {
                tabs.style.flexWrap = '';
                tabs.style.overflowX = '';
            }
        }
        
        // Adjust message layout
        const messages = document.querySelector('.messages');
        if (messages) {
            if (breakpoint === 'super-narrow') {
                messages.classList.add('narrow-layout');
            } else {
                messages.classList.remove('narrow-layout');
            }
        }

        // Only hide collapse buttons for channels/people sidebars, not server section
        const sidebarToggle = document.querySelector('#channels .toggle-sidebar');
        const peopleToggle = document.querySelector('#peopleSidebar .toggle-people-sidebar');
        
        if (this.isMobile()) {
            if (sidebarToggle) sidebarToggle.style.display = 'none';
            if (peopleToggle) peopleToggle.style.display = 'none';
        } else {
            if (sidebarToggle) sidebarToggle.style.display = '';
            if (peopleToggle) peopleToggle.style.display = '';
        }
    }

    adjustComposerForMobile() {
        const composer = document.querySelector('.composer');
        const messages = document.querySelector('.messages');
        
        if (!composer || !messages) return;

        if (this.isMobile()) {
            messages.style.paddingBottom = '90px';
        } else {
            messages.style.paddingBottom = '';
        }
    }

    enhanceTouchInteractions() {
        let lastTap = 0;
        document.addEventListener('touchend', (e) => {
            const currentTime = new Date().getTime();
            const tapLength = currentTime - lastTap;
            
            if (tapLength < 500 && tapLength > 0) {
                const messageLine = e.target.closest('.message-line');
                if (messageLine && !e.target.closest('.message-sender')) {
                    this.handleDoubleTapMessage(messageLine);
                }
            }
            lastTap = currentTime;
        });
    }

    handleDoubleTapMessage(messageLine) {
        messageLine.style.backgroundColor = '#3A3A3A';
        setTimeout(() => {
            messageLine.style.backgroundColor = '';
        }, 300);
    }

    isMobile() {
        return this.currentBreakpoint !== 'desktop';
    }

    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        }
    }

    // Public methods for integration
    handleNewMessage() {
        if (this.isMobile() && (this.sidebarOpen || this.peopleSidebarOpen)) {
            setTimeout(() => this.closeAllSidebars(), 1500);
        }
    }

    handleChannelSwitch(channelName) {
        if (this.isMobile()) {
            this.closeAllSidebars();
            this.updateMobileTitle();
        }
    }

    setupMessageInput() {
        const messageInput = document.getElementById('messageInput');
        if (!messageInput) return;

        messageInput.addEventListener('focus', () => {
            if (this.isMobile()) {
                setTimeout(() => {
                    const messages = document.querySelector('.messages');
                    if (messages) {
                        messages.scrollTop = messages.scrollHeight;
                    }
                }, 300);
            }
        });

        messageInput.addEventListener('keypress', (e) => {
            if (this.isMobile() && e.key === 'Enter') {
                e.preventDefault();
                setTimeout(() => {
                    const sendBtn = document.getElementById('sendBtn');
                    if (sendBtn) sendBtn.click();
                }, 100);
            }
        });
    }
}

// Initialize mobile manager
document.addEventListener('DOMContentLoaded', () => {
    window.mobileManager = new MobileManager();
    integrateWithExistingApp();
});

// Integration with existing app
function integrateWithExistingApp() {
    // Override setActiveTab
    const originalSetActiveTab = window.setActiveTab;
    if (originalSetActiveTab) {
        window.setActiveTab = function(name) {
            originalSetActiveTab(name);
            if (window.mobileManager) {
                window.mobileManager.handleChannelSwitch(name);
            }
        };
    }

    // Override addMessage
    const originalAddMessage = window.addMessage;
    if (originalAddMessage) {
        window.addMessage = function(sender, content, isUser = false) {
            originalAddMessage(sender, content, isUser);
            if (window.mobileManager) {
                window.mobileManager.handleNewMessage();
            }
        };
    }

    // Override addSystemMessage
    const originalAddSystemMessage = window.addSystemMessage;
    if (originalAddSystemMessage) {
        window.addSystemMessage = function(content) {
            originalAddSystemMessage(content);
            if (window.mobileManager) {
                window.mobileManager.handleNewMessage();
            }
        };
    }

    // Override the original toggle functions
    if (window.toggleSidebar) {
        const originalToggleSidebar = window.toggleSidebar;
        window.toggleSidebar = function() {
            if (window.mobileManager && window.mobileManager.isMobile()) {
                window.mobileManager.toggleSidebar();
            } else {
                originalToggleSidebar();
            }
        };
    }

    if (window.togglePeopleSidebar) {
        const originalTogglePeopleSidebar = window.togglePeopleSidebar;
        window.togglePeopleSidebar = function() {
            if (window.mobileManager && window.mobileManager.isMobile()) {
                window.mobileManager.togglePeopleSidebar();
            } else {
                originalTogglePeopleSidebar();
            }
        };
    }

    // Setup mobile message input
    setTimeout(() => {
        if (window.mobileManager) {
            window.mobileManager.setupMessageInput();
        }
    }, 1000);
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = MobileManager;
}