import { _decorator, Node, Prefab, instantiate, SpriteFrame, tween, Vec3, Sprite } from "cc";
import { Fruit } from "./Fruit";
import { FruitNode } from "./FruitNode";
const { ccclass, property } = _decorator;

@ccclass("Board")
export class Board extends Node {
    @property(Prefab) fruitPrefab: Prefab = null!;
    @property([SpriteFrame]) fruitSprites: SpriteFrame[] = [];

    board: (Fruit | null)[][] = [];
    rows = 4;
    cols = 4;

    node: Node = null!;

    onLoad() {
        this.initBoard();
    }

    initBoard() {
        this.board = [];
        for (let r = 0; r < this.rows; r++) {
            this.board[r] = [];
            for (let c = 0; c < this.cols; c++) {
                this.board[r][c] = null;
            }
        }
        this.spawnFruit();
        this.spawnFruit();
    }

    spawnFruit() {
        let emptyCells: { r: number; c: number }[] = [];
        for (let r = 0; r < this.rows; r++) {
            for (let c = 0; c < this.cols; c++) {
                if (!this.board[r][c]) emptyCells.push({ r, c });
            }
        }
        if (emptyCells.length === 0) return;

        let index = Math.floor(Math.random() * emptyCells.length);
        let cell = emptyCells[index];

        let node = instantiate(this.fruitPrefab);
        node.setParent(this.node);
        node.setPosition(new Vec3(cell.c * 100, cell.r * -100, 0));

        let fruit = new Fruit(node, cell.r, cell.c, 1);
        node.getComponent(FruitNode)!.init(fruit, this);
        node.getComponent(Sprite)!.spriteFrame = this.fruitSprites[0];

        this.board[cell.r][cell.c] = fruit;
    }

    merge(f1: Fruit, f2: Fruit) {
        if (f1.level !== f2.level) return;
        f1.level += 1;

        if (f1.level - 1 < this.fruitSprites.length)
            f1.node.getComponent(Sprite)!.spriteFrame = this.fruitSprites[f1.level - 1];

        this.playMergeAnimation(f1.node, f2.node);

        this.board[f2.row][f2.col] = null;
        f2.node.destroy();

        this.spawnFruit();
    }

    playMergeAnimation(n1: Node, n2: Node) {
        // tween(n1)
        //     .to(0.2, { scale: 1.2 })
        //     .to(0.1, { scale: 1 })
        //     .start();
    }
}
