@section Css
{
    <style>
        html {
            height: 100vh; background: hsl(0, 0%, 95%);
        }
        .app {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            text-align: center;
        }
        .spinner { color: #00a996 }
        .button {
            min-width: 64px;
            font-weight: bold;
            height: 32px;
            border: none;
            border-radius: 2px;
            text-decoration: none;
            text-transform: uppercase;
            text-align: center;
            background: #e36927;
            color: #fcfcfc;
            --buttonHoverColor: hsl(from #e36927 h s l / 0.84);
            --rippleColor: #fcfcfc;
            position: relative;
            transition: background 100ms 0ms cubic-bezier(.4, 0, .2, 1), box-shadow 250ms 0ms cubic-bezier(.4, 0, .2, 1);
            box-shadow: 0 2px 2px 0 hsl(0 0% 0% / 0.14), 0 1px 5px 0 hsl(0 0% 0% / 0.12), 0 3px 1px -2px hsl(0 0% 0% / 0.2);
            padding-inline: 16px;
            overflow: hidden;
        }
        #popup-blocker-warning {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
    </style>
    <link rel="stylesheet" href="@Url.Action("LoadingSplash", "Css")" />
}

@section Scripts
{
}

@Html.AntiForgeryToken()

<div class="app" id="app">
    @Html.Partial("Spinner", "large")
    <div id="popup-blocker-warning" style="display: none;">
        Unable to authenticate with Zap Data Hub. Ensure browser popup blocker is disabled for this site and retry.
        <br />
        <br />
        <button class="button" id="retryButton" style="display: inline;" onclick="requestPopupAuthentication();">Retry</button>
    </div>
</div>

<script>
    if (Object.create){
        window.addEventListener('message', (event) => {
            if (event.origin !== '@ViewBag.ApiServiceBaseUrl') {
                return;
            }
            let eventData = JSON.parse(event.data);

            if (eventData.type === 'AuthError' || isPopupAuthResponseInvalid(eventData)) {
                handleErrorMessage(eventData);
                document.getElementById('popup-blocker-warning').style.display = 'block';
                document.getElementsByClassName('spinner')[0].style.display = 'none';
                return;
            }

            if (shouldRequestPopupAuthentication(eventData.type)) {
                requestPopupAuthentication();
                return;
            }

            fetch('@Url.Action("AuthenticateTeamsAppToken", "User")', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + eventData.authToken,
                    'Content-Type': 'application/json',
                    'TokenType': eventData.type,
                    'Application': '@ViewBag.ApplicationType'
                },
                body: JSON.stringify({ returnUrl: eventData.link })
            }).then(response => {
                if (response.ok) {
                    window.location.href = eventData.link;
                } else {
                    throw new Error('Failed to authenticate user.');
                }
            }).catch(_ => {
                eventData.type == "PopupAuthResponse" ? clearPopupCachedToken() : requestPopupAuthentication();
            });

        });
    }
    else
        location.href = '@Url.Action("UnsupportedDocumentMode", "Error", new
                                 {
                                     originalUrl = Request.RawUrl
                                 }, Request.Url.Scheme)';

    function isPopupAuthResponseInvalid(eventData){
        return eventData.type === 'PopupAuthResponse' && eventData.authToken === "";
    }

    function handleErrorMessage(eventData){
        const logEvent = {
            Level: "Warning",
            MessageTemplate: "Teams authentication failed:  {Error}",
            MessageProperties: [eventData.error],
            ContextProperties: {
                Error: eventData.error
            }
        };
        fetch('@Url.Action("LogEvent", "ClientLogging")', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(logEvent)
        })
    }

    function shouldRequestPopupAuthentication(eventType){
        return eventType === "SSOToken" && '@ViewBag.AuthenticationProtocol' !== "EntraId";
    }

    function requestPopupAuthentication(){
        window.parent.postMessage(JSON.stringify({ type: "RequestPopupAuth"}), '@ViewBag.ApiServiceBaseUrl');
    }

    function clearPopupCachedToken(){
        window.parent.postMessage(JSON.stringify({ type: "RequestPopupAuth", message: "ClearCachedToken"}), '@ViewBag.ApiServiceBaseUrl');
    }
</script>