@using RpgRoller.Components.Pages.HomeControls
@attribute [ExcludeFromCodeCoverage]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <base href="@BaseHref"/>
    <title>RpgRoller</title>
    <link rel="stylesheet" href="@Assets["styles.css"]"/>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@400;500;600;700&family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Color+Emoji&display=swap" rel="stylesheet">
    @if (UseInteractiveApp)
    {
        <HeadOutlet/>
    }
</head>
<body>
@if (UseStaticAuthPage)
{
    <StaticAuthPage StatusMessage="@AuthStatusMessage" StatusIsError="@AuthStatusIsError"/>
}
else
{
    <Routes/>
}
<script src="js/rpgroller-api.js"></script>
@if (UseInteractiveApp)
{
    <script src="_framework/blazor.web.js" autostart="false"></script>
    <script>
        Blazor.start({
            ssr: {
                disableDomPreservation: true
            }
        });
    </script>
}
</body>
</html>

@code {
    [CascadingParameter] private HttpContext? HttpContext { get; set; }

    private bool UseInteractiveApp => !UseStaticAuthPage;

    private bool UseStaticAuthPage => IsLoginRequest;

    private bool IsLoginRequest
    {
        get
        {
            var path = HttpContext?.Request.Path.Value;
            return string.Equals(path, "/login", StringComparison.Ordinal);
        }
    }

    private string? AuthStatusMessage => ReadAuthQueryValue("message");

    private bool AuthStatusIsError => string.Equals(ReadAuthQueryValue("kind"), "error", StringComparison.OrdinalIgnoreCase);

    private string BaseHref
    {
        get
        {
            var pathBase = HttpContext?.Request.PathBase.Value;
            if (string.IsNullOrWhiteSpace(pathBase))
                return "/";

            return pathBase.EndsWith('/') ? pathBase : $"{pathBase}/";
        }
    }

    private string? ReadAuthQueryValue(string key)
    {
        if (!IsLoginRequest || HttpContext is null)
            return null;

        var value = HttpContext.Request.Query[key];
        return value.Count > 0 ? value[0] : null;
    }

}
