using System;
using System.Threading.Tasks;
using Microsoft.JSInterop;

namespace FilterCair.Client.Services
{
    public class AppState
    {
        private readonly IJSRuntime _js;
        public AppState(IJSRuntime js)
        {
            _js = js;
        }

        public string? SelectedCustomer { get; private set; }

        public bool IsOnline { get; private set; } = true;
        public event Action? OnChange;

        private void NotifyStateChanged() => OnChange?.Invoke();

        public async Task SetCustomerAsync(string customer)
        {
            SelectedCustomer = customer;
            await _js.InvokeVoidAsync("sessionStorage.setItem", "selectedCustomer", customer);
            NotifyStateChanged();
        }

        public async Task LoadFromSessionAsync()
        {
            SelectedCustomer = await _js.InvokeAsync<string?>("sessionStorage.getItem", "selectedCustomer");
            NotifyStateChanged();
        }

        public void SetOnlineStatus(bool isOnline)
        {
            IsOnline = isOnline;
            NotifyStateChanged();
        }

        public async Task ClearAsync()
        {
            SelectedCustomer = null;
            await _js.InvokeVoidAsync("sessionStorage.removeItem", "selectedCustomer");
            NotifyStateChanged();
        }



    }
}
