using System.Text.RegularExpressions;

namespace Tests.Pages.BuildCalculator;

public class ArmyComponent
{
    private readonly Website _website;

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

    public ILocator ArmyView => _website.Locator(".armyView");

    public ILocator ArmyCards => ArmyView.Locator(".armyCard");

    public ILocator DisplayValue(string label)
    {
        return _website.Locator(".displayContainer").Filter(new LocatorFilterOptions { HasText = label })
            .Locator(".displayContent");
    }

    public async Task<string> GetArmyCompletedAtAsync()
    {
        return (await DisplayValue("Army Completed At").TextContentAsync())?.Trim() ?? "";
    }

    public async Task<string> GetArmyAttackingAtAsync()
    {
        return (await DisplayValue("Army Attacking At").TextContentAsync())?.Trim() ?? "";
    }

    public async Task<IReadOnlyList<string>> GetArmyUnitNamesAsync()
    {
        var cards = await ArmyCards.AllAsync();
        var names = new List<string>();
        foreach (var card in cards)
        {
            var text = (await card.InnerTextAsync()).Trim();
            var match = Regex.Match(text, @"\d+x\s*(.+)");
            names.Add(match.Success ? match.Groups[1].Value.Trim() : text);
        }

        return names;
    }

    public async Task<IReadOnlyList<(string Name, int Count)>> GetArmyUnitCountsAsync()
    {
        var cards = await ArmyCards.AllAsync();
        var counts = new List<(string, int)>();
        foreach (var card in cards)
        {
            var countEl = card.Locator(".armyCount");
            var nameEl = card.Locator("div").Last;
            var count = (await countEl.TextContentAsync())?.Replace("x", "").Trim() ?? "0";
            var name = (await nameEl.TextContentAsync())?.Trim() ?? "";
            counts.Add((name, int.Parse(count)));
        }

        return counts;
    }
}