using Microsoft.JSInterop;

namespace WebClientTpos.Client.Services;

/// <summary>
/// EN: Typed localStorage service — wraps IJSRuntime to provide type-safe key/value access.
///     Consolidates scattered localStorage.getItem/setItem/removeItem calls (FRONT-W-07).
/// VI: Service localStorage có kiểu — bao bọc IJSRuntime để truy cập key/value an toàn kiểu.
///     Tập trung các lời gọi localStorage.getItem/setItem/removeItem rải rác (FRONT-W-07).
/// </summary>
public class LocalStorageService
{
    private readonly IJSRuntime _js;

    public LocalStorageService(IJSRuntime js) => _js = js;

    /// <summary>
    /// EN: Read a string value from localStorage. Returns null if key does not exist or JS is unavailable.
    /// VI: Đọc giá trị chuỗi từ localStorage. Trả về null nếu key không tồn tại hoặc JS không khả dụng.
    /// </summary>
    public async Task<string?> GetAsync(string key)
    {
        try { return await _js.InvokeAsync<string?>("localStorage.getItem", key); }
        catch { return null; }
    }

    /// <summary>
    /// EN: Write a string value to localStorage. Silently ignores errors (e.g. pre-render, storage full).
    /// VI: Ghi giá trị chuỗi vào localStorage. Bỏ qua lỗi (ví dụ pre-render, hết dung lượng).
    /// </summary>
    public async Task SetAsync(string key, string value)
    {
        try { await _js.InvokeVoidAsync("localStorage.setItem", key, value); }
        catch { }
    }

    /// <summary>
    /// EN: Remove a key from localStorage. Silently ignores errors.
    /// VI: Xoá key khỏi localStorage. Bỏ qua lỗi.
    /// </summary>
    public async Task RemoveAsync(string key)
    {
        try { await _js.InvokeVoidAsync("localStorage.removeItem", key); }
        catch { }
    }
}
