#pragma once

#include "CoreMinimal.h"
#include "UIActivatableScreen_Base.h"
#include "ZMMOWorldEntry.h"
#include "UIServerSelectScreen_Base.generated.h"

class UCommonTextBlock;
class UBorder;
class UPanelWidget;
class UUIServerCard_Base;
class UZeusCharServerSubsystem;

/**
 * Tela de Server Select — Fase 1 do ARQUITETURA_SERVER_SELECT.
 *
 * Fluxo:
 *  1. NativeOnActivated subscreve OnRawMessage do UZeusCharServerSubsystem
 *  2. Envia C_WORLD_LIST_REQUEST (payload vazio)
 *  3. ParseWorldList monta `Worlds`
 *  4. RebuildCards apaga filhos de `CardContainer` e instancia 1 WBP_ServerCard
 *     por mundo, bindando `OnCardPressed -> SelectWorldAndProceed`
 *  5. Dispara `OnWorldListReceived` (BIE) pra extensoes em BP
 */
UCLASS(Abstract, Blueprintable)
class ZMMO_API UUIServerSelectScreen_Base : public UUIActivatableScreen_Base
{
	GENERATED_BODY()

public:
	UFUNCTION(BlueprintCallable, Category = "Zeus|ServerSelect")
	void RequestWorldList();

	UFUNCTION(BlueprintCallable, Category = "Zeus|ServerSelect")
	void SelectWorldAndProceed(const FString& WorldId);

	UPROPERTY(BlueprintReadOnly, Category = "Zeus|ServerSelect")
	TArray<FZMMOWorldEntry> Worlds;

	UFUNCTION(BlueprintImplementableEvent, Category = "Zeus|ServerSelect")
	void OnWorldListReceived();

protected:
	virtual void NativePreConstruct() override;
	virtual void NativeOnActivated() override;
	virtual void NativeOnDeactivated() override;
	virtual void RefreshUIStyle_Implementation() override;

	UFUNCTION()
	void HandleCharRawMessage(int32 Opcode, const TArray<uint8>& Payload);

	UFUNCTION()
	void HandleCardPressed(FString WorldId, uint8 State);

	UZeusCharServerSubsystem* GetCharServer() const;
	void ParseWorldList(const TArray<uint8>& Payload);
	void ApplyStatusUpdate(const TArray<uint8>& Payload);
	void RebuildCards();

	/** Background e titulo (mantidos para RefreshUIStyle). */
	UPROPERTY(meta = (BindWidgetOptional)) TObjectPtr<UBorder>          Border_Bg;
	UPROPERTY(meta = (BindWidgetOptional)) TObjectPtr<UCommonTextBlock> Text_Title;

	/**
	 * Container onde os cards sao instanciados (ScrollBox/VerticalBox/
	 * UniformGridPanel/WrapBox — qualquer UPanelWidget serve).
	 */
	UPROPERTY(meta = (BindWidget)) TObjectPtr<UPanelWidget> CardContainer;

	/**
	 * Classe do card a instanciar. Configurada no WBP_ServerSelect
	 * (Defaults) ou via Project Settings se for global.
	 */
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Zeus|ServerSelect")
	TSubclassOf<UUIServerCard_Base> CardClass;

private:
	bool bSubscribed = false;

	UPROPERTY(Transient)
	TArray<TObjectPtr<UUIServerCard_Base>> SpawnedCards;
};
