@inject IJSRuntime JS

<div class="border border-border rounded-[var(--radius-lg)] overflow-hidden">
    <Flex Class="p-6 items-center justify-center min-h-[120px] bg-background">
        @ChildContent
    </Flex>
    @if (_showCode && !string.IsNullOrEmpty(Code))
    {
        <div class="border-t border-border bg-muted/20 overflow-x-auto">
            <pre class="p-4 text-xs leading-relaxed text-foreground font-mono whitespace-pre-wrap">@Code</pre>
        </div>
    }
    <Flex Class="border-t border-border px-4 py-2 items-center justify-between text-sm text-muted-foreground">
        <Lumeo.Text As="span">@Label</Lumeo.Text>
        <Flex Class="items-center gap-2">
            @if (_showCode && !string.IsNullOrEmpty(Code))
            {
                <Button Class="text-xs hover:text-foreground transition-colors flex items-center gap-1"
                        OnClick="CopyCode">
                    @if (_copied)
                    {
                        <DynamicIcon Name="Check" Class="h-3 w-3 text-primary" />
                        <Lumeo.Text As="span" Class="text-primary">Copied</Lumeo.Text>
                    }
                    else
                    {
                        <DynamicIcon Name="Clipboard" Class="h-3 w-3" />
                        <Lumeo.Text As="span">Copy</Lumeo.Text>
                    }
                </Button>
            }
            <Button Class="text-xs hover:text-foreground transition-colors flex items-center gap-1"
                    OnClick="Toggle">
                <DynamicIcon Name="Code" Class="h-3 w-3" />
                @(_showCode ? "Hide code" : "View code")
            </Button>
        </Flex>
    </Flex>
</div>

@code {
    [Parameter] public RenderFragment? ChildContent { get; set; }
    [Parameter] public string? Label { get; set; }
    [Parameter] public string? Code { get; set; }

    private bool _showCode;
    private bool _copied;

    private void Toggle() => _showCode = !_showCode;

    private async Task CopyCode()
    {
        if (string.IsNullOrEmpty(Code)) return;
        await JS.InvokeVoidAsync("navigator.clipboard.writeText", Code);
        _copied = true;
        StateHasChanged();
        await Task.Delay(2000);
        _copied = false;
        StateHasChanged();
    }
}
