'use strict';

const grid = require('./grid-math');

function findNodeByUuid(root, uuid) {
    if (!root || !uuid) return null;
    if (root.uuid === uuid) return root;
    for (const ch of root.children) {
        const hit = findNodeByUuid(ch, uuid);
        if (hit) return hit;
    }
    return null;
}

function resolveLayer(node) {
    let cur = node;
    while (cur) {
        if (cur.name === 'Ground') return 'ground';
        if (cur.name === 'Border') return 'border';
        cur = cur.parent;
    }
    const m = node.name && node.name.match(/^([gb])_(-?\d+)_(-?\d+)$/);
    if (m) return m[1] === 'g' ? 'ground' : 'border';
    return null;
}

exports.methods = {
    /**
     * 将指定 uuid 节点吸附到等距格子中心（场景内拖动后调用）
     */
    snapNodeByUuid(uuid) {
        const { director, Vec3 } = require('cc');
        const scene = director.getScene();
        if (!scene) return { ok: false, reason: 'no scene' };
        const node = findNodeByUuid(scene, uuid);
        if (!node) return { ok: false, reason: 'node not found' };
        const layer = resolveLayer(node);
        if (!layer) return { ok: false, reason: 'not under Ground/Border' };

        const p = node.position;
        const c = grid.worldCenterToCellXY(p.x, p.y);
        const w = grid.cellCenterWorldXY(c.x, c.y);
        node.setPosition(new Vec3(w.x, w.y, p.z));

        const prefix = layer === 'ground' ? 'g' : 'b';
        const expected = `${prefix}_${c.x}_${c.y}`;
        if (/^[gb]_-?\d+_-?\d+$/.test(node.name) || node.name.startsWith(prefix)) {
            node.name = expected;
        }
        return { ok: true, cell: c, key: grid.cellKey(c.x, c.y), layer };
    },

    /** 批量吸附（参数为 uuid 数组） */
    snapNodes(uuids) {
        const list = Array.isArray(uuids) ? uuids : [uuids];
        const results = [];
        for (const id of list) {
            results.push(exports.methods.snapNodeByUuid(id));
        }
        return results;
    },

    /** 在 Level 根节点挂载 GridSnapHelper（编辑器场景内持续吸附） */
    attachHelperOnSelection(uuid) {
        const { director } = require('cc');
        const scene = director.getScene();
        if (!scene) return { ok: false, reason: 'no scene' };
        let node = findNodeByUuid(scene, uuid);
        if (!node) return { ok: false, reason: 'node not found' };
        let root = node;
        while (root.parent && !/^Level\d+$/.test(root.name)) {
            root = root.parent;
        }
        if (!/^Level\d+$/.test(root.name)) {
            return { ok: false, reason: 'not a Level prefab node' };
        }
        let comp = root.getComponent('GridSnapHelper');
        if (!comp) {
            comp = root.addComponent('GridSnapHelper');
        }
        return { ok: true, level: root.name, hasHelper: !!comp };
    },
};

exports.load = function () {};
exports.unload = function () {};
