class TouchControls {
    constructor(canvas, inputHandler) {
        this.canvas = canvas;
        this.input = inputHandler;
        this.touchZones = {
            left: { x: 0, y: 0, width: 0, height: 0 },
            right: { x: 0, y: 0, width: 0, height: 0 },
            jump: { x: 0, y: 0, width: 0, height: 0 },
            crouch: { x: 0, y: 0, width: 0, height: 0 }
        };
        
        this.lastTapTime = 0;
        this.doubleTapDelay = 300; // ms
        this.lastTapSide = null;
        
        this.setupTouchZones();
        this.addTouchListeners();
    }
    
    setupTouchZones() {
        // Usar dimensiones del canvas directamente
        const width = this.canvas.width;
        const height = this.canvas.height;
        
        // Zona izquierda (1/3 izquierdo, parte inferior)
        this.touchZones.left = {
            x: 0,
            y: height * 0.4, // Desde 40% hacia abajo
            width: width * 0.35,
            height: height * 0.6
        };
        
        // Zona derecha (1/3 derecho, parte inferior)
        this.touchZones.right = {
            x: width * 0.65,
            y: height * 0.4,
            width: width * 0.35,
            height: height * 0.6
        };
        
        // Zona de salto (mitad superior)
        this.touchZones.jump = {
            x: 0,
            y: 0,
            width: width,
            height: height * 0.4
        };
        
        // Zona de agacharse (centro inferior)
        this.touchZones.crouch = {
            x: width * 0.35,
            y: height * 0.8,
            width: width * 0.3,
            height: height * 0.2
        };
    }
    
    addTouchListeners() {
        // Prevenir comportamiento por defecto del navegador
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            this.handleTouchStart(e);
        }, { passive: false });
        
        this.canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            this.handleTouchEnd(e);
        }, { passive: false });
        
        this.canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
        }, { passive: false });
        
        // Redimensionar zonas cuando cambie el tamaño
        window.addEventListener('resize', () => {
            this.setupTouchZones();
        });
    }
    
    getTouchPosition(touch) {
        const rect = this.canvas.getBoundingClientRect();
        const scaleX = this.canvas.width / rect.width;
        const scaleY = this.canvas.height / rect.height;
        
        return {
            x: (touch.clientX - rect.left) * scaleX,
            y: (touch.clientY - rect.top) * scaleY
        };
    }
    
    isInZone(pos, zone) {
        return pos.x >= zone.x && 
               pos.x <= zone.x + zone.width && 
               pos.y >= zone.y && 
               pos.y <= zone.y + zone.height;
    }
    
    handleTouchStart(e) {
        for (let touch of e.touches) {
            const pos = this.getTouchPosition(touch);
            
            console.log('Touch at:', pos.x, pos.y);
            console.log('Zones:', this.touchZones);
            
            if (this.isInZone(pos, this.touchZones.jump)) {
                console.log('Jump zone touched');
                // Simular tecla W presionada
                this.input.keys.W = true;
                this.input.keys.w = true;
            } else if (this.isInZone(pos, this.touchZones.crouch)) {
                console.log('Crouch zone touched');
                // Simular tecla ArrowDown presionada
                this.input.keys.ArrowDown = true;
                this.input.keys.s = true;
                this.input.keys.S = true;
            } else if (this.isInZone(pos, this.touchZones.left)) {
                console.log('Left zone touched');
                // Simular tecla A presionada
                this.input.keys.A = true;
                this.input.keys.a = true;
                this.checkDoubleTap('left');
            } else if (this.isInZone(pos, this.touchZones.right)) {
                console.log('Right zone touched');
                // Simular tecla D presionada
                this.input.keys.D = true;
                this.input.keys.d = true;
                this.checkDoubleTap('right');
            }
        }
    }
    
    handleTouchEnd(e) {
        // Liberar todas las teclas cuando se levanta el dedo
        this.input.keys.A = false;
        this.input.keys.a = false;
        this.input.keys.D = false;
        this.input.keys.d = false;
        this.input.keys.W = false;
        this.input.keys.w = false;
        this.input.keys.ArrowDown = false;
        this.input.keys.s = false;
        this.input.keys.S = false;
        console.log('Touch ended - all keys released');
    }
    
    checkDoubleTap(side) {
        const now = Date.now();
        
        if (this.lastTapSide === side && 
            now - this.lastTapTime < this.doubleTapDelay) {
            // Doble tap detectado - activar dash direccional
            this.input.keys.Shift = true;
            
            // Liberar Shift después de un frame
            setTimeout(() => {
                this.input.keys.Shift = false;
            }, 50);
            
            this.lastTapTime = 0; // Resetear para evitar múltiples activaciones
        } else {
            this.lastTapTime = now;
            this.lastTapSide = side;
        }
    }
    
    // Método para dibujar las zonas táctiles (debug)
    drawTouchZones(ctx) {
        if (!this.showDebug) return;
        
        ctx.save();
        ctx.globalAlpha = 0.3;
        
        // Zona izquierda
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(
            this.touchZones.left.x,
            this.touchZones.left.y,
            this.touchZones.left.width,
            this.touchZones.left.height
        );
        
        // Zona derecha
        ctx.fillStyle = '#00ff00';
        ctx.fillRect(
            this.touchZones.right.x,
            this.touchZones.right.y,
            this.touchZones.right.width,
            this.touchZones.right.height
        );
        
        // Zona de salto
        ctx.fillStyle = '#0000ff';
        ctx.fillRect(
            this.touchZones.jump.x,
            this.touchZones.jump.y,
            this.touchZones.jump.width,
            this.touchZones.jump.height
        );
        
        // Zona de agacharse
        ctx.fillStyle = '#ffff00';
        ctx.fillRect(
            this.touchZones.crouch.x,
            this.touchZones.crouch.y,
            this.touchZones.crouch.width,
            this.touchZones.crouch.height
        );
        
        ctx.restore();
    }
    
    toggleDebug() {
        this.showDebug = !this.showDebug;
    }
}

// Exportar para uso global
window.TouchControls = TouchControls;