import { _decorator, Component, director } from 'cc';
import { ConfigMgr } from '../data/ConfigMgr';
import { CCJsonLoader } from './CCJsonLoader';
import { BossController } from '../logic/BossController';
import { ensureCanvasSize, createLabel, createButton } from './MainMenuEntry';
import { Color } from 'cc';
import { DESIGN_WIDTH, DESIGN_HEIGHT } from '../common/Constants';

const { ccclass, property } = _decorator;

/**
 * Boss scene entry (task 7.3 / 8.2 hookup, req 9.x + 14.x).
 *
 * Attach to the root node of `Boss_ShuangHuanFang.scene`. Default bossId
 * matches the chapter-1 final boss.
 *
 * When `autoBuildUI` is enabled, two temporary debug buttons are placed on
 * screen so the flow can be validated before the combat view layer lands:
 *   - Left side:  "Hit Butterfly" → `onButterflyHit`
 *   - Right side: "Hit Body"      → `onBodyHit`
 * These will be removed once the real combat HUD is built.
 */
@ccclass('BossEntry')
export class BossEntry extends Component {
    @property({ tooltip: '对应 configs/bosses.json 中的 id' })
    public bossId: string = 'shuang_huan_fang';

    @property({ tooltip: '是否自动创建调试按钮 (战斗 HUD 就绪前使用)' })
    public autoBuildUI: boolean = true;

    private ctrl: BossController | undefined;

    protected async onLoad(): Promise<void> {
        if (this.autoBuildUI) this.buildDefaultUI();
        const cfg = new ConfigMgr(new CCJsonLoader());
        await cfg.load();
        this.ctrl = new BossController(cfg.boss(this.bossId));
    }

    /** Dev-hook: attack landed on the butterfly (req 9.2). */
    public onButterflyHit(): void {
        const events = this.ctrl?.onButterflyHit() ?? [];
        this.processEvents(events);
    }

    /** Dev-hook: attack landed on boss body (req 9.3). */
    public onBodyHit(): void {
        const events = this.ctrl?.onBodyHit() ?? [];
        this.processEvents(events);
    }

    private processEvents(events: ReturnType<NonNullable<BossController['onBodyHit']>>): void {
        for (const ev of events) {
            if (ev.kind === 'boss_killed') {
                director.loadScene('Settlement');
                return;
            }
        }
    }

    private buildDefaultUI(): void {
        ensureCanvasSize(this.node);
        createLabel(this.node, 'BOSS · 双幻坊', 0, DESIGN_HEIGHT / 2 - 60, 32, Color.WHITE);
        createLabel(
            this.node,
            '调试：先击中蝴蝶 → 再击中本体',
            0,
            DESIGN_HEIGHT / 2 - 110,
            18,
            new Color(200, 200, 200, 255),
        );
        // Left / right debug buttons, 180px off center.
        createButton(this.node, 'Hit Butterfly', -180, -120, 220, 70, () => this.onButterflyHit());
        createButton(this.node, 'Hit Body', 180, -120, 220, 70, () => this.onBodyHit());
    }
}
