namespace MBN_STOCK_WEBVIEW.LegacyWeb.Tests;

public sealed class LegacyHiddenNonOriginalControlsTests
{
    private static readonly string RepositoryRoot = FindRepositoryRoot();
    private static readonly string Markup = File.ReadAllText(Path.Combine(
        RepositoryRoot,
        "src",
        "MBN_STOCK_WEBVIEW.LegacyParityApp",
        "Web",
        "index.html"));
    private static readonly string Styles = File.ReadAllText(Path.Combine(
        RepositoryRoot,
        "src",
        "MBN_STOCK_WEBVIEW.LegacyParityApp",
        "Web",
        "styles.css"));

    [Fact]
    public void NonOriginalShortcutsAndRuntimeClippedPrepareAndDissolveStayHidden()
    {
        Assert.Contains("class=\"manual-list-actions\" aria-label=\"수동 송출 목록\" hidden",
            Markup,
            StringComparison.Ordinal);
        Assert.Contains("id=\"playout-prepare\" class=\"prepare\" type=\"button\" disabled hidden",
            Markup,
            StringComparison.Ordinal);
        Assert.Contains("class=\"fade-control\" for=\"playout-fade-duration\" hidden",
            Markup,
            StringComparison.Ordinal);
        Assert.Contains("aria-hidden=\"true\">DissolveTime</label>",
            Markup,
            StringComparison.Ordinal);
        Assert.Contains(
            "id=\"playout-fade-duration\" disabled hidden aria-hidden=\"true\" tabindex=\"-1\"",
            Markup,
            StringComparison.Ordinal);
        Assert.Contains("*[hidden] { display: none !important; }", Styles,
            StringComparison.Ordinal);

        foreach (var id in new[]
                 {
                     "playout-prepare",
                     "playout-fade-duration"
                 })
        {
            Assert.Equal(1, Count(Markup, $"id=\"{id}\""));
        }

        foreach (var screen in new[] { "individual", "foreign", "institution", "vi" })
        {
            Assert.Contains($"data-manual-list-screen=\"{screen}\"", Markup,
                StringComparison.Ordinal);
        }
    }

    private static int Count(string value, string token)
    {
        var count = 0;
        var start = 0;
        while ((start = value.IndexOf(token, start, StringComparison.Ordinal)) >= 0)
        {
            count++;
            start += token.Length;
        }

        return count;
    }

    private static string FindRepositoryRoot()
    {
        var directory = new DirectoryInfo(AppContext.BaseDirectory);
        while (directory is not null)
        {
            if (File.Exists(Path.Combine(directory.FullName, "MBN_STOCK_WEBVIEW.sln")))
            {
                return directory.FullName;
            }

            directory = directory.Parent;
        }

        throw new DirectoryNotFoundException("Repository root was not found.");
    }
}
