var Start = false
var PlayButton = [690,760,390,430]
window.onload = function(){
	var canvas = document.getElementById('canvas');
	var ctx = canvas.getContext('2d');
	var clavier = new Clavier();

	var fond = new Image();
	var perso = new Image();
    var puit = new Image();
    var farfadet = new Image();
    var noir = new Image();
    var icon = new Image();

    rgb = 0
    fond.src = "Images/paysage.png";
	perso.src = 'Images/spritesheet.png';
	puit.src = 'Images/puit.png';
	farfadet.src = 'Images/farfadet.png';
    noir.src = 'Images/unnoirbiensucre.png';
    icon.src = 'Images/gameicon.webp';

    var LesMessagesDuFarfadet = [
        ["wsh"],["ya quoi"],["eh bouge de la"],["j'ai jure c'est une dinguerie..."],["tu veut un bonbon mon petit ?"]
    ]

    var GroundList = [
        [0,325,250,13],[300,325,163,13],[510,325,825,13],[1390,325,170,13],
        [0,455,150,13],[605,455,163,13],[1091,447,450,13],
        [850,536,150,13],
        [0,600,780,13],[1075,600,500,13],
    ];

    var ObstaclesList = [
    ];

    var StairList = [
        [293,325,7,6,"Left","Down",20],[460,325,7,6,"Right","Down",20],[1385,325,7,6,"Left","Down",17],
        [150,460,12,10,"Right","Down",12],[600,460,13,11,"Left","Down",12],[765,460,13,11,"Right","Down",6],[1080,455,13,11,"Left","Down",6],
        [850,540,7,6,"Left","Down",11],[1000,540,7,6,"Right","Down",11],
    ];

    var DoorList = [
        [90,285,27,40,"House1"],
        [1333,532,40,70,"Cave"],
    ]


    
    for (let stair of StairList) {
        let posx = stair[0];
        let posy = stair[1];
        for (let pas = 0; pas < stair[6]; pas++) {
            GroundList.push([posx,posy,stair[2],stair[3]]);
            if (stair[4] == "Right") {posx += stair[2];}
            if (stair[4] == "Left") {posx -= stair[2];}
            if (stair[5] == "Up") {posy -= stair[3];}
            if (stair[5] == "Down") {posy += stair[3];}
        }    
    }

    var PosX = 0;
    var PosY = 285;
    var FeetHitBox = [10,37,15,10] // place it just below your feet
    var HeadHitBox = [10,0,15,10] // place it on your head :)
    var BodyRightHitBox = [25,10,10,20]
    var BodyLeftHitBox = [0,10,10,20]
    var BodyHitBox = [13,12,10,20]
    var compt = 0;
    var pas = 0;
    var AnimationPosition = 704;
    var WidthX = 65;
    var WidthY = 65;
    var Hauteur = 0;
    var PositionInitiale = 0;
    var OnDoor = "";
    var LeDernierMessageDuFarfadet = ""
    fond.onload = function(){setInterval(boucle,20); }

    function GetRandomInTable(Table) {
        var randomIndex = Math.floor(Math.random() * Table.length);
        return Table[randomIndex][0];
    }

    function CtxFill(Element,X,Y,Color,Shadow) {
        ctx.globalAlpha = Shadow; ctx.fillStyle = Color;
        if (typeof(Element[0])=="string") {ctx.font = Element[1]+"px "+Element[2]; ctx.fillText(Element[0],X,Y);}
        if (typeof(Element[0])=="number") {ctx.fillRect(X,Y,Element[0],Element[1]);}
    }

    function ShowHitBox() {
        for (let obs of GroundList) {CtxFill([obs[2],obs[3]],obs[0],obs[1],"black",0.5)}
        for (let obs of ObstaclesList) {CtxFill([obs[2],obs[3]],obs[0],obs[1],"red",0.5)}
        for (let obs of DoorList) {CtxFill([obs[2],obs[3]],obs[0],obs[1],"yellow",0.5)}
        CtxFill([FeetHitBox[2],FeetHitBox[3]],PosX+FeetHitBox[0],PosY+FeetHitBox[1],"green",0.5)
        CtxFill([FeetHitBox[2],FeetHitBox[3]],PosX+FeetHitBox[0],PosY,"green",0.5)
        CtxFill([FeetHitBox[2],FeetHitBox[3]],PosX+FeetHitBox[0],PosY+FeetHitBox[1],"green",0.5)
        CtxFill([BodyRightHitBox[2],BodyRightHitBox[3]],PosX+BodyRightHitBox[0],PosY+BodyRightHitBox[1],"green",0.5)
        CtxFill([BodyLeftHitBox[2],BodyLeftHitBox[3]],PosX+BodyLeftHitBox[0],PosY+BodyLeftHitBox[1],"green",0.5)
        CtxFill([BodyHitBox[2],BodyHitBox[3]],PosX+BodyHitBox[0],PosY+BodyHitBox[1],"green",0.5)
    }

    
    function CheckCollision(Class,Part) {
        var HitBox = []
        var CollisionElement = []
        if (Part=="Ground" || Part=="Stair") {HitBox=FeetHitBox} else {HitBox=HeadHitBox}
        if (Class == "Obstacle") {
            if (Part=="Right") {CollisionElement=ObstaclesList;HitBox=BodyRightHitBox}
            if (Part=="Left") {CollisionElement=ObstaclesList;HitBox=BodyLeftHitBox}
        } else {CollisionElement=GroundList}
        for (let obs of CollisionElement) {
            var sol = new Obstacle(obs[0],obs[1],obs[2],obs[3]);
            if (sol.collision(PosX+HitBox[0],PosY+HitBox[1],HitBox[2],HitBox[3])) {
                if (Part=="Stair") {
                    return obs[1]-37;
                }
                return true;
            } 
        }
        return false;
    }

    function CheckDoor() {
        OnDoor="";
        for (let obs of DoorList) {
            var sol = new Obstacle(obs[0],obs[1],obs[2],obs[3]);
            if (sol.collision(PosX+BodyHitBox[0],PosY+BodyHitBox[1],BodyHitBox[2],BodyHitBox[3])) {
                ctx.font = "20px serif";
                CtxFill(["'E' to enter",20,"Serif"],PosX,PosY-15,"black",1)
                OnDoor=obs[4];
            } 
        }
    }


    function CheckLeFarfadet() {
            var sol = new Obstacle(350,250,75,75);
            if (sol.collision(PosX+BodyHitBox[0],PosY+BodyHitBox[1],BodyHitBox[2],BodyHitBox[3])) {
                if (LeDernierMessageDuFarfadet=="") {
                    LeDernierMessageDuFarfadet = GetRandomInTable(LesMessagesDuFarfadet)
                    CtxFill([LeDernierMessageDuFarfadet,20,"Serif"],350,240,"black",1);
                } else {CtxFill([LeDernierMessageDuFarfadet,20,"Serif"],350,240,"black",1);CtxFill(["'T' to talk",20,"Serif"],350,220,"black",1);}
            } else {LeDernierMessageDuFarfadet = ""}
    }
    var time = 0

    noir.onload = function () {
        if (Start==false) {
            let opacity = 0;
            const fadeInDuration = 2000;
            const steps = 100;
            const stepDuration = fadeInDuration / steps;
            let currentStep = 0;
            let loadingStep = 0;
            let time = 0; 
            let loadingInterval; 
        
            function fadeIcon() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(noir, 0, -100, 1560, 1000);
                ctx.globalAlpha = opacity;
                ctx.drawImage(icon, 650, 220, 150, 150);
                ctx.globalAlpha = 1;
                if (currentStep < steps) {
                    currentStep++;
                    opacity += 1 / steps; 
                    setTimeout(fadeIcon, stepDuration); 
                } else {
                    startLoadingAnimation();
                }
            }
        
            function startLoadingAnimation() {
                loadingInterval = setInterval(function () {
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(noir, 0, -100, 1560, 1000);
                    CtxFill(["The Legend of Zelda : souvenirs d'enfance", 40, "Arial"], 370, 200, "white", 1);
                    ctx.drawImage(icon, 650, 220, 150, 150);
        
                    const loadingTexts = ["loading", "loading.", "loading..", "loading..."];
                    CtxFill([loadingTexts[loadingStep % loadingTexts.length], 40, "Serif"], 665, 420, "yellow", 1);
                    loadingStep++;
                    time++;
        
                    if (time >= 9) {
                        clearInterval(loadingInterval);
                        displayPlay();
                    }
                }, 500); 
            }
        
            function displayPlay() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(noir, 0, -100, 1560, 1000);
                CtxFill(["The Legend of Zelda : souvenirs d'enfance", 40, "Arial"], 370, 200, "white", 1);
                ctx.drawImage(icon, 650, 220, 150, 150);
                CtxFill(["play", 40, "Serif"], 690, 420, "white", 1);
            }
        
            fadeIcon();
        }
    };
    
    
    


    function boucle() {
        if (Start) {
        var moving = false;
        compt++;
        if(clavier.droite){
            if (CheckCollision("Obstacle","Right") == false) {
                PosX=PosX+5;
            }
			if(PosX>1520){PosX=0;}
            if (compt%3==0)pas++;
            AnimationPosition = 704
            moving = true
		}

        if(clavier.e){
            if (OnDoor!="") {
                window.location.href = OnDoor +".htm";
            }
        }

        
        if(clavier.gauche){
            if (CheckCollision("Obstacle","Left") == false) {
                PosX=PosX-5;
            }
			if(PosX<0){PosX=1520;}
            if (compt%3==0)pas++;
            AnimationPosition = 576
            moving = true
		}

        if (clavier.espace && CheckCollision("NotObstacle","Ground")==true && Hauteur<=0){
			PositionInitiale = PosY;
			Hauteur = 40;
		} 

        if (CheckCollision("NotObstacle","Ground")!=true) {PosY=PosY*1.03}
        
        if (CheckCollision("NotObstacle","Stair")!=false) {PosY=CheckCollision("NotObstacle","Stair")}
        
        if (Hauteur>=0){
			if (Hauteur>15){
				PosY=PositionInitiale+(20-Hauteur)*(20-Hauteur)/4*1.5-150;
                if (CheckCollision("here is a text you have to write but useless :)","this one too")==true) {Hauteur=-1}
			}	
        Hauteur--;
		}
        if (pas>=9) pas=0;
        ctx.save();
        ctx.drawImage(fond,0,0,1560,680);
        ctx.drawImage(farfadet,350,250,75,75);
        if (moving) {ctx.drawImage(perso,(pas*64)+15,AnimationPosition,50,64,PosX-5,PosY-25,WidthX,WidthY);   
        } else {ctx.drawImage(perso,15,128,50,64,PosX-5,PosY-25,WidthX,WidthY)}
        ctx.drawImage(puit,1000,272,50,50);
        if(clavier.t){
            if (LeDernierMessageDuFarfadet!="") {
                console.log(LeDernierMessageDuFarfadet)

                CtxFill(["si ta recup le code va dans la cave (sans sous-entendus)",20,"Serif"],350,200,"black",1);
            }
        }

        CheckDoor()
        CheckLeFarfadet()
        ctx.restore();
        }
    }
}

window.onclick = function(evt){
    var canvas = document.getElementById('canvas');
    if (PlayButton[0]<=evt.clientX-canvas.offsetLeft&&
        evt.clientX-canvas.offsetLeft<=PlayButton[1]&&
        evt.clientY-canvas.offsetTop>=PlayButton[2]&&
        evt.clientY-canvas.offsetTop<=PlayButton[3])
        Start = true;
}