package com.tiedup.remake.network.conversation;

import com.tiedup.remake.core.TiedUpMod;
import java.util.function.Supplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent;

/**
 * Server-to-Client packet: server forces conversation end
 * (e.g., NPC died, player moved too far).
 *
 * Split from the former bidirectional PacketEndConversation (H16 fix).
 */
public class PacketEndConversationS2C {

    private final int entityId;

    public PacketEndConversationS2C(int entityId) {
        this.entityId = entityId;
    }

    public void encode(FriendlyByteBuf buf) {
        buf.writeInt(entityId);
    }

    public static PacketEndConversationS2C decode(FriendlyByteBuf buf) {
        return new PacketEndConversationS2C(buf.readInt());
    }

    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(this::handleClient);
        ctx.get().setPacketHandled(true);
    }

    @OnlyIn(Dist.CLIENT)
    private void handleClient() {
        ClientHandler.handle(this);
    }

    public int getEntityId() {
        return entityId;
    }

    @OnlyIn(Dist.CLIENT)
    private static class ClientHandler {

        private static void handle(PacketEndConversationS2C pkt) {
            TiedUpMod.LOGGER.info(
                "[PacketEndConversationS2C] Server ended conversation with entity {}",
                pkt.entityId
            );

            // Close any open conversation screen
            if (
                net.minecraft.client.Minecraft.getInstance().screen instanceof
                    com.tiedup.remake.client.gui.screens.ConversationScreen
            ) {
                net.minecraft.client.Minecraft.getInstance().setScreen(null);
            }
        }
    }
}
