class AdvancedAutoAim {
    constructor() {
        this.config = {
            enabled: true,
            aimType: "smooth",
            targetSelection: "nearest",
            smoothFactor: 0.15,
            predictionStrength: 0.8,
            maxDistance: 300,
            fov: 45,
            ignoreTeammates: true,
            autoFire: false,
            fireDelay: 100,
            headshotPriority: true,
            bodyPart: "head"
        };

        this.weaponProfiles = {
            assault_rifle: {
                recoilControl: 0.85,
                burstMode: true,
                maxBurstShots: 3,
                aimAssist: 0.9,
                effectiveRange: 400
            },
            sniper: {
                recoilControl: 0.95,
                scopeSwayReduction: 0.8,
                holdBreathAssist: true,
                aimAssist: 0.7,
                effectiveRange: 1000
            },
            smg: {
                recoilControl: 0.75,
                sprayControl: 0.8,
                movingAccuracy: 0.9,
                aimAssist: 0.85,
                effectiveRange: 200
            },
            shotgun: {
                spreadReduction: 0.6,
                pelletFocus: 0.7,
                closeRangeBoost: 1.2,
                aimAssist: 0.8,
                effectiveRange: 50
            }
        };

        this.targetData = {
            currentTarget: null,
            targetHistory: [],
            aimPosition: { x: 0, y: 0 },
            isAiming: false,
            lastShotTime: 0,
            hitCount: 0,
            missCount: 0
        };

        this.performance = {
            totalShots: 0,
            successfulHits: 0,
            headshotCount: 0,
            accuracy: 0.0
        };

        this.safety = {
            humanizerEnabled: true,
            randomOffset: 2.5,
            reactionTime: 150,
            patternRandomization: true,
            detectionEvasion: true
        };
    }

    initialize() {
        this.setupEventListeners();
        this.loadConfiguration();
        return this.config.enabled;
    }

    setupEventListeners() {
        document.addEventListener('mousedown', (e) => this.handleMouseDown(e));
        document.addEventListener('mouseup', (e) => this.handleMouseUp(e));
        document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
        document.addEventListener('keydown', (e) => this.handleKeyPress(e));
        
        window.addEventListener('gameUpdate', () => this.onGameUpdate());
    }

    handleMouseDown(event) {
        if (event.button === 2) {
            this.targetData.isAiming = true;
            this.acquireTarget();
        } else if (event.button === 0 && this.config.autoFire) {
            this.startAutoFire();
        }
    }

    handleMouseUp(event) {
        if (event.button === 2) {
            this.targetData.isAiming = false;
            this.targetData.currentTarget = null;
        }
    }

    handleKeyPress(event) {
        switch(event.code) {
            case 'F1':
                this.toggleAimBot();
                break;
            case 'F2':
                this.switchAimMode();
                break;
            case 'F3':
                this.adjustSensitivity();
                break;
            case 'F4':
                this.toggleAutoFire();
                break;
        }
    }

    onGameUpdate() {
        if (this.targetData.isAiming) {
            this.updateAim();
        }
    }

    acquireTarget() {
        const targets = this.getVisibleTargets();
        if (targets.length === 0) return;

        let bestTarget = null;
        let bestScore = -1;

        targets.forEach(target => {
            if (this.isValidTarget(target)) {
                const score = this.calculateTargetScore(target);
                if (score > bestScore) {
                    bestScore = score;
                    bestTarget = target;
                }
            }
        });

        this.targetData.currentTarget = bestTarget;
        if (bestTarget) {
            this.targetData.aimPosition = this.calculateAimPosition(bestTarget);
        }
    }

    getVisibleTargets() {
        const targets = [];
        
        // Simulated game data
        targets.push({
            id: 1,
            position: { x: 100, y: 50, z: 200 },
            screenPosition: { x: 960, y: 540 },
            distance: 150,
            health: 100,
            isTeammate: false,
            isVisible: true,
            velocity: { x: 2, y: 0, z: 1 },
            bodyParts: {
                head: { x: 960, y: 525 },
                chest: { x: 960, y: 540 },
                stomach: { x: 960, y: 555 }
            }
        });

        return targets.filter(target => 
            target.isVisible && 
            target.distance <= this.config.maxDistance &&
            !(this.config.ignoreTeammates && target.isTeammate)
        );
    }

    calculateTargetScore(target) {
        let score = 0;
        
        // Distance scoring
        const distanceScore = 1 - (target.distance / this.config.maxDistance);
        score += distanceScore * 0.3;
        
        // Health scoring
        const healthScore = (100 - target.health) / 100;
        score += healthScore * 0.2;
        
        // Center screen scoring
        const screenCenter = { x: 960, y: 540 };
        const centerDistance = this.calculateDistance(target.screenPosition, screenCenter);
        const centerScore = 1 - (centerDistance / 1000);
        score += centerScore * 0.3;
        
        // Movement scoring
        const speed = Math.sqrt(target.velocity.x ** 2 + target.velocity.y ** 2);
        const movementScore = 1 - Math.min(1, speed / 10);
        score += movementScore * 0.2;
        
        return Math.min(1.0, score);
    }

    calculateAimPosition(target) {
        let aimPos = { ...target.screenPosition };
        
        // Select body part based on config
        if (this.config.headshotPriority && target.bodyParts) {
            aimPos = { ...target.bodyParts[this.config.bodyPart] };
        }
        
        // Apply prediction for moving targets
        if (this.config.aimType === "predictive") {
            aimPos = this.predictTargetMovement(aimPos, target);
        }
        
        // Apply humanizer for natural movement
        if (this.safety.humanizerEnabled) {
            aimPos = this.applyHumanizer(aimPos);
        }
        
        return aimPos;
    }

    predictTargetMovement(basePos, target) {
        const predictionTime = 0.2;
        const predictedX = basePos.x + (target.velocity.x * predictionTime * 100);
        const predictedY = basePos.y + (target.velocity.y * predictionTime * 100);
        
        return {
            x: basePos.x + (predictedX - basePos.x) * this.config.predictionStrength,
            y: basePos.y + (predictedY - basePos.y) * this.config.predictionStrength
        };
    }

    applyHumanizer(position) {
        const offset = this.safety.randomOffset;
        const jitter = 0.3;
        
        return {
            x: position.x + (Math.random() * offset * 2 - offset) * jitter,
            y: position.y + (Math.random() * offset * 2 - offset) * jitter
        };
    }

    updateAim() {
        if (!this.targetData.currentTarget || !this.targetData.isAiming) return;
        
        const currentMousePos = this.getMousePosition();
        const targetPos = this.targetData.aimPosition;
        
        const moveVector = {
            x: targetPos.x - currentMousePos.x,
            y: targetPos.y - currentMousePos.y
        };
        
        const distance = this.calculateDistance(currentMousePos, targetPos);
        
        if (distance < 5) {
            if (this.config.autoFire && this.canFire()) {
                this.executeShot();
            }
            return;
        }
        
        const smoothMove = {
            x: moveVector.x * this.config.smoothFactor,
            y: moveVector.y * this.config.smoothFactor
        };
        
        this.moveMouseSmooth(smoothMove);
    }

    moveMouseSmooth(moveVector) {
        const steps = Math.max(3, Math.min(10, Math.abs(moveVector.x + moveVector.y) / 10));
        const stepX = moveVector.x / steps;
        const stepY = moveVector.y / steps;
        
        for (let i = 0; i < steps; i++) {
            setTimeout(() => {
                this.simulateMouseMovement(stepX, stepY);
            }, i * 15);
        }
    }

    simulateMouseMovement(dx, dy) {
        if (typeof window !== 'undefined') {
            const mouseEvent = new MouseEvent('mousemove', {
                clientX: window.event.clientX + dx,
                clientY: window.event.clientY + dy,
                bubbles: true
            });
            document.dispatchEvent(mouseEvent);
        }
    }

    canFire() {
        const currentTime = Date.now();
        if (currentTime - this.targetData.lastShotTime < this.config.fireDelay) return false;
        
        const mousePos = this.getMousePosition();
        const targetPos = this.targetData.aimPosition;
        const distance = this.calculateDistance(mousePos, targetPos);
        
        return distance < 8;
    }

    executeShot() {
        this.targetData.lastShotTime = Date.now();
        this.performance.totalShots++;
        
        // Simulate shot execution
        if (this.isHeadshot()) {
            this.performance.headshotCount++;
            this.performance.successfulHits++;
        } else if (this.isHit()) {
            this.performance.successfulHits++;
        }
        
        this.updateAccuracy();
        
        // Fire shot
        if (typeof window !== 'undefined') {
            const mouseDown = new MouseEvent('mousedown', { button: 0, bubbles: true });
            const mouseUp = new MouseEvent('mouseup', { button: 0, bubbles: true });
            
            document.dispatchEvent(mouseDown);
            setTimeout(() => document.dispatchEvent(mouseUp), 50);
        }
    }

    isHeadshot() {
        return this.config.headshotPriority && Math.random() > 0.3;
    }

    isHit() {
        const baseAccuracy = 0.95;
        const distancePenalty = this.targetData.currentTarget.distance / 1000;
        return Math.random() < (baseAccuracy - distancePenalty);
    }

    updateAccuracy() {
        if (this.performance.totalShots > 0) {
            this.performance.accuracy = this.performance.successfulHits / this.performance.totalShots;
        }
    }

    toggleAimBot() {
        this.config.enabled = !this.config.enabled;
        console.log(`Aimbot ${this.config.enabled ? 'ENABLED' : 'DISABLED'}`);
    }

    switchAimMode() {
        const modes = ["smooth", "instant", "predictive"];
        const currentIndex = modes.indexOf(this.config.aimType);
        this.config.aimType = modes[(currentIndex + 1) % modes.length];
        console.log(`Aim mode: ${this.config.aimType}`);
    }

    adjustSensitivity() {
        this.config.smoothFactor = (this.config.smoothFactor + 0.05) % 0.35;
        if (this.config.smoothFactor < 0.05) this.config.smoothFactor = 0.05;
        console.log(`Smooth factor: ${this.config.smoothFactor.toFixed(2)}`);
    }

    toggleAutoFire() {
        this.config.autoFire = !this.config.autoFire;
        console.log(`Auto fire ${this.config.autoFire ? 'ENABLED' : 'DISABLED'}`);
    }

    setWeaponProfile(weaponType) {
        const profile = this.weaponProfiles[weaponType];
        if (profile) {
            Object.assign(this.config, profile);
        }
    }

    getMousePosition() {
        if (typeof window !== 'undefined' && window.event) {
            return {
                x: window.event.clientX,
                y: window.event.clientY
            };
        }
        return { x: 0, y: 0 };
    }

    calculateDistance(pos1, pos2) {
        const dx = pos2.x - pos1.x;
        const dy = pos2.y - pos1.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    isValidTarget(target) {
        return target && 
               target.isVisible && 
               target.distance <= this.config.maxDistance &&
               !(this.config.ignoreTeammates && target.isTeammate);
    }

    loadConfiguration() {
        try {
            const saved = localStorage.getItem('aimbotConfig');
            if (saved) {
                const config = JSON.parse(saved);
                Object.assign(this.config, config);
            }
        } catch (e) {
            console.warn('Config load failed');
        }
    }

    saveConfiguration() {
        try {
            localStorage.setItem('aimbotConfig', JSON.stringify(this.config));
        } catch (e) {
            console.warn('Config save failed');
        }
    }

    getStatus() {
        return {
            enabled: this.config.enabled,
            isAiming: this.targetData.isAiming,
            currentTarget: this.targetData.currentTarget,
            performance: this.performance,
            config: this.config
        };
    }

    getPerformanceStats() {
        return {
            totalShots: this.performance.totalShots,
            hits: this.performance.successfulHits,
            headshots: this.performance.headshotCount,
            accuracy: (this.performance.accuracy * 100).toFixed(2) + '%',
            kdRatio: this.calculateKDRatio()
        };
    }

    calculateKDRatio() {
        const deaths = Math.max(1, this.performance.totalShots - this.performance.successfulHits);
        return (this.performance.successfulHits / deaths).toFixed(2);
    }

    resetStats() {
        this.performance = {
            totalShots: 0,
            successfulHits: 0,
            headshotCount: 0,
            accuracy: 0.0
        };
    }
}

const aimBot = new AdvancedAutoAim();

aimBot.initialize();

export default aimBot