package com.tiedup.remake.network.sync;

import com.tiedup.remake.network.base.AbstractPlayerSyncPacket;
import com.tiedup.remake.v2.bondage.movement.MovementStyle;
import java.util.UUID;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.Pose;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.jetbrains.annotations.Nullable;

/**
 * Server-to-client packet that syncs the active movement style for a player.
 * Sent when the active style changes (including clearing to null).
 *
 * <p>Extends {@link AbstractPlayerSyncPacket} for UUID-based player lookup
 * with retry support for login race conditions.</p>
 *
 * <p>Distribution: {@code ModNetwork.sendToAllTrackingAndSelf()} so all
 * nearby clients can render the correct animation for remote players.</p>
 */
public class PacketSyncMovementStyle extends AbstractPlayerSyncPacket {

    /** Marker byte for "no style" (null). */
    private static final byte NO_STYLE = -1;

    /** The active style ordinal, or -1 for null. */
    private final byte styleOrdinal;

    /**
     * Construct a sync packet.
     *
     * @param playerUUID the affected player's UUID
     * @param style      the active style, or null to clear
     */
    public PacketSyncMovementStyle(
        UUID playerUUID,
        @Nullable MovementStyle style
    ) {
        super(playerUUID);
        this.styleOrdinal = style == null ? NO_STYLE : (byte) style.ordinal();
    }

    private PacketSyncMovementStyle(UUID playerUUID, byte styleOrdinal) {
        super(playerUUID);
        this.styleOrdinal = styleOrdinal;
    }

    public void encode(FriendlyByteBuf buf) {
        encodeUUID(buf);
        buf.writeByte(styleOrdinal);
    }

    public static PacketSyncMovementStyle decode(FriendlyByteBuf buf) {
        UUID uuid = decodeUUID(buf);
        byte ordinal = buf.readByte();
        return new PacketSyncMovementStyle(uuid, ordinal);
    }

    @Override
    @OnlyIn(Dist.CLIENT)
    protected void applySync(Player player) {
        ClientHandler.handle(this, player);
    }

    @Override
    @OnlyIn(Dist.CLIENT)
    protected void queueForRetry() {
        // Movement style will be re-sent on next change or re-resolved on tick.
        // Non-critical: skip retry to avoid complexity.
    }

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

        private static void handle(PacketSyncMovementStyle pkt, Player player) {
            MovementStyle style = null;
            if (
                pkt.styleOrdinal >= 0 &&
                pkt.styleOrdinal < MovementStyle.values().length
            ) {
                style = MovementStyle.values()[pkt.styleOrdinal];
            }

            if (style != null) {
                com.tiedup.remake.client.state.MovementStyleClientState.set(
                    player.getUUID(),
                    style
                );
            } else {
                com.tiedup.remake.client.state.MovementStyleClientState.clear(
                    player.getUUID()
                );
            }

            // Crawl pose management: server sets forced pose for hitbox,
            // client must also set it for correct rendering
            if (style == MovementStyle.CRAWL) {
                player.setForcedPose(Pose.SWIMMING);
                player.refreshDimensions();
            } else {
                // Clear forced pose if it was previously set by crawl
                if (player.getForcedPose() == Pose.SWIMMING) {
                    player.setForcedPose(null);
                    player.refreshDimensions();
                }
            }
        }
    }
}
