let boarImage;
const cols = 20;
const rows = 10;
const cellSize = 40;
let maze = [];
let stack = [];
let mazeWalls = [];
let rainSound;
let rainVolume = 0;
let fadingInRain = false;

let x, y;
const inc = 5;
let angle = 0;
let boarSize = 30;

let inRainyParadise = false;
let raindrops = [];
let boarVX = 0;
let boarVY = -0.6;  // Slower vertical speed in the paradise
let boarSpeed = 0.5; // Reduced range of motion speed
let wanderingSlowDownTimer = 0; // Timer for slowing down
let isStopping = false; // Flag to check if the boar should stop
let stopCounter = 0; // Counter to track how long to stop
let stopDuration = 100; // Duration to stop

function preload() {
    boarImage = loadImage('boar.png');
    rainSound = loadSound('rain.mp3'); // Load your rain sound
  }

function setup() {
    createCanvas(cols * cellSize, rows * cellSize + 100);
    x = (cols - 1) * cellSize + 5;
    y = rows * cellSize - 55;

    for (let j = 0; j < rows; j++) {
        for (let i = 0; i < cols; i++) {
            maze.push(new Cell(i, j));
        }
    }

    let current = maze[0];
    current.visited = true;
    stack.push(current);

    while (stack.length > 0) {
        let next = current.checkNeighbors();
        if (next) {
            next.visited = true;
            stack.push(current);
            removeWalls(current, next);
            current = next;
        } else {
            current = stack.pop();
        }
    }
    rainSound.setVolume(0); // Start silent
}
function draw() {
    if (inRainyParadise) {
        drawRainyParadise();

        // Fade in rain sound
        if (!rainSound.isPlaying()) {
            rainSound.loop();
            fadingInRain = true;
        }
        if (fadingInRain && rainVolume < 0.5) {
            rainVolume += 0.005;
            rainSound.setVolume(rainVolume);
        }

        return;
    }

    background(0);
    mazeWalls = [];

    for (let cell of maze) {
        cell.show();
    }

    noStroke();
    fill(0);
    rect((cols - 1) * cellSize + 1, rows * cellSize - 20, cellSize - 2, 20); // Entrance
    rect(1, 0, cellSize - 2, 20); // Exit

    if (keyIsDown(UP_ARROW) || keyIsDown(DOWN_ARROW)) {
        angle = sin(frameCount * 0.1) * 0.2;
    } else {
        angle = 0;
    }

    push();
    translate(x + boarSize / 2, y + boarSize / 2);
    rotate(angle);
    imageMode(CENTER);
    image(boarImage, 0, 0, boarSize, boarSize);
    pop();

    let nextX = x;
    let nextY = y;

    if (keyIsDown(UP_ARROW)) nextY -= inc;
    if (keyIsDown(DOWN_ARROW)) nextY += inc;
    if (keyIsDown(LEFT_ARROW)) nextX -= inc;
    if (keyIsDown(RIGHT_ARROW)) nextX += inc;

    if (!collidesWithWalls(nextX, nextY)) {
        x = nextX;
        y = nextY;
    }

    // When the boar reaches the exit, move to the rainy paradise scene
    if (x < 10 && y < 10) {
        inRainyParadise = true;
        x = width / 2 - boarSize / 2;
        y = height + 50;
        for (let i = 0; i < 300; i++) {
            raindrops.push(new Raindrop());
        }
        if (!rainSound.isPlaying()) {
            rainSound.loop();
            fadingInRain = true;
        }
    }
}


function index(i, j) {
    if (i < 0 || j < 0 || i >= cols || j >= rows) return -1;
    return i + j * cols;
}

function Cell(i, j) {
    this.i = i;
    this.j = j;
    this.walls = [true, true, true, true];
    this.visited = false;

    this.checkNeighbors = function () {
        let neighbors = [];

        let top = maze[index(i, j - 1)];
        let right = maze[index(i + 1, j)];
        let bottom = maze[index(i, j + 1)];
        let left = maze[index(i - 1, j)];

        if (top && !top.visited) neighbors.push(top);
        if (right && !right.visited) neighbors.push(right);
        if (bottom && !bottom.visited) neighbors.push(bottom);
        if (left && !left.visited) neighbors.push(left);

        if (neighbors.length > 0) {
            return random(neighbors);
        } else {
            return undefined;
        }
    };

    this.show = function () {
        let x = this.i * cellSize;
        let y = this.j * cellSize;
        stroke(150);
        strokeWeight(2);

        if (this.walls[0]) {
            line(x, y, x + cellSize, y);
            mazeWalls.push({ x: x, y: y - 1, w: cellSize, h: 2 });
        }
        if (this.walls[1]) {
            line(x + cellSize, y, x + cellSize, y + cellSize);
            mazeWalls.push({ x: x + cellSize - 1, y: y, w: 2, h: cellSize });
        }
        if (this.walls[2]) {
            line(x + cellSize, y + cellSize, x, y + cellSize);
            mazeWalls.push({ x: x, y: y + cellSize - 1, w: cellSize, h: 2 });
        }
        if (this.walls[3]) {
            line(x, y + cellSize, x, y);
            mazeWalls.push({ x: x - 1, y: y, w: 2, h: cellSize });
        }
    };
}

function removeWalls(a, b) {
    let x = a.i - b.i;
    if (x === 1) {
        a.walls[3] = false;
        b.walls[1] = false;
    } else if (x === -1) {
        a.walls[1] = false;
        b.walls[3] = false;
    }

    let y = a.j - b.j;
    if (y === 1) {
        a.walls[0] = false;
        b.walls[2] = false;
    } else if (y === -1) {
        a.walls[2] = false;
        b.walls[0] = false;
    }
}

function collidesWithWalls(newX, newY) {
    let boarBox = { x: newX, y: newY, w: boarSize, h: boarSize };

    for (let wall of mazeWalls) {
        if (rectIntersect(boarBox, wall)) {
            return true;
        }
    }

    return false;
}

function rectIntersect(r1, r2) {
    return !(
        r2.x > r1.x + r1.w ||
        r2.x + r2.w < r1.x ||
        r2.y > r1.y + r1.h ||
        r2.y + r2.h < r1.y
    );
}

function drawRainyParadise() {
    background(90, 120, 130);  // Soft blue sky

    // Grassy background: more consistent colors and no flashing
    noStroke();
    for (let yPos = 0; yPos < height; yPos += 30) {
        fill(100, 130, 100);  // Muted green for the grass
        rect(0, yPos, width, 30);
    }

    // Rain
    for (let drop of raindrops) {
        drop.update();
        drop.show();
    }

    // Slow down the boar intermittently
    wanderingSlowDownTimer--;
    if (wanderingSlowDownTimer <= 0 && !isStopping) {
        boarSpeed = random(0.1, 0.3);  // Slow down to a very low speed range
        wanderingSlowDownTimer = random(60, 120);  // Randomize the interval to stop
        isStopping = true;
        stopCounter = random(60, 120);  // Duration to stop
    }

    // Boar movement in the paradise
    if (isStopping) {
        stopCounter--;
        if (stopCounter <= 0) {
            isStopping = false; // Stop pausing after the counter reaches 0
            boarVX = random(-boarSpeed, boarSpeed);  // Controlled horizontal range
            boarVY = random(-0.3, -0.6);  // Slow upward motion
        }
    }

    x += boarVX;
    y += boarVY;

    // Ensure the boar doesn't wander off the screen
    x = constrain(x, 0, width - boarSize);
    y = constrain(y, -boarSize, height - boarSize);

    push();
    translate(x + boarSize / 2, y + boarSize / 2);
    rotate(sin(frameCount * 0.1) * 0.1);
    imageMode(CENTER);
    image(boarImage, 0, 0, boarSize, boarSize);
    pop();
}

function Raindrop() {
    this.x = random(width);
    this.y = random(-500, 0);
    this.len = random(10, 20);
    this.speed = random(4, 10);

    this.update = function () {
        this.y += this.speed;
        if (this.y > height) {
            this.y = random(-200, 0);
            this.x = random(width);
        }
    };

    this.show = function () {
        stroke(200, 200, 255, 180);
        line(this.x, this.y, this.x, this.y + this.len);
    };
}
