<div class="@ContainerClassees">
    <div class="@OverlayClasses"></div>
    <img class="@ImageClasses" loading="@LoadingAttribute" src="@Source" @onload="OnImageLoaded">
</div>

@code {
    [Parameter]
    public required string Source { get; set; }

    [Parameter]
    public string FallbackSource { get; set; } = "images/home/no_img_main.gif";

    [Parameter]
    public bool LazyLoading { get; set; } = true;

    [Parameter]
    public string? ContainerClass { get; set; }

    [Parameter]
    public string? OverlayClass { get; set; }

    [Parameter]
    public string? ImageClass { get; set; }

    private bool _isLoaded;
    private string? _lastSource;

    private string ContainerClassees => GetContainerClasses();
    private string OverlayClasses => GetOverlayClasses();
    private string ImageClasses => GetImageClasses();

    private string? LoadingAttribute => LazyLoading ? "lazy" : null;

    protected override void OnParametersSet()
    {
        if (!string.Equals(_lastSource, Source, StringComparison.Ordinal))
        {
            _lastSource = Source;
            _isLoaded = false;
        }
    }

    private string GetContainerClasses()
    {
        List<string> classNames = ["j-image-container"];

        if (!string.IsNullOrEmpty(ContainerClass))
        {
            List<string> customClassNames = ContainerClass
                .Split(" ")
                .Select(className => className.Trim())
                .Where(className => !string.IsNullOrWhiteSpace(className))
                .ToList();

            classNames.AddRange(customClassNames);
        }

        return string.Join(" ", classNames);
    }

    private string GetOverlayClasses()
    {
        List<string> classNames = ["j-image-overlay"];

        if (!string.IsNullOrEmpty(OverlayClass))
        {
            List<string> customClassNames = OverlayClass
                .Split(" ")
                .Select(className => className.Trim())
                .Where(className => !string.IsNullOrWhiteSpace(className))
                .ToList();

            classNames.AddRange(customClassNames);
        }

        return string.Join(" ", classNames);
    }

    private string GetImageClasses()
    {
        List<string> classNames = ["j-image"];

        if (!_isLoaded)
        {
            classNames.Add("j-lazy-load");
        }

        if (!string.IsNullOrEmpty(ImageClass))
        {
            List<string> customClassNames = ImageClass
                .Split(" ")
                .Select(className => className.Trim())
                .Where(className => !string.IsNullOrWhiteSpace(className))
                .ToList();

            classNames.AddRange(customClassNames);
        }

        return string.Join(" ", classNames);
    }

    private void OnImageLoaded()
    {
        _isLoaded = true;
    }
}