MenuState = {};

let isSea = false;
let isDesert = false;
let isAir = false;
let bought = localStorage.getItem('bought') === 'true';


let isHiddenMode = false;
let isSpeedMode = false;
let isSlowMode = false;

let dead = false;
let isBumPlayed = false;

const owned_desert_cars = [
    //DEFAULT CARS
    { nimi: 'rekka',  scale: 0.1 },
    { nimi: 'tuktuk', scale: 0.6 },
    ///
];

const owned_sea_cars = [
    //DEFAULT CARS
    { nimi: 'sukellusvene',  scale: 0.6 },
    { nimi: 'hai', scale: 0.8 },
    { nimi: 'mauri', scale: 0.8 },
    { nimi: 'marko',   scale: 0.8 },
    ///
];

const owned_air_cars = [
    //DEFAULT CARS
    { nimi: 'plane',  scale: 1.2 },
    { nimi: 'helikopteri',  scale: 1.0 },
    ///
];

const savedCars = JSON.parse(localStorage.getItem('case_cars') || '[]');
savedCars.forEach(c => owned_desert_cars.push(c));

const wheel = [
    { name: "Basic", angleStart: 0, angleEnd: 216 },
    { name: "Rare", angleStart: 216, angleEnd: 338 },
    { name: "Epic", angleStart: 338, angleEnd: 356 },
    { name: "Legendary", angleStart: 356, angleEnd: 359 },
    { name: "Contraband", angleStart: 359, angleEnd: 359.9 },
    { name: "Unobtainable", angleStart: 359.9, angleEnd: 360 }
];

const rewards = {
    Basic: [
        ['Traktori'],
        ],
    Rare: [
        ['Paloauto'],
        ],
    Epic: [
        ['Poliisiauto'],
    ],
    Legendary: [
        ['Mopo'],
        ],
    Contraband: [
        ['Ogrektaa'],
        ],
    Unobtainable: [
        ['Error occured'],
        ]
};

function getRandomAngleForRarity(rarityName) {
    const segment = wheel.find(w => w.name === rarityName);
    const EPSILON = 0.0001;
    return segment.angleStart +
        Math.random() * (segment.angleEnd - segment.angleStart - EPSILON);
}

function rollRarity() {
    const rarities = [
        { name: "Basic", rarity: 6000 },
        { name: "Rare", rarity: 3400 },
        { name: "Epic", rarity: 500  },
        { name: "Legendary", rarity: 100  },
        { name: "Contraband", rarity: 50  },
        { name: "Unobtainable", rarity: 1   },
    ];
    const total = rarities.reduce((sum, r) => sum + r.rarity, 0);
    let roll = Math.floor(Math.random() * total);
    for (const r of rarities) {
        if (roll < r.rarity) return r.name;
        roll -= r.rarity;
    }
}

function getGameMode() {
    if (isHiddenMode)
    {
        return 'HIDDEN';
    }
    if (isSpeedMode) 
    {
        return 'SPEED';
    }
    if (isSlowMode)
    {
       return 'SLOW'; 
    }
    else {
        return 'NORMAL';
    }
}
function getHighScore() {
    const mode = getGameMode();
    return parseInt(localStorage.getItem('highscore_' + mode) || '0');
}

function saveUrBestScore(score) {
    const mode = getGameMode();
    const key = 'highscore_' + mode;
    if (score > parseInt(localStorage.getItem(key) || '0')) {
        localStorage.setItem(key, score);
    }
}


MenuState.preload = function () {
    const uniqueCars = owned_desert_cars.filter(
    (car, index, self) =>
        index === self.findIndex(c => c.nimi === car.nimi)
    );
    
    owned_desert_cars.length = 0;
    owned_desert_cars.push(...uniqueCars);
    console.log("Tämä on ajoneuvo listasi:", owned_desert_cars);
    this.game.load.image('logo', 'images/Logo.jpg'); 
    this.game.load.image('boooom', 'images/Boom.png'); 
    this.game.load.audio('bum','audio/bum.mp3');
    this.game.load.audio('help','audio/help.mp3');
};

MenuState.create = function () {
    this.game.stage.backgroundColor = '#ffffff';
    
    
    //CREDITS
    
     //listaa updatet tähän
     
     let updateslist = 'LATEST UPDATES:  \n- ADDED NEW MAPS (SEA + AIR)\n- NEW GAMEMODE: SLOWW\n- ADDED INFORMATION BOX \n TO DEATH SCREEN \n- YOU CAN SEE YOUR STATS NOW\n- SHOP ADDED\n- CASES';
    
    this.credits = this.game.add.text(1200,300,'CREDITS:  \nLUKE\nVANYA\nMR.LOKKI',{ fontSize: '24px', fill: '#000000' });
    this.credits.visible = false;
    
    //VERSIO
    this.version = this.game.add.text(this.game.world.centerX,850, 'V.1.2',{ fontSize: '24px', fill: '#000000' });
    this.version.anchor.setTo(0.5, 0.9);
    
    //UPDATES LOG
    
    this.updateslog = this.game.add.text(300,300, updateslist,{ fontSize: '24px', fill: '#000000' });
    this.updateslog.visible = false;
    
    //PELIMUODOT
    
    this.gamemodestext = this.game.add.text(1200,300,'GAMEMODES:',{ fontSize: '24px', fill: '#000000' });
    this.gamemodestext.visible = false;
    
    this.normal = this.game.add.text(1200,340,'- NORMAL',{ fontSize: '24px', fill: '#00ff1a' });
    this.normal.inputEnabled = true;
    this.normal.visible = false;
    
    this.hidden = this.game.add.text(1200,380,'- HIDDEN',{ fontSize: '24px', fill: '#fff700' });
    this.hidden.inputEnabled = true;
    this.hidden.visible = false;
    
    this.speed = this.game.add.text(1200,420,'- SPEEEED',{ fontSize: '24px', fill: '#ff0000' });
    this.speed.inputEnabled = true;
    this.speed.visible = false;
    
    this.slow = this.game.add.text(1200,460,'- SLOWWW',{ fontSize: '24px', fill: '#fc9803' });
    this.slow.inputEnabled = true;
    this.slow.visible = false;
    

    this.hidden.events.onInputDown.add(() => {
        this.gamemodestext.text = 'MAPS (HIDDEN)';
        this.normal.visible = false;
        this.hidden.visible = false;
        this.speed.visible = false;
        this.slow.visible = false;
        
        this.desert.visible = true;
        this.sea.visible = true;
        this.air.visible = true;
        
        isHiddenMode = true;
    });
    
    this.normal.events.onInputDown.add(() => {
        this.gamemodestext.text = 'MAPS (NORMAL)';
        this.normal.visible = false;
        this.hidden.visible = false;
        this.speed.visible = false;
        this.slow.visible = false;
        
        this.desert.visible = true;
        this.sea.visible = true;
        this.air.visible = true;
        
    });
    
    this.speed.events.onInputDown.add(() => {
        this.gamemodestext.text = 'MAPS (SPEEEED)';
        this.normal.visible = false;
        this.hidden.visible = false;
        this.speed.visible = false;
        this.slow.visible = false;
        
        this.desert.visible = true;
        this.sea.visible = true;
        this.air.visible = true;
        
        isSpeedMode = true;
        
    });
    
    this.slow.events.onInputDown.add(() => {
        this.gamemodestext.text = 'MAPS (SLOWWW)';
        this.normal.visible = false;
        this.hidden.visible = false;
        this.speed.visible = false;
        this.slow.visible = false;
        
        this.desert.visible = true;
        this.sea.visible = true;
        this.air.visible = true;
        
        isSlowMode = true;
        
    });
    
    //KENTÄT
    
    this.desert = this.game.add.text(1200,340,'- DESERT',{ fontSize: '24px', fill: '#e1e38a' });
    this.desert.visible = false;
    this.desert.inputEnabled = true;
    
    this.sea = this.game.add.text(1200,380,'- SEA',{ fontSize: '24px', fill: '#295eff' });
    this.sea.visible = false;
    this.sea.inputEnabled = true;
    
    this.air = this.game.add.text(1200,420,'- AIR',{ fontSize: '24px', fill: '#a1ecff' });
    this.air.visible = false;
    this.air.inputEnabled = true;
    ///////
    
    // LOGO
    
    let logo = this.game.add.image(this.game.world.centerX, 200, 'logo');
    logo.anchor.setTo(0.5);
    
    // GAMEMODeS NAPPI123
    
    let btn = this.game.add.text(
        this.game.world.centerX, 340,'GAMEMODES',{ fontSize: '28px', fill: '#000000', backgroundColor: '#ffffff', padding: { x: 20, y: 10 } }
    );
    // CREDITS NAPPI123
    
    let btn2 = this.game.add.text(
        this.game.world.centerX, 410,'CREDITS',{ fontSize: '28px', fill: '#000000', backgroundColor: '#ffffff', padding: { x: 20, y: 10 } }
    );
    // HELP NAPPI123
    
    let btn3 = this.game.add.text(
        this.game.world.centerX, 480,'HELP!!!!!',{ fontSize: '28px', fill: '#000000', backgroundColor: '#ffffff', padding: { x: 20, y: 10 } }
    );
    
    // UPDATES
    let btn4 = this.game.add.text(
        this.game.world.centerX, 550,'UPDATES',{ fontSize: '28px', fill: '#000000', backgroundColor: '#ffffff', padding: { x: 20, y: 10 } }
    );
    // STATS
    let btn5 = this.game.add.text(
        this.game.world.centerX, 620,'STATS',{ fontSize: '28px', fill: '#000000', backgroundColor: '#ffffff', padding: { x: 20, y: 10 } }
    );
    // SHOP
    let btn6 = this.game.add.text(
        this.game.world.centerX, 690,'SHOP',{ fontSize: '28px', fill: '#000000', backgroundColor: '#ffffff', padding: { x: 20, y: 10 } }
    );
    btn.anchor.setTo(0.5);
    btn2.anchor.setTo(0.5);
    btn3.anchor.setTo(0.5);
    btn4.anchor.setTo(0.5);
    btn5.anchor.setTo(0.5);
    btn6.anchor.setTo(0.5);
    
    btn.inputEnabled = true;
    btn2.inputEnabled = true;
    btn3.inputEnabled = true;
    btn4.inputEnabled = true;
    btn5.inputEnabled = true;
    btn6.inputEnabled = true;
    

    this.desert.events.onInputDown.add(() => {
        this.game.state.start('play');
        isDesert = true;
    });
    this.sea.events.onInputDown.add(() => {
        this.game.state.start('play');
        isSea = true;
    });
    
    this.air.events.onInputDown.add(() => {
        this.game.state.start('play');
        isAir = true;
    });
    btn.events.onInputDown.add(() => {
        if (this.credits.visible === true)
        {
            
            isHiddenMode = false;
            isSpeedMode = false;
            isSlowMode = false;
            
            //SULKEE CREDITS TEKSTIN 
            this.credits.visible = false;
            
            this.gamemodestext.visible = true;
            this.normal.visible = true;
            this.hidden.visible = true;
            this.speed.visible = true;
            this.slow.visible = true;
          
        }
        else if (this.gamemodestext.visible === true)
        {
            
            isHiddenMode = false;
            isSpeedMode = false;
            isSlowMode = false;
            
            this.gamemodestext.visible = false;
            this.gamemodestext.text = 'GAMEMODES:';
            this.desert.visible = false;
            this.sea.visible = false;
            this.air.visible = false;
            this.normal.visible = false;
            this.hidden.visible = false;
            this.speed.visible = false;
            this.slow.visible = false;

        }
        else {
            
            isHiddenMode = false;
            isSpeedMode = false;
            isSlowMode = false;
            
            this.gamemodestext.visible = true;
            this.normal.visible = true;
            this.hidden.visible = true;
            this.speed.visible = true;
            this.slow.visible = true;
        }
    });

    btn2.events.onInputDown.add(() => {
        if (this.gamemodestext.visible === true)
        {
            
          isHiddenMode = false;  
          isSpeedMode = false;
          isSlowMode = false;
          this.gamemodestext.visible = false;
          this.gamemodestext.text = 'GAMEMODES:';
          this.desert.visible = false;
          this.sea.visible = false;
          this.air.visible = false;
          this.speed.visible = false;
          this.hidden.visible = false;
          this.normal.visible = false;
          this.slow.visible = false;
          
          
          // AVAA CREDITS TEKSTIN
          this.credits.visible = true;  
        }
        else if (this.credits.visible === true)
        {
            this.credits.visible = false;
        }
        else{
            this.credits.visible = true;
        }
    });
    help = this.game.add.audio('help');
    btn3.events.onInputDown.add(() => {
        if (!help.isPlaying) {
            help.play();
        }
    });
    btn4.events.onInputDown.add(() => {
        if (this.updateslog.visible)
        {
           this.updateslog.visible = false; 
        }
        else 
        {
            this.updateslog.visible = true;    
        }
        
    });
    btn5.events.onInputDown.add(() => {
        this.game.state.start('stats');
    });
    btn6.events.onInputDown.add(() => {
        this.game.state.start('shop');
    });
};

CaseState = {};

CaseState.preload = function () {
    this.game.load.image('tumma', 'images/hyrry22.png');
    this.game.load.image('rinkula', 'images/rinkula.png');
    this.game.load.image('spin', 'images/Spinnausnappi22.png');
    this.game.load.audio('casesound','audio/casesound.mp3');
    
    this.game.load.image('Poliisiauto', 'images/Poliisi22.png');
    this.game.load.image('Paloauto', 'images/Paloauto.png');
    this.game.load.image('Ogrektaa', 'images/ogrektaa.png');
    this.game.load.image('Traktori', 'images/rahtori22.png');
    this.game.load.image('Mopo', 'images/MulOMopo.png');
    this.game.load.image('Error occured', 'images/Hitbox.png');
    
};

CaseState.create = function () {
    koira = this.game.add.text(this.game.world.centerX, 200, '', { fontSize: '48px', fill: '#000000' });
    koira.anchor.setTo(0.5);
    koira.visible = false;
    let graphics = this.game.add.graphics(0, 0);
    
    const väritykset = [
        { color: 0x13a300 },
        { color: 0x34adfe },
        { color: 0x750071 },
        { color: 0xfafe16 },
        { color: 0x454545 },
    ];
    
    for (let i = 0; i < väritykset.length; i++) {
        graphics.beginFill(väritykset[i].color, 1);
        graphics.drawRect(1530, 3 + i * 28, 25, 25); 
        graphics.endFill();
    }
    
    let graphics2 = this.game.add.graphics(0, 0);
    graphics2.beginFill(0xffffff, 1);
    graphics2.drawRect(1530, 144, 25, 25);
    graphics2.endFill();
    
    graphics2.beginFill(0xffffff, 1);
    graphics2.drawRect(this.game.world.centerX, 495, 229, 10);
    graphics2.endFill();
    
    this.rainbow = graphics2;
    this.t = 0;
        
    let currentRotation = 0;
    let spinned = false;
    let spinning = false;
    let img = null;
    this.game.add.text(1300, 0, 'BASIC 60%\nRARE 34%\nEPIC 5%\nLEGENDARY 1%\nCONTRABAND 0.5%\nUNOBTAINABLE 0.01%',{ fontSize: '20px', fill: '#000000', align:'right'});

    rinkula = this.game.add.image(this.game.world.centerX, 500, 'rinkula');
    tumma = this.game.add.image(this.game.world.centerX, 500, 'tumma');
    spin = this.game.add.image(this.game.world.centerX, 500, 'spin');
    
    rinkula.anchor.setTo(0.5);
    tumma.anchor.setTo(0.5);
    tumma.scale.setTo(0.8); 
    spin.anchor.setTo(0.5);
    spin.scale.setTo(0.6); 
    
    spin.inputEnabled = true;
    spin.events.onInputDown.add(() => {
        if (spinning) return;
        if (img) {
            img.visible = false; 
        }
        if (koira)
        {
            koira.visible = false;
        }
        spin.scale.setTo(0.5); 
        this.game.time.events.add(200, () => {
                spin.scale.setTo(0.6); 
            });
            
        const coins = parseInt(localStorage.getItem('coins') || '0');
        
        if (coins >= 500 && !spinned) {
            spinned = true;
            localStorage.setItem('coins', coins - 500);
            spinning = true;
            if (spinned)
            {
                this.casesound = this.game.add.audio("casesound");
                this.casesound.play();
            }
            const rarity = rollRarity();
            
            const pool = rewards[rarity];
            const car = pool[Math.floor(Math.random() * pool.length)];
            const alreadyOwned = owned_desert_cars.some(c => c.nimi === car[0]);
            if (!alreadyOwned) {
                owned_desert_cars.push({ nimi: car[0], scale: 0.8 });
                const savedCars = JSON.parse(localStorage.getItem('case_cars') || '[]');
                savedCars.push({ nimi: car[0], scale: 0.8 });
                localStorage.setItem('case_cars', JSON.stringify(savedCars));
            }
            
            img = this.game.add.image(this.game.world.centerX, 500, car[0]); 
            img.anchor.setTo(0.5);
            img.visible = false;

            const targetAngle = getRandomAngleForRarity(rarity);
        
            const extraSpins =  5 * 360;
        
            const totalRotation = extraSpins + targetAngle;
        
            const currentNormalized = ((tumma.angle % 360) + 360) % 360;
    
            const offset = 90;
            const targetWithOffset = (targetAngle + offset) % 360;
            
            let delta = targetWithOffset - currentNormalized;
            if (delta < 0) delta += 360;
            
            currentRotation = tumma.angle + extraSpins + delta;
            
        
            this.game.add.tween(tumma).to({ angle: currentRotation },2000,Phaser.Easing.Exponential.Out,true);
            this.game.time.events.add(4000, () => {
                koira.text = rarity; 
                koira.visible = true;
                img.visible = true;
                spinned = false; 
                spinning = false;
            });
            
        } 
        else {
            this.error = this.game.add.audio("error");
            this.error.play();
    }
});
    const back = this.game.add.text(1400, 800,'BACK TO SHOP',{ fontSize: '28px', fill: '#000000', backgroundColor: '#ffffff', padding: { x: 20, y: 10 } });
    back.anchor.setTo(0.5);
    back.inputEnabled = true;
    back.events.onInputDown.add(() => {
        spinned = false;
        if (!spinning)
        {
            this.game.state.start('shop');
        }
        else {
            return;
        }
    });
};

CaseState.update = function () {
    this.t += 0.3;
    const r = Math.floor(Math.sin(this.t) * 127 + 128);
    const g = Math.floor(Math.sin(this.t + 2) * 127 + 128);
    const b = Math.floor(Math.sin(this.t + 4) * 127 + 128);
    this.rainbow.tint = (r << 16) | (g << 8) | b;
};

ShopState = {};

ShopState.preload = function () {
    this.game.load.image('tantti', 'images/Jaakko22.png');
    this.game.load.image('auto', 'images/Arto22.png');
    this.game.load.audio('error','audio/errorei.mp3');
    this.game.load.image('konnacase', 'images/keissi22.png');
};
ShopState.create = function () {
    this.game.add.text(this.game.world.centerX, 100, 'SHOP:', { fontSize: '24px', fill: '#000000' });
    const coins = parseInt(localStorage.getItem('coins') || '0');

    const coinsText = this.game.add.text(0, 30, 'COINS: ' + coins, { fontSize: '24px', fill: '#f5a623' });
    
    const cases = [
        { name:"Car Case", key: 'konnacase', x: 475, price: 500, map: 'DESERT', scale: 1.0 },
    ];
    const items = [
        { name:"Tank", key: 'tantti', x: 500, price: 500,  map: 'DESERT', boughtKey: 'bought',  scale:1.0 },
        { name:"Car", key: 'auto',   x: 800, price: 1100, map: 'DESERT', boughtKey: 'bought2', scale: 1.0 },
    ];
    
    
    cases.forEach(caseItem => {
        const img = this.game.add.image(caseItem.x + 25, 200, caseItem.key);
        img.scale.setTo(caseItem.scale);
        örkki = this.game.add.text(caseItem.x + 125, 300,
            `BUY\nPRICE: ${caseItem.price} COINS\nMAP: ${caseItem.map}`,
            { fontSize: '24px', fill: '#e1e38a', align: 'center'}
        );
        örkki.anchor.setTo(0.5, 0);
        neiti = this.game.add.text(caseItem.x + 125, 150, `${caseItem.name}`, { fontSize: '24px', fill: '#000000', align: 'center'});
        neiti.anchor.setTo(0.5, 0);
    
        örkki.inputEnabled = true;
        örkki.events.onInputDown.add(() => {
            const currentCoins = parseInt(localStorage.getItem('coins') || '0');
                if (currentCoins >= caseItem.price) {
                    this.game.state.start('caset');
                } else {
                    this.error = this.game.add.audio("error");
                    this.error.play();
                }
        });
    });
    
    const resultText = this.game.add.text(this.game.world.centerX, 700, '', { fontSize: '32px', fill: '#ffffff', align: 'center' });
    resultText.anchor.setTo(0.5, 0);

    items.forEach(item => {
        const img = this.game.add.image(item.x, 500, item.key);
        img.scale.setTo(item.scale); 
        mörkö = this.game.add.text(item.x + 0, 600,
            `BUY\nPRICE: ${item.price} COINS\nMAP: ${item.map}`,
            { fontSize: '24px', fill: '#e1e38a', align: 'center'}
        );
        naapuri = this.game.add.text(item.x + 99, 430,
            `${item.name}` ,
            { fontSize: '24px', fill: '#000000', align: 'center'}
        );
        naapuri.anchor.setTo(0.5, 0);

        const isBought = localStorage.getItem(item.boughtKey) === 'true';
        if (isBought)
        {
            mörkö.text = "BOUGHT"
        }
        if (!isBought) {
            mörkö.inputEnabled = true;

            mörkö.events.onInputDown.add(() => {
                if (coins >= item.price) {
                    localStorage.setItem(item.boughtKey, 'true');
                    localStorage.setItem('coins', coins - item.price);
                } else{
                    this.error = this.game.add.audio("error");
                    this.error.play();
                }
            });
        }
    });

    backbtn = this.game.add.text(1400, 800, 'BACK TO MENU', { fontSize: '24px', fill: '#000000' });
    backbtn.inputEnabled = true;
    backbtn.events.onInputDown.add(() => {
        this.game.state.start('menu');
    });
};

StatState = {};

StatState.create = function () {
    const normal = parseInt(localStorage.getItem('highscore_NORMAL') || '0');
    const speed  = parseInt(localStorage.getItem('highscore_SPEED')  || '0');
    const hidden = parseInt(localStorage.getItem('highscore_HIDDEN') || '0');
    const slow   = parseInt(localStorage.getItem('highscore_SLOW')   || '0');

    let bestEver = Math.max(normal, speed, hidden, slow);

    this.stats = this.game.add.text(20, 20,'YOUR STATS:\n\n' +'BEST SCORE EVER: ' + bestEver + '\n' +'NORMAL: ' + normal + '\n' +'SPEEEED: ' + speed + '\n' +'HIDDEN: ' + hidden + '\n' +'SLOWWW: ' + slow,{ fontSize: '24px', fill: '#000000' }
    );

    backbtn = this.game.add.text(1400, 800, 'BACK TO MENU', { fontSize: '24px', fill: '#000000' });
    backbtn.inputEnabled = true;
    

    backbtn.events.onInputDown.add(() => {
        this.game.state.start('menu');
    });
};


PlayState = {};

PlayState.preload = function () {
    if (isSea)
    {
        this.game.load.image('backgroundsea', 'images/sea.jpg');
        this.game.load.image('background2', 'images/sea_1.jpg');
        this.game.load.image('merimiina', 'images/Petri22.png');
        this.game.load.image('hai', 'images/Shrk22.png');
        this.game.load.image('sukellusvene', 'images/Rautakasa22.png');
        this.game.load.image('mauri', 'images/angler22.png');
        this.game.load.image('marko', 'images/Homo22.png');
        this.game.load.audio('merimusiikki','audio/merimusic.mp3');
        this.game.load.audio('merimusiikki2','audio/pizza.mp3');
        this.game.load.audio('merimusiikki3','audio/misiikki.mp3');

    }
    else if (isDesert) {
        this.game.load.image('background', 'images/kenttä22.png');
        this.game.load.image('rekka', 'images/rekha11.png');
        this.game.load.image('tuktuk', 'images/tuktuk.png');
        this.game.load.image('tantti', 'images/Jaakko22.png');
        this.game.load.image('auto', 'images/Arto22.png');
        this.game.load.image('Mopo', 'images/MulOMopo.png');
        this.game.load.image('miina', 'images/Olli22.png');
        this.game.load.audio('music','audio/bosniansong.mp3');
        this.game.load.audio('music2','audio/romania.mp3');
        this.game.load.audio('music3','audio/music3.mp3');
        this.game.load.audio('music4','audio/music4.mp3');
        this.game.load.audio('music5','audio/EVA.mp3');
        this.game.load.image('Poliisiauto', 'images/Poliisi22.png');
        this.game.load.image('Paloauto', 'images/Paloauto.png');
        this.game.load.image('Ogrektaa', 'images/ogrektaa.png');
        this.game.load.image('Error occured', 'images/Hitbox.png');
        this.game.load.image('Traktori', 'images/rahtori22.png');
    }
    else if (isAir)
    {
        this.game.load.image('background', 'images/Air22.png');
        this.game.load.image('background2', 'images/Air22_1.png');
        this.game.load.image('drone', 'images/Drooni22.png');
        
        this.game.load.image('plane', 'images/realfinir.png');
        this.game.load.image('helikopteri', 'images/Hellakopteri22.png');
        this.game.load.audio('music5','audio/EVA.mp3');
    }
    
};


PlayState.create = function () {
    if (isSlowMode)
    {
        this.rekkaspeed = 2;
    }
    else {
        this.rekkaspeed = 3;
    }
    this.movespeed = 3;
    this.bumsound = this.game.add.audio('bum');
    isBumPlayed = false;
    
    if (isSea)
    {
        this.bg1 = this.game.add.image(0, 0, 'backgroundsea');
        this.bg1.width = this.game.width;
        this.bg1.height = this.game.height;


        this.bg2 = this.game.add.image(this.game.width, 0, 'background2');
        this.bg2.width = this.game.width;
        this.bg2.height = this.game.height; 
        const soittolista = ['merimusiikki', 'merimusiikki2', 'merimusiikki3']
        const kurkku = soittolista[Math.floor(Math.random() * soittolista.length)];
        
        this.music = this.game.add.audio(kurkku);
        this.music.loop = true;
        this.music.play();

    }
    else if (isDesert)
    {
        this.bg1 = this.game.add.image(0, 0, 'background');
        this.bg1.width = this.game.width;
        this.bg1.height = this.game.height;


        this.bg2 = this.game.add.image(this.game.width, 0, 'background');
        this.bg2.width = this.game.width;
        this.bg2.height = this.game.height;
        
        const soittolista = ['music', 'music2', 'music3', 'music4', 'music5']
        const kurkku = soittolista[Math.floor(Math.random() * soittolista.length)];
        
        this.music = this.game.add.audio(kurkku);
        this.music.loop = true;
        this.music.play();
    }
    else if (isAir)
    {
        this.bg1 = this.game.add.image(0, 0, 'background');
        this.bg1.width = this.game.width;
        this.bg1.height = this.game.height;

        
        this.bg2 = this.game.add.image(this.game.width, 0, 'background2');
        this.bg2.width = this.game.width;
        this.bg2.height = this.game.height;
        
        const soittolista = ['music5']
        const kurkku = soittolista[Math.floor(Math.random() * soittolista.length)];
        
        this.music = this.game.add.audio(kurkku);
        this.music.loop = true;
        this.music.play();
    }


    this.mines = [];
    let minecraft_amount = 5
    if (isSlowMode)
    {
        minecraft_amount = 250
    }
    for (let i = 0; i < minecraft_amount; i++) {
        let x = this.game.rnd.integerInRange(this.game.width, this.game.width * 2);
        let y = this.game.rnd.integerInRange(0, this.game.height - 0);
        if (isSea)
        {
            let miina = this.game.add.image(x, y, 'merimiina');
            miina.anchor.setTo(0.5);
            miina.scale.setTo(1.0);
            this.mines.push(miina);
        }
        else if (isDesert) {
            let miina = this.game.add.image(x, y, 'miina');
            miina.anchor.setTo(0.5);
            miina.scale.setTo(0.7);
            this.mines.push(miina);
        }
        else if (isAir) {
            let miina = this.game.add.image(x, y, 'drone');
            miina.anchor.setTo(0.5);
            miina.scale.setTo(0.8);
            this.mines.push(miina);
        }
    }
    
    if (isDesert)
    {
        if (localStorage.getItem('bought') === 'true' && !owned_desert_cars.some(car => car.nimi === "tantti"))
        {
            owned_desert_cars.push({ nimi: 'tantti', scale: 0.6 });
        }
        if (localStorage.getItem('bought2') === 'true' && !owned_desert_cars.some(car => car.nimi === "auto"))
        {
            owned_desert_cars.push({ nimi: 'auto', scale: 0.8 });
        }

    
        const kurkku = owned_desert_cars[Math.floor(Math.random() * owned_desert_cars.length)];
        this.rekka = this.game.add.image(100, this.game.world.centerY, kurkku.nimi);
        this.rekka.anchor.setTo(0.4);
        this.rekka.scale.setTo(kurkku.scale);
    }

    else if (isSea)
        {

            const kurkku = owned_sea_cars[Math.floor(Math.random() * owned_sea_cars.length)];
        
            this.rekka = this.game.add.image(100, this.game.world.centerY, kurkku.nimi);
            this.rekka.anchor.setTo(0.4);
            this.rekka.scale.setTo(kurkku.scale);
    }
    else if (isAir)
        {

            const kurkku = owned_air_cars[Math.floor(Math.random() * owned_air_cars.length)];
        
            this.rekka = this.game.add.image(100, this.game.world.centerY, kurkku.nimi);
            this.rekka.anchor.setTo(0.4);
            this.rekka.scale.setTo(kurkku.scale);
    }

//NÄPPÄIMET
    this.cursors = this.game.input.keyboard.createCursorKeys();
    this.wasd = {
        up: this.game.input.keyboard.addKey(Phaser.Keyboard.W),
        down: this.game.input.keyboard.addKey(Phaser.Keyboard.S),
        left: this.game.input.keyboard.addKey(Phaser.Keyboard.A),
        right: this.game.input.keyboard.addKey(Phaser.Keyboard.D)
    };
    this.score = 0;
    if (isSea)
    {
        this.pointstar = this.game.add.image(1540, 5, 'merimiina');
        this.pointstar.scale.setTo(0.5);   
    }
    else if (isDesert) {
        this.pointstar = this.game.add.image(1540, 5, 'miina');
        this.pointstar.scale.setTo(0.6);    
    }
    else if (isAir) {
        this.pointstar = this.game.add.image(1540, 5, 'drone');
        this.pointstar.scale.setTo(0.7);    
    }
    currentgamemode = getGameMode();
    this.playingtext = this.game.add.text(0, 0, 'YOU ARE PLAYING: ' + currentgamemode + 'MODE', { fontSize: '24px', fill: '#ffffff' });
    if (isAir)
    {
        this.scoreText = this.game.add.text(this.game.width - 20, 20,'AVOIDED DRONES: 0',{ fontSize: '24px', fill: '#ffffff' });
    }
    else {
        this.scoreText = this.game.add.text(this.game.width - 20, 20,'AVOIDED MINES: 0',{ fontSize: '24px', fill: '#ffffff' });
    }
    this.scoreText.anchor.setTo(1, 0);
    this.speedText = this.game.add.text(this.game.width - 20, 40,'SPEED: ' + this.rekkaspeed * 3.6 + ' KM/H',{ fontSize: '24px', fill: '#ffffff' });
    this.speedText.anchor.setTo(1, 0);
};

PlayState.update = function () {
    if (dead === false)
    {
        this.bg1.x -= this.rekkaspeed;
        this.bg2.x -= this.rekkaspeed;
    
        if (this.bg1.x <= -this.game.width) {
            this.bg1.x = this.bg2.x + this.game.width;
        }
        if (this.bg2.x <= -this.game.width) {
            this.bg2.x = this.bg1.x + this.game.width;
        }
    }
    let moremines = 5 + Math.floor(this.score / 20) * 3; 

    if (this.mines.length < moremines) {
        let x = this.game.rnd.integerInRange(this.game.width, this.game.width + 500);
        let y = this.game.rnd.integerInRange(50, this.game.height - 50);
        if (isSea)
        {
            let miina = this.game.add.image(x, y, 'merimiina');
            miina.anchor.setTo(0.5);
            miina.scale.setTo(1.0);
            this.mines.push(miina);
        }
        else if (isDesert) {
            let miina = this.game.add.image(x, y, 'miina');
            miina.anchor.setTo(0.5);
            miina.scale.setTo(0.7);
            this.mines.push(miina);
        }
        else if (isAir) {
            let miina = this.game.add.image(x, y, 'drone');
            miina.anchor.setTo(0.5);
            miina.scale.setTo(0.8);
            this.mines.push(miina);
        }
    }

    for (let i = 0; i < this.mines.length; i++) {
        if (dead === false)
        {
            this.mines[i].x -= this.rekkaspeed;
        }

        if (isHiddenMode)
        {
          this.mines[i].visible = false; 
        }
        
        if (this.mines[i].x < -50 && this.rekka.visible == true) {
            this.mines[i].x = this.game.rnd.integerInRange(this.game.width, this.game.width + 500);
            this.mines[i].y = this.game.rnd.integerInRange(50, this.game.height - 50);
            this.score += 1;
            if (isAir)
            {
                this.scoreText.text = 'AVOIDED DRONES: ' + this.score;
            }
            else {
                this.scoreText.text = 'AVOIDED MINES: ' + this.score;
            }
            this.speedText.text = 'SPEED: ' + Math.trunc(this.rekkaspeed *3.6*1000)/1000 + ' KM/H';
        }
        
        

        let dx = this.rekka.x - this.mines[i].x;
        let dy = this.rekka.y - this.mines[i].y;
        let distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < 30) {
            this.bum();
        }
    }
    
    // REKKA YLÖS JA ALAS KIIHDYTYS
    if (this.cursors.up.isDown || this.wasd.up.isDown || this.cursors.left.isDown || this.wasd.left.isDown) {
        this.movespeed += 0.5; 
        
    if (this.movespeed > 20) this.movespeed = 20; 
        this.rekka.y -= this.movespeed;
    } 
    else if (this.cursors.down.isDown || this.wasd.down.isDown || this.cursors.right.isDown || this.wasd.right.isDown) {
        this.movespeed += 0.5;
    if (this.movespeed > 20) this.movespeed = 20;
        this.rekka.y += this.movespeed;
    } 
    else
    {
        this.movespeed = 3; 
    }

    let yMin = this.rekka.height * this.rekka.anchor.y;
    let yMax = this.game.height - this.rekka.height * (1 - this.rekka.anchor.y);

    if (this.rekka.y < yMin) {
        this.rekka.y = yMin;
    }
    if (this.rekka.y > yMax) {
        this.rekka.y = yMax;
    }
    if (isSpeedMode)
    {
        this.rekkaspeed = 3 + (this.score * 0.1);
    }
};

PlayState.bum = function () {
    if (dead === true) return;
    dead = true;
    saveUrBestScore(this.score);
    
    const oldCoins = parseInt(localStorage.getItem('coins') || '0');
    localStorage.setItem('coins', oldCoins + this.score);
    
    this.music.pause();
    this.rekka.visible = false;
    if (isBumPlayed === false)
    {
      this.bumsound.play();
      isBumPlayed = true;
    }
    

    let pic = this.game.add.image(this.game.world.centerX, 200, 'boooom');
    pic.anchor.setTo(0.5);
    pic.scale.setTo(2);
    pic.scale.setTo(2, 1.5);
    
    let now = new Date();
    let timeString = now.getHours() + ':' + now.getMinutes();
    let day = now.getDate();
    let month = now.getMonth() + 1;
    let year = now.getFullYear();

    const modeName = getGameMode().toUpperCase();

    this.pisteinfo = this.game.add.text(this.game.world.centerX, 600, 'TOTAL SCORE:' + this.score + '\nHIGH SCORE (' + modeName + '): ' + getHighScore() + '\nTIME: ' + timeString + '\nDATE:' + day + '.' + month + '.' + year, { fontSize: '50px', fill: '#000000', backgroundColor: '#ffffff' });
    this.pisteinfo.anchor.setTo(0.5);

    this.pisteinfo.visible = true;
    


    this.game.time.events.add(6000, () => {
        this.music.destroy();
        
        this.mines.forEach(m => m.destroy());
        this.mines = [];
        this.pisteinfo.visible = false;
        if(isHiddenMode || isSpeedMode || isSlowMode || isSea || isDesert || isAir)
        {
            minecraft_amount = 5
            isHiddenMode = false;
            isSpeedMode = false;
            isSlowMode = false;
            
            isSea = false;
            isDesert = false;
            isAir = false;
        }
        this.game.state.start('menu');
        
        dead = false;
    });
};

window.onload = function () {
    let game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, 'game');
    game.state.add('menu', MenuState);
    game.state.add('play', PlayState);
    game.state.add('stats', StatState);
    game.state.add('shop', ShopState);
    game.state.add('caset', CaseState);
    game.state.start('menu');
};