using System.Text.Json;
using Microsoft.JSInterop;

namespace FrontOffice.Main.Utilities;

/// <summary>
/// اسکرول/فوکوس محصول پس از بازگشت از جزئیات — کلیدهای محدود به لیست فروشگاه (نه لندینگ).
/// </summary>
public static class ShopListScrollRestore
{
    public const string StoreKey = "fo:store:scroll";
    public const string DiscountKey = "fo:discount:scroll";

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    public static async Task SaveAsync(IJSRuntime js, string storageKey, long productId)
    {
        double scrollY = 0;
        try
        {
            scrollY = await js.InvokeAsync<double>("eval", "window.scrollY || window.pageYOffset || 0");
        }
        catch
        {
            // ignore
        }

        var payload = JsonSerializer.Serialize(new ScrollPayload(productId, scrollY), JsonOptions);
        await js.InvokeVoidAsync("sessionStorage.setItem", storageKey, payload);
    }

    public static async Task<ScrollPayload?> TakeAsync(IJSRuntime js, string storageKey)
    {
        try
        {
            var raw = await js.InvokeAsync<string?>("sessionStorage.getItem", storageKey);
            await js.InvokeVoidAsync("sessionStorage.removeItem", storageKey);
            if (string.IsNullOrWhiteSpace(raw))
                return null;
            return JsonSerializer.Deserialize<ScrollPayload>(raw, JsonOptions);
        }
        catch
        {
            return null;
        }
    }

    public static async Task RestoreAsync(IJSRuntime js, ScrollPayload payload)
    {
        try
        {
            await js.InvokeVoidAsync("eval",
                $@"(function(){{
                    var el = document.getElementById('shop-product-{payload.ProductId}');
                    if (el) {{ el.scrollIntoView({{ block: 'center', behavior: 'instant' }}); return; }}
                    window.scrollTo(0, {payload.ScrollY.ToString(System.Globalization.CultureInfo.InvariantCulture)});
                }})()");
        }
        catch
        {
            // ignore
        }
    }

    public sealed record ScrollPayload(long ProductId, double ScrollY);
}
