namespace Tests.Pages.BuildCalculator;

public class HotkeyViewerComponent
{
    private readonly Website _website;

    public HotkeyViewerComponent(Website website)
    {
        _website = website;
    }

    public ILocator KeyContainer => _website.Locator(".keyContainer");

    public async Task<ILocator?> FindKeyButtonAsync(string keyLabel)
    {
        var upper = keyLabel.ToUpperInvariant();
        var buttons = KeyContainer.Locator("> div > div");
        var count = await buttons.CountAsync();
        for (var i = 0; i < count; i++)
        {
            var btn = buttons.Nth(i);
            var text = (await btn.TextContentAsync())?.Trim().ToUpperInvariant() ?? "";
            if (text.StartsWith(upper)) return btn;
        }

        return null;
    }

    public async Task ClickKeyAsync(string keyText)
    {
        var btn = await FindKeyButtonAsync(keyText);
        if (btn is null) throw new InvalidOperationException($"Key \"{keyText}\" not found");
        await btn.ClickAsync(new LocatorClickOptions { Force = true });
    }

    public async Task<string?> GetFirstEntityNameAsync(string keyText)
    {
        var btn = await FindKeyButtonAsync(keyText);
        if (btn is null) return null;
        var entities = btn.Locator("> div");
        if (await entities.CountAsync() == 0) return null;
        return (await entities.First.TextContentAsync())?.Trim();
    }

    public async Task<IReadOnlyList<string>> GetEntityNamesOnKeyAsync(string keyText)
    {
        var btn = await FindKeyButtonAsync(keyText);
        if (btn is null) return Array.Empty<string>();
        var entities = btn.Locator("> div");
        var count = await entities.CountAsync();
        var names = new List<string>();
        for (var i = 0; i < count; i++)
        {
            var text = (await entities.Nth(i).TextContentAsync())?.Trim();
            if (!string.IsNullOrEmpty(text)) names.Add(text);
        }

        return names;
    }
}