import { _decorator, Component } from 'cc';
import { LevelMapData } from './LevelMapData';
import { layoutLevelTiles } from './TileLayout';
import { LevelConfig } from './LevelTypes';

const { ccclass, executionOrder } = _decorator;

/**
 * 挂在 LevelN 根节点：运行时首帧按 levels-database 重新对齐砖块。
 * 解决「编辑器 JSON 正确、运行预览叠在一起 / 只显示一块」。
 */
@ccclass('LevelTileLayout')
@executionOrder(-50)
export class LevelTileLayout extends Component {
    /** 运行时权威配置（来自 levels-database.json，优先于预制体 LevelMapData） */
    runtimeConfig: LevelConfig | null = null;

    start() {
        this.applyLayout();
        this.scheduleOnce(() => this.applyLayout(), 0);
    }

    setRuntimeConfig(config: LevelConfig) {
        this.runtimeConfig = config;
    }

    applyLayout() {
        const config = this.runtimeConfig ?? this.configFromMapData();
        if (!config) return;
        layoutLevelTiles(this.node, config);
    }

    private configFromMapData(): LevelConfig | null {
        const md = this.getComponent(LevelMapData);
        if (!md) return null;
        let ground: LevelConfig['ground'];
        let border: LevelConfig['border'];
        try {
            ground = JSON.parse(md.groundJson || '{}');
            border = JSON.parse(md.borderJson || '{}');
        } catch {
            return null;
        }
        return {
            levelID: md.levelID,
            boundary: { x: 0, y: 0 },
            spawns: [],
            theme: md.theme || 'silu',
            ground,
            border,
        };
    }
}
