UI/Window/WindowContainer.razor
@using System;
@using Sandbox;
@using Sandbox.UI;
@inherits Panel
@namespace HC3.UI

@if ( !Window.IsValid() )
{
    Close();
    Delete( true );
    return;
}

<root style="left: @(Window.ScreenPosition.x * ScaleFromScreen)px; top: @(Window.ScreenPosition.y * ScaleFromScreen)px;">
    <div class="titlebar" @ref=Titlebar>
        @if ( Window.Icon is not null )
        {
            <Silkicon Icon="@Window.Icon" />
        }

        <label class="title">@Window.Title</label>

        @if ( Window.IsPinnable )
        {
            <div class="close" onclick=@(() => TogglePinned())><i>@(Window.Pinned ? "eject" : "push_pin")</i></div>
        }

        @if ( CanShrink )
        {
            <div class="close @(IsShrunk ? "" : "offset")" onclick=@(() => ToggleShrink())><i>@(IsShrunk ? "open_in_full" : "minimize")</i></div>
        }

        <div class="close" onclick=@(() => Close())><i>close</i></div>

    </div>
    <div @ref=Content></div>
</root>

@code
{
    public bool IsShrunk { get; private set; }
    public bool IsDragging { get; private set; }
    public bool IsActive => WindowManager.Instance.Focused == Window;

    public bool CanShrink => Window.CanShrink;

    public Window Window { get; init; }

    private Panel Titlebar;
    public Panel Content { get; set; }

    public WindowContainer( Window window )
    {
        Window = window;

        BindClass( "active", () => IsActive );
        BindClass( "shrunk", () => IsShrunk );
    }

    void TogglePinned()
    {
        Window.Pinned = !Window.Pinned;
    }

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

        if ( !Window.IsValid() )
            return;

        Content.AddChild( Window );
        Window.AddClass( "content" );

        if ( firstTime )
        {
            WindowManager.Instance.BringToFront( Window );
        }
    }

    protected override void OnMouseDown(MousePanelEvent e)
    {
        base.OnMouseDown(e);

        if ( e.Button == "mouseleft" && Titlebar.IsInside( Mouse.Position ) )
            IsDragging = true;

        // Already in front
        if (WindowManager.Instance.Focused == Window) 
            return;

		WindowManager.Instance.BringToFront( Window );
	}

	protected override void OnMouseUp(MousePanelEvent e)
	{
		base.OnMouseUp(e);
		IsDragging = false;
	}

	protected override void OnMouseMove(MousePanelEvent e)
	{
		base.OnMouseMove(e);

		if ( IsDragging )
		{
			Window.ScreenPosition += Mouse.Delta;
			//Window.ConstrainToScreen();
		}
	}

	public virtual void Close()
	{
		Sound.Play( "click2" );

		WindowManager.Instance.Close( Window );
	}

	public virtual void ToggleShrink()
	{
		IsShrunk = !IsShrunk;
		Content.Style.Display = IsShrunk ? DisplayMode.None : DisplayMode.Flex;
	}

	protected override int BuildHash()
	{
		if ( !Window.IsValid() ) return 0;
		return HashCode.Combine( Window.Position, ScaleFromScreen, Window.Title );
	}
}