import { _decorator, Component } from 'cc';

const { ccclass, property } = _decorator;

/**
 * 挂在关卡预制体根节点（与 Unity LevelN.prefab 同级）。
 * 地图碰撞/可走数据；视觉由预制体子节点 Ground、Border 上的 Sprite 呈现。
 */
@ccclass('LevelMapData')
export class LevelMapData extends Component {
    @property
    levelID = 0;

    @property({ multiline: true, displayName: 'Ground JSON' })
    groundJson = '{}';

    @property({ multiline: true, displayName: 'Border JSON' })
    borderJson = '{}';

    @property({ displayName: '地图主题 (silu/sanxing/…)' })
    theme = 'silu';

    parseGround(): Map<string, string> {
        return LevelMapData.parseRecord(this.groundJson);
    }

    parseBorder(): Set<string> {
        return LevelMapData.parseBorder(this.borderJson);
    }

    static parseRecord(json: string): Map<string, string> {
        const m = new Map<string, string>();
        try {
            const o = JSON.parse(json || '{}') as Record<string, string>;
            for (const [k, v] of Object.entries(o)) {
                if (typeof v === 'string' && v) m.set(k, v);
            }
        } catch (e) {
            console.warn('[LevelMapData] groundJson parse error', e);
        }
        return m;
    }

    static parseBorder(json: string): Set<string> {
        const s = new Set<string>();
        try {
            const o = JSON.parse(json || '{}') as Record<string, boolean>;
            for (const k of Object.keys(o)) {
                if (o[k]) s.add(k);
            }
        } catch (e) {
            console.warn('[LevelMapData] borderJson parse error', e);
        }
        return s;
    }
}
