{% extends "base.html" %}
{% block title %}OIDC Login{% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block content %}
<div class="text-center">
    <div id="signed-in" class="bg-blue-100 border border-blue-400 text-blue-700 px-4 py-3 rounded relative mb-8 hidden"
        role="alert">
        <p>You seem to be logged in already.</p>
        <p><a href="/" class="text-blue-600 hover:underline hover:text-blue-700 font-bold">Open the Home Assistant
                dashboard</a></p>
    </div>

    {% if code %}
        <div>
            <p id="device-instructions">Please login to Home Assistant on another device and enter this code when asked:</p>
            <div class="mt-4 text-3xl tracking-wide font-bold bg-gray-100 border border-gray-300 rounded-lg py-4 px-6 inline-block" id="device-code">
                {{ code }}
            </div>
            <p class="mt-4 text-sm text-gray-600">
                The login will continue automatically when you complete the login on your other device. Please keep the app open.
            </p>
        </div>
        <script>
            const source = new EventSource('/auth/oidc/device-sse');

            source.addEventListener('ready', function () {
                source.close();

                // Perform a POST request to the finish endpoint to complete the login.
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '/auth/oidc/finish';
                document.body.appendChild(form);
                form.submit();
            });

            source.addEventListener('error', function () {
                source.close();
            });
        </script>
    {% else %}
        <div>
                <a id="login-button" href="/auth/oidc/redirect" class="
                    w-full py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 
                    focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75
                    hover:cursor-pointer
                ">
                Login with {{ name }}
            </a>
        </div>
    {% endif %}

    {% if other_link %}
        <p class=" mt-4 text-sm text-center">
            <a id="alternative-sign-in-link" href="{{ other_link }}" class="text-gray-600 hover:underline">Use alternative sign-in method</a>
        </p>
    {% endif %}
</div>
<script>
    // Show the direct login button if we already have a token
    if (localStorage.getItem('hassTokens')) {
        document.getElementById('signed-in').classList.remove('hidden');
    }
</script>
{% endblock %}