package de.winniepat.citrus.cosmetics.capes.sync;

import de.winniepat.citrus.managers.ClientRegistrationManager;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.player.PlayerEntity;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class PlayerCapeTracker {
    private static final Map<UUID, Long> LAST_SEEN_PLAYERS = new ConcurrentHashMap<>();
    private static final long SYNC_INTERVAL = 30000;

    public static void tick() {
        MinecraftClient client = MinecraftClient.getInstance();
        if (client.world == null || client.player == null) return;

        List<UUID> citrusUsersToSync = new ArrayList<>();
        long currentTime = System.currentTimeMillis();

        for (PlayerEntity player : client.world.getPlayers()) {
            UUID uuid = player.getUuid();

            if (player == client.player) continue;

            if (!ClientRegistrationManager.isPlayerOnlineWithCitrus(uuid)) {
                continue;
            }

            Long lastSeen = LAST_SEEN_PLAYERS.get(uuid);
            if (lastSeen == null || currentTime - lastSeen > SYNC_INTERVAL) {
                citrusUsersToSync.add(uuid);
                LAST_SEEN_PLAYERS.put(uuid, currentTime);
            }
        }

        if (!citrusUsersToSync.isEmpty()) {
            CapeSyncManager.batchFetchCapes(citrusUsersToSync);
        }

        Iterator<Map.Entry<UUID, Long>> iterator = LAST_SEEN_PLAYERS.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<UUID, Long> entry = iterator.next();
            UUID uuid = entry.getKey();

            boolean stillPresent = client.world.getPlayers().stream()
                    .anyMatch(p -> p.getUuid().equals(uuid) && p != client.player);

            if (!stillPresent && currentTime - entry.getValue() > 60000) {
                iterator.remove();
                CapeSyncManager.clearCache(uuid);
            }
        }

        if (currentTime % 60000 < 50) {
            CapeSyncManager.retryPendingUpdates();
        }
    }
}