/*
 * Copyright (c) 2026 盐灯水母
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package com.remains_cave.network;

import com.remains_cave.client.ClientChallengeData;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.registration.PayloadRegistrar;

@EventBusSubscriber(modid = "remains_cave", value = Dist.CLIENT)  // 移除过时的 bus 参数
public class ClientPayloadHandler {

    @SubscribeEvent
    public static void register(final RegisterPayloadHandlersEvent event) {
        final PayloadRegistrar registrar = event.registrar("remains_cave");
        registrar.playToClient(
                ChallengeDataPacket.TYPE,
                ChallengeDataPacket.CODEC,
                ClientPayloadHandler::handleChallengeData
        );
    }

    private static void handleChallengeData(ChallengeDataPacket packet, IPayloadContext context) {
        context.enqueueWork(() -> {
            if (packet.phase() == 3) {
                // 挑战结束，清除 UI
                ClientChallengeData.clear();
                return;
            }

            ClientChallengeData.ChallengeData current = ClientChallengeData.current;
            if (current == null) {
                ClientChallengeData.update(new ClientChallengeData.ChallengeData(
                        packet.roomId(),
                        packet.challengeType(),
                        packet.wave(),
                        packet.monsterProgress(),
                        packet.timeProgress(),
                        packet.waveProgress(),
                        packet.phase()
                ));
            } else {
                current.updateTarget(
                        packet.monsterProgress(),
                        packet.timeProgress(),
                        packet.waveProgress(),
                        packet.wave(),
                        packet.phase()
                );
            }
        });
    }
}