// ====== Mobile-Specific Functionality ======

import { debounce, throttle } from '../core/utils.js';
import { $, $$ } from '../core/helpers.js';

class MobileManager {
    constructor() {
        this.isMobile = this.checkMobile();
        this.touchStart = { x: 0, y: 0 };
        this.init();
    }

    init() {
        this.setupTouchEvents();
        this.setupViewport();
        this.setupSwipeGestures();
        this.detectOrientation();
    }

    checkMobile() {
        return window.innerWidth <= 768 || 
               /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }

    setupTouchEvents() {
        // Improve touch interactions
        if (this.isMobile) {
            document.documentElement.classList.add('touch-device');
            
            // Prevent zoom on double-tap
            let lastTap = 0;
            document.addEventListener('touchend', (e) => {
                const currentTime = new Date().getTime();
                const tapLength = currentTime - lastTap;
                
                if (tapLength < 500 && tapLength > 0) {
                    e.preventDefault();
                }
                
                lastTap = currentTime;
            }, { passive: false });
        } else {
            document.documentElement.classList.add('mouse-device');
        }
    }

    setupViewport() {
        // Dynamically set viewport for different devices
        const viewport = document.querySelector('meta[name="viewport"]');
        if (viewport && this.isMobile) {
            viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes');
        }
    }

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

        document.addEventListener('touchstart', (e) => {
            touchStartX = e.changedTouches[0].screenX;
            touchStartY = e.changedTouches[0].screenY;
        });

        document.addEventListener('touchend', (e) => {
            const touchEndX = e.changedTouches[0].screenX;
            const touchEndY = e.changedTouches[0].screenY;
            
            const diffX = touchStartX - touchEndX;
            const diffY = touchStartY - touchEndY;

            // Minimum swipe distance
            if (Math.abs(diffX) < 50 && Math.abs(diffY) < 50) return;

            if (Math.abs(diffX) > Math.abs(diffY)) {
                // Horizontal swipe
                if (diffX > 0) {
                    this.onSwipe('left');
                } else {
                    this.onSwipe('right');
                }
            } else {
                // Vertical swipe
                if (diffY > 0) {
                    this.onSwipe('up');
                } else {
                    this.onSwipe('down');
                }
            }
        });
    }

    onSwipe(direction) {
        const event = new CustomEvent('swipe', {
            detail: { direction }
        });
        window.dispatchEvent(event);
        
        // Close modals/dropdowns on swipe down
        if (direction === 'down') {
            const activeModals = $$('.modal.active');
            activeModals.forEach(modal => modal.classList.remove('active'));
        }
    }

    detectOrientation() {
        const updateOrientation = () => {
            const orientation = window.innerHeight > window.innerWidth ? 'portrait' : 'landscape';
            document.documentElement.setAttribute('data-orientation', orientation);
            
            const event = new CustomEvent('orientationchange', {
                detail: { orientation }
            });
            window.dispatchEvent(event);
        };

        window.addEventListener('resize', throttle(updateOrientation, 250));
        updateOrientation();
    }

    // Vibration feedback (if supported)
    vibrate(pattern = 50) {
        if (navigator.vibrate && this.isMobile) {
            navigator.vibrate(pattern);
        }
    }

    // Prevent overscroll on body
    preventOverscroll() {
        if (!this.isMobile) return;

        document.addEventListener('touchmove', (e) => {
            if (e.scale !== 1) {
                e.preventDefault();
            }
        }, { passive: false });
    }

    // Safe area insets for notched devices
    getSafeAreaInsets() {
        const style = getComputedStyle(document.documentElement);
        
        return {
            top: parseInt(style.getPropertyValue('--safe-area-inset-top')) || 0,
            right: parseInt(style.getPropertyValue('--safe-area-inset-right')) || 0,
            bottom: parseInt(style.getPropertyValue('--safe-area-inset-bottom')) || 0,
            left: parseInt(style.getPropertyValue('--safe-area-inset-left')) || 0
        };
    }

    // Lock body scroll (for modals)
    lockBodyScroll() {
        if (this.isMobile) {
            document.body.style.overflow = 'hidden';
            document.body.style.position = 'fixed';
            document.body.style.width = '100%';
        }
    }

    unlockBodyScroll() {
        if (this.isMobile) {
            document.body.style.overflow = '';
            document.body.style.position = '';
            document.body.style.width = '';
        }
    }
}

// Create singleton instance
export const mobileManager = new MobileManager();