<!doctype html>
<html lang="{{ locale|default('fr-FR') }}">
<head>
    <meta charset="utf-8">
    {% include 'partials/page-meta.twig' with { page: 'login' } only %}

    {# Google Identity Services + Sign in with Apple JS + Facebook SDK
       are loaded lazily and ONLY when their respective client id is
       configured. Buttons render server-side; the JS just wires the
       SDK callbacks to the (hidden) form submissions below. #}
    {% if oauth.google.clientId %}
        <script src="https://accounts.google.com/gsi/client" async defer></script>
    {% endif %}
    {% if oauth.apple.clientId %}
        <script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
    {% endif %}
</head>
<body>
    <h1>{{ trans('pages.login.title') }}</h1>

    {% if error %}
        <p role="alert" data-error-code="{{ error }}">
            {{ trans('pages.login.error.' ~ error) }}
        </p>
    {% endif %}

    {# Password sign-in — same form as before. #}
    <form method="post" action="/login">
        <input type="hidden" name="_csrf" value="{{ csrf_token }}">
        {% if return %}
            <input type="hidden" name="return" value="{{ return }}">
        {% endif %}

        <label>
            {{ trans('pages.login.email') }}
            <input type="email" name="email" required autocomplete="email">
        </label>

        <label>
            {{ trans('pages.login.password') }}
            <input type="password" name="password" required autocomplete="current-password">
        </label>

        <button type="submit">{{ trans('pages.login.submit') }}</button>
    </form>

    {# -------------------------------------------------------------------
       OAuth providers
       --------------------------------------------------------------------
       Each provider has:
         1. A HIDDEN form (action = our web OAuth endpoint) carrying _csrf
            + the OAuth token (filled by JS before submit()).
         2. A VISIBLE button: either the provider's own widget (Google
            renders its own `<div class="g_id_signin">`, Apple renders its
            own `<div id="appleid-signin">`), or a plain `<button>` for
            Facebook that we wire to FB.login().
       The hidden form approach lets the browser do a normal full-page
       POST (with the _csrf cookie attached automatically by the
       same-origin request) — same path as the password form. ------- #}

    {% if oauth.google.clientId or oauth.apple.clientId or oauth.facebook.appId %}
        <section aria-labelledby="oauth-heading">
            <h2 id="oauth-heading">{{ trans('pages.login.oauth.heading') }}</h2>

            {# --- Google --- #}
            {% if oauth.google.clientId %}
                <form id="oauth-google-form" method="post" action="/auth/oauth/google">
                    <input type="hidden" name="_csrf" value="{{ csrf_token }}">
                    <input type="hidden" name="idToken" value="">
                    {% if return %}<input type="hidden" name="return" value="{{ return }}">{% endif %}
                </form>

                <div id="g_id_onload"
                     data-client_id="{{ oauth.google.clientId }}"
                     data-context="signin"
                     data-ux_mode="popup"
                     data-callback="onGoogleCredential"
                     data-auto_prompt="false"></div>
                <div class="g_id_signin"
                     data-type="standard"
                     data-shape="rectangular"
                     data-theme="outline"
                     data-text="signin_with"
                     data-size="large"
                     data-logo_alignment="left"></div>

                <script>
                    function onGoogleCredential(response) {
                        var form = document.getElementById('oauth-google-form');
                        form.elements['idToken'].value = response.credential;
                        form.submit();
                    }
                </script>
            {% endif %}

            {# --- Apple --- #}
            {% if oauth.apple.clientId %}
                <form id="oauth-apple-form" method="post" action="/auth/oauth/apple">
                    <input type="hidden" name="_csrf" value="{{ csrf_token }}">
                    <input type="hidden" name="idToken" value="">
                    {% if return %}<input type="hidden" name="return" value="{{ return }}">{% endif %}
                </form>

                <div id="appleid-signin"
                     data-color="black"
                     data-border="true"
                     data-type="sign in"
                     data-width="240"
                     data-height="40"></div>

                <script>
                    document.addEventListener('DOMContentLoaded', function () {
                        if (typeof AppleID === 'undefined') { return; }
                        AppleID.auth.init({
                            clientId:    {{ oauth.apple.clientId|json_encode|raw }},
                            scope:       'name email',
                            redirectURI: {{ oauth.apple.redirectUri|json_encode|raw }},
                            usePopup:    true
                        });
                        document.addEventListener('AppleIDSignInOnSuccess', function (event) {
                            var idToken = event.detail && event.detail.authorization && event.detail.authorization.id_token;
                            if (!idToken) { return; }
                            var form = document.getElementById('oauth-apple-form');
                            form.elements['idToken'].value = idToken;
                            form.submit();
                        });
                    });
                </script>
            {% endif %}

            {# --- Facebook (classic web flow) --- #}
            {% if oauth.facebook.appId %}
                <form id="oauth-facebook-form" method="post" action="/auth/oauth/facebook">
                    <input type="hidden" name="_csrf" value="{{ csrf_token }}">
                    <input type="hidden" name="flow" value="classic">
                    <input type="hidden" name="accessToken" value="">
                    {% if return %}<input type="hidden" name="return" value="{{ return }}">{% endif %}
                </form>

                <button type="button" id="oauth-facebook-button">
                    {{ trans('pages.login.oauth.facebook') }}
                </button>

                <script>
                    window.fbAsyncInit = function () {
                        FB.init({
                            appId:   {{ oauth.facebook.appId|json_encode|raw }},
                            cookie:  true,
                            xfbml:   false,
                            version: 'v19.0'
                        });
                    };
                    (function (d, s, id) {
                        var js, fjs = d.getElementsByTagName(s)[0];
                        if (d.getElementById(id)) { return; }
                        js = d.createElement(s); js.id = id;
                        js.src = 'https://connect.facebook.net/en_US/sdk.js';
                        fjs.parentNode.insertBefore(js, fjs);
                    }(document, 'script', 'facebook-jssdk'));

                    document.getElementById('oauth-facebook-button').addEventListener('click', function () {
                        FB.login(function (response) {
                            if (response.status !== 'connected' || !response.authResponse) { return; }
                            var form = document.getElementById('oauth-facebook-form');
                            form.elements['accessToken'].value = response.authResponse.accessToken;
                            form.submit();
                        }, { scope: 'email,public_profile' });
                    });
                </script>
            {% endif %}
        </section>
    {% endif %}

    {% include 'partials/cookie-consent.twig' %}
</body>
</html>
