import { _decorator, Component, director, Label, Node, Color } from 'cc';
import { ChapterSettlement, ISettlementStats } from '../logic/ChapterSettlement';
import { ensureCanvasSize, createLabel, createButton } from './MainMenuEntry';
import { DESIGN_HEIGHT } from '../common/Constants';

const { ccclass, property } = _decorator;

/**
 * Settlement scene entry (task 8.2 hookup, req 14.x).
 *
 * Attach to the root of `Settlement.scene`. All UI is auto-built by default
 * (title, score, closing line, back-to-menu button). If `autoBuildUI` is
 * disabled and you wire up `scoreLabelNode` / `closingLabelNode` manually,
 * those wins.
 */
@ccclass('SettlementEntry')
export class SettlementEntry extends Component {
    @property({ type: Node, tooltip: '得分 Label 节点 (可留空自动创建)' })
    public scoreLabelNode: Node | null = null;

    @property({ type: Node, tooltip: '结局旁白 Label 节点 (可留空自动创建)' })
    public closingLabelNode: Node | null = null;

    @property({ tooltip: '是否自动创建结算界面 (Label + Back 按钮)' })
    public autoBuildUI: boolean = true;

    protected onLoad(): void {
        if (this.autoBuildUI) this.buildDefaultUI();

        const defaultStats: ISettlementStats = {
            totalScore: 0,
            stageScore: 0,
            comboCount: 0,
            flawless: true,
            remainingTimeSec: 0,
        };
        const settlement = new ChapterSettlement(defaultStats);
        const result = settlement.build();
        this.setLabel(this.scoreLabelNode, `Stage Score: ${result.stats.stageScore}`);
        this.setLabel(this.closingLabelNode, result.closingLine);
    }

    /** Bind to a "Back to Menu" button. */
    public onReturnToMenu(): void {
        director.loadScene('MainMenu');
    }

    private setLabel(node: Node | null, text: string): void {
        if (!node) return;
        const label = node.getComponent(Label);
        if (label) label.string = text;
    }

    private buildDefaultUI(): void {
        ensureCanvasSize(this.node);
        // Title.
        createLabel(this.node, '章 节 结 算', 0, DESIGN_HEIGHT / 2 - 70, 40, Color.WHITE);
        // Score label (created only if inspector did not supply one).
        if (!this.scoreLabelNode) {
            this.scoreLabelNode = createLabel(this.node, '', 0, 40, 30, new Color(255, 220, 120, 255));
        }
        // Closing line label.
        if (!this.closingLabelNode) {
            this.closingLabelNode = createLabel(this.node, '', 0, -30, 24, new Color(200, 200, 200, 255));
        }
        // Bottom "Back to Menu" button.
        createButton(this.node, 'Back to Menu', 0, -DESIGN_HEIGHT / 2 + 80, 240, 60, () => this.onReturnToMenu());
    }
}
