UI/CatalogItemPanel.razor
@using Sandbox;
@using Sandbox.UI;
@using HC3.UI

@inherits Panel
@namespace HC3

<root>
    <div tooltip="@IPlacementObject.GetPurchaseFailedReason(Item)" class="@(IsSelected ? "selected" : "") @(IPlacementObject.CanPurchase(Item) ? "" : "locked") item">
		<img class="image" [email protected] onclick=@(() => StartPlacing()) />
		@if (Item.GetTintComponent().IsValid())
		{
			var deco = Item.GetTintComponent();
			<div class="color-deco">
				<label class="yes">palette</label>
				<div class="tint-swatch">
					@if (deco.PrimaryEnabled)
					{
						<div class="color-swatch @(SelectedTintChannel == TintChannel.Primary ? "selected" : "")" style=@($"background-color: {NewRedColor.Hex}") onclick=@(() => SetSelectedTint(TintChannel.Primary))></div>
					}
					@if (deco.SecondaryEnabled)
					{
						<div class="color-swatch @(SelectedTintChannel == TintChannel.Secondary ? "selected" : "")" style=@($"background-color: {NewGreenColor.Hex}") onclick=@(() => SetSelectedTint(TintChannel.Secondary))></div>
					}
					@if (deco.AccentEnabled)
					{
						<div class="color-swatch @(SelectedTintChannel == TintChannel.Accent ? "selected" : "")" style=@($"background-color: {NewBlueColor.Hex}") onclick=@(() => SetSelectedTint(TintChannel.Accent))></div>
					}
					@if (deco.DetailEnabled)
					{
						<div class="color-swatch @(SelectedTintChannel == TintChannel.Detail ? "selected" : "")" style=@($"background-color: {NewAlphaColor.Hex}") onclick=@(() => SetSelectedTint(TintChannel.Detail))></div>
					}
				</div>
			</div>
		}
		<div class="info">

			<label class="name">@Item.Title</label>
			<label class="cost">@(GameUtils.Currency)@(Item.Cost)</label>
		</div>
	</div>
</root>

@code
{
    public bool IsSelected { get; set; } = false;

    Color StartingRedColor => Item.GetTintComponent().IsValid() ? Item.GetTintComponent().PrimaryColor : Color.White;
    Color StartingGreenColor => Item.GetTintComponent().IsValid() ? Item.GetTintComponent().SecondaryColor : Color.White;
    Color StartingBlueColor => Item.GetTintComponent().IsValid() ? Item.GetTintComponent().AccentColor : Color.White;
    Color StartingAlphaColor => Item.GetTintComponent().IsValid() ? Item.GetTintComponent().DetailColor : Color.White;

    Color NewRedColor = Color.White;
    Color NewGreenColor = Color.White;
    Color NewBlueColor = Color.White;
    Color NewAlphaColor = Color.White;

    private IPlacementObject _item;

    public IPlacementObject Item
    {
        get => _item;
        set
        {
            if (value == _item) return;
            _item = value;

            if ( _item.IsValid() )
            {
                var deco = _item.GetTintComponent();
                NewRedColor = deco.IsValid() ? deco.PrimaryColor : Color.White;
                NewGreenColor = deco.IsValid() ? deco.SecondaryColor : Color.White;
                NewBlueColor = deco.IsValid() ? deco.AccentColor : Color.White;
                NewAlphaColor = deco.IsValid() ? deco.DetailColor : Color.White;
            }
        }
    }


    protected override void OnAfterTreeRender(bool firstTime)
    {
        base.OnAfterTreeRender(firstTime);

        if(firstTime)
        {
            if (!Item.IsValid()) return;
            // Set the initial color values
            NewRedColor = Item.GetTintComponent().IsValid() ? Item.GetTintComponent().PrimaryColor : Color.White;
            NewGreenColor = Item.GetTintComponent().IsValid() ? Item.GetTintComponent().SecondaryColor : Color.White;
            NewBlueColor = Item.GetTintComponent().IsValid() ? Item.GetTintComponent().AccentColor : Color.White;
            NewAlphaColor = Item.GetTintComponent().IsValid() ? Item.GetTintComponent().DetailColor : Color.White;

            // From saved cookies if we have them
            NewRedColor = Game.Cookies.Get($"{Item.GameObject.Name}_{(int)TintChannel.Primary}", NewRedColor);
            NewGreenColor = Game.Cookies.Get($"{Item.GameObject.Name}_{(int)TintChannel.Secondary}", NewGreenColor);
            NewBlueColor = Game.Cookies.Get($"{Item.GameObject.Name}_{(int)TintChannel.Accent}", NewBlueColor);
            NewAlphaColor = Game.Cookies.Get($"{Item.GameObject.Name}_{(int)TintChannel.Detail}", NewAlphaColor);
        }
    }

    void StartPlacing()
    {
        if ( !Item.IsValid() ) 
            return;

        if ( !IPlacementObject.CanPurchase( Item ) )
        {
            var reason = IPlacementObject.GetPurchaseFailedReason( Item );
            if ( reason is not null )
            {
                NotificationPanel.Instance?.Broadcast( $"Not enough money! (Costs {GameUtils.Currency}{Item.Cost})", "money_off" );
            }
            Sound.Play( "error" );
            return;
        }

        BuildingPlacer.Instance.StartPlacing(Item);

        // Reset selection
        SelectedColor = Color.White;
        SelectedTintChannel = TintChannel.Primary;

        Log.Info($"Placing {Item.Title}");

        // Apply tint colors from the selected item
        var deco = Item.GetTintComponent();
        if (deco.IsValid())
        {
            SelectedColor = NewRedColor;

            if (deco.PrimaryEnabled)
            {
                BuildingPlacer.Instance?.SetDecorationColor(NewRedColor, TintChannel.Primary);
            }
            else
            {
                BuildingPlacer.Instance?.SetDecorationColor(Color.White, TintChannel.Primary);
            }

            if (deco.SecondaryEnabled)
            {
                BuildingPlacer.Instance?.SetDecorationColor(NewGreenColor, TintChannel.Secondary);
            }
            else
            {
                BuildingPlacer.Instance?.SetDecorationColor(Color.White, TintChannel.Secondary);
            }

            if (deco.AccentEnabled)
            {
                BuildingPlacer.Instance?.SetDecorationColor(NewBlueColor, TintChannel.Accent);
            }

            else
            {
                BuildingPlacer.Instance?.SetDecorationColor(Color.White, TintChannel.Accent);

            }
            if (deco.DetailEnabled)
            {
                BuildingPlacer.Instance?.SetDecorationColor(NewAlphaColor, TintChannel.Detail);
            }
            else
            {
                BuildingPlacer.Instance?.SetDecorationColor(Color.White, TintChannel.Detail);

            }
        }

        //CloseCanvas("FeaturesCanvas");
    }

    protected override int BuildHash() => System.HashCode.Combine(base.BuildHash(), BuildingPlacer.Instance?.IsDestroying, BuildingPlacer.Instance.PlacingResource, SelectedColor, NewRedColor, NewGreenColor, NewBlueColor, NewAlphaColor);

    TintChannel? SelectedTintChannel = TintChannel.Primary;
    Color SelectedColor = Color.White;
    ColorPicker colorPicker;

    void SetSelectedTint(TintChannel channel)
    {
        SelectedTintChannel = channel;

        var color = channel switch
        {
            TintChannel.Primary => NewRedColor,
            TintChannel.Secondary => NewGreenColor,
            TintChannel.Accent => NewBlueColor,
            TintChannel.Detail => NewAlphaColor,
            _ => Color.White
        };

        if ( !colorPicker.IsValid() )
            colorPicker = new ColorPicker(color, OnColorPicked);

        colorPicker.SetColor(color);
        WindowManager.Instance.Open(colorPicker);
        colorPicker.SetPosition(Screen.Size / 2, Window.ScreenAlignment.Center);
    }

    void OnColorPicked(Color color)
    {
        if (color == SelectedColor) return;

        SelectedColor = color;

        if ( !SelectedTintChannel.HasValue )
            return;

        // Apply to the selected tint channel
        switch ( SelectedTintChannel.Value )
        {
            case TintChannel.Primary:
                NewRedColor = color;
                break;
            case TintChannel.Secondary:
                NewGreenColor = color;
                break;
            case TintChannel.Accent:
                NewBlueColor = color;
                break;
            case TintChannel.Detail:
                NewAlphaColor = color;
                break;
        }

        Game.Cookies.Set($"{Item.GameObject.Name}_{(int)SelectedTintChannel.Value}", SelectedColor );

		// Send to the placer
		BuildingPlacer.Instance?.SetDecorationColor( color, SelectedTintChannel.Value );

		StateHasChanged();
	}
}