package com.tiedup.remake.network.sync;

import com.tiedup.remake.network.base.AbstractPlayerSyncPacket;
import com.tiedup.remake.state.PlayerBindState;
import java.util.UUID;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

/**
 * Packet to synchronize struggle animation state.
 * Lightweight packet (17 bytes): UUID (16 bytes) + boolean (1 byte).
 *
 * Direction: Server → Client (S2C)
 *
 * Sent when:
 * - Player starts struggle animation (R key pressed)
 * - Struggle animation auto-stops after 80 ticks
 */
public class PacketSyncStruggleState extends AbstractPlayerSyncPacket {

    private final boolean isStruggling;

    /**
     * Create a packet to sync struggle animation state.
     *
     * @param playerUUID The player's UUID
     * @param isStruggling True if player is struggling, false otherwise
     */
    private PacketSyncStruggleState(UUID playerUUID, boolean isStruggling) {
        super(playerUUID);
        this.isStruggling = isStruggling;
    }

    /**
     * Create a packet from a player's current struggle state.
     *
     * @param player The player
     * @return The packet, or null if player has no bind state
     */
    public static PacketSyncStruggleState fromPlayer(Player player) {
        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state == null) {
            return null;
        }

        return new PacketSyncStruggleState(
            player.getUUID(),
            state.isStruggling()
        );
    }

    /**
     * Encode the packet to a byte buffer.
     */
    public void encode(FriendlyByteBuf buf) {
        encodeUUID(buf);
        buf.writeBoolean(isStruggling);
    }

    /**
     * Decode the packet from a byte buffer.
     */
    public static PacketSyncStruggleState decode(FriendlyByteBuf buf) {
        UUID playerUUID = decodeUUID(buf);
        boolean isStruggling = buf.readBoolean();
        return new PacketSyncStruggleState(playerUUID, isStruggling);
    }

    /**
     * Apply the struggle state sync to a player.
     */
    @Override
    @OnlyIn(Dist.CLIENT)
    protected void applySync(Player player) {
        PlayerBindState state = PlayerBindState.getInstance(player);
        if (state == null) {
            return;
        }

        // Update struggle state (client-side only - server manages timer)
        state.setStrugglingClient(isStruggling);
    }

    // queueForRetry() not needed - struggle state is non-critical and will be re-sent

    // Getters

    public boolean isStruggling() {
        return isStruggling;
    }
}
