@extends('layouts.landing', ['title' => 'Account - Sign In'])

@section('content')
    <main class="content-wrapper w-100 px-3 ps-lg-5 pe-lg-4 mx-auto" style="max-width: 1920px">
        <div class="d-lg-flex">
            <!-- Login form + Footer -->
            <div class="d-flex flex-column min-vh-100 w-100 py-4 mx-auto me-lg-5" style="max-width: 416px">
                <!-- Logo -->
                <header class="navbar px-0 pb-4 mt-n2 mt-sm-0 mb-2 mb-md-3 mb-lg-4">
                    <a class="navbar-brand pt-0" href="/">
                        <span class="d-flex flex-shrink-0 text-primary me-2">
                            <img src="{{ asset('logo/logo-colored.png') }}" alt="AsiaGolf Logo"
                                style="height: 36px; width: auto;">
                        </span>
                    </a>
                </header>
                <h1 class="h2 mt-auto">Welcome back</h1>
                <div class="nav fs-sm mb-4">
                    Don't have an account?
                    <a class="nav-link text-decoration-underline p-0 ms-2"
                        href="{{ route('register') }}">Create an account</a>
                </div>

                {{-- show error message --}}
                @if (session('error'))
                    <div class="alert alert-danger">{{ session('error') }}</div>
                @endif

                {{-- show error message --}}
                <div id="error-message" class="alert alert-danger d-none"></div>

                <!-- Form -->
                <form class="needs-validation" id="loginForm" novalidate="">
                    <div class="position-relative mb-4">
                        <input class="form-control form-control-lg"
                            placeholder="{{ $type == 'email' ? __('signin.email_placeholder') : __('signin.phone_placeholder') }}"
                            required="" name="identity" id="identity" min="1"
                            type="{{ $type == 'email' ? 'email' : 'number' }}" />
                        <div class="invalid-tooltip bg-transparent py-0">
                            {{ $type == 'email' ? __('signin.email_invalid') : __('signin.phone_invalid') }}</div>
                    </div>

                    <div class="d-flex align-items-center justify-content-end mb-4">
                        {{-- <div class="form-check me-2">
                            <input class="form-check-input" id="remember-30" type="checkbox" />
                            <label class="form-check-label" for="remember-30">{{ __('signin.remember_for_30_days') }}</label>
                        </div> --}}
                        <div class="nav">
                            <a class="nav-link animate-underline p-0"
                                href="{{ $type == 'email' ? route('login') : route('login-email') }}">
                                <span
                                    class="animate-target">{{ $type == 'email' ? __('signin.login_with_phone') : __('signin.login_with_email') }}</span>
                            </a>
                        </div>
                    </div>
                    <button class="btn btn-lg btn-primary w-100" type="submit">{{ __('signin.sign_in') }}</button>
                </form>
                <x-social-login />
                <!-- Footer -->
                <footer class="mt-auto">
                    {{-- <div class="nav mb-4">
                        <a class="nav-link text-decoration-underline p-0"
                            href="{{ route('second', ['help', 'topics-v1']) }}">Need help?</a>
                    </div>
                    <p class="fs-xs mb-0">
                        © All rights reserved. Made by <span class="animate-underline"><a
                                class="animate-target text-dark-emphasis text-decoration-none"
                                href="https://coderthemes.com/" rel="noreferrer" target="_blank">Coderthemes</a></span>
                    </p> --}}
                </footer>
            </div>
            <!-- Cover image visible on screens > 992px wide (lg breakpoint) -->
            <div class="d-none d-lg-block w-100 py-4 ms-auto" style="max-width: 1034px">
                <div class="d-flex flex-column justify-content-end h-100 rounded-5 overflow-hidden">
                    <span class="position-absolute top-0 start-0 w-100 h-100 d-none-dark"
                        style="background: linear-gradient(-90deg, #accbee 0%, #e7f0fd 100%)"></span>
                    <span class="position-absolute top-0 start-0 w-100 h-100 d-none d-block-dark"
                        style="background: linear-gradient(-90deg, #1b273a 0%, #1f2632 100%)"></span>
                    <div class="ratio position-relative z-2" style="--cz-aspect-ratio: calc(1030 / 1032 * 100%)">
                        <img alt="Girl" src="/img/account/cover.png" />
                    </div>
                </div>
            </div>
        </div>
    </main>
@endsection

@section('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const loginForm = document.getElementById('loginForm');
            const submitBtn = loginForm.querySelector('button[type="submit"]');
            const identityInput = document.getElementById('identity');
            const passwordInput = document.getElementById('password');

            // Hide error message when user starts typing
            identityInput.addEventListener('input', function() {
                const errorDiv = document.getElementById('error-message');
                errorDiv.classList.add('d-none');
            });

            // Hide error message when password field is typed
            if (passwordInput) {
                passwordInput.addEventListener('input', function() {
                    const errorDiv = document.getElementById('error-message');
                    errorDiv.classList.add('d-none');
                });
            }

            loginForm.addEventListener('submit', function(e) {
                e.preventDefault();

                // Hide error message when submitting
                const errorDiv = document.getElementById('error-message');
                errorDiv.classList.add('d-none');

                // Reset validation
                loginForm.classList.remove('was-validated');

                // Basic validation
                if (!identityInput.value.trim()) {
                    loginForm.classList.add('was-validated');
                    return;
                }

                if (passwordInput && !passwordInput.value.trim()) {
                    loginForm.classList.add('was-validated');
                    return;
                }

                // Show loading state
                submitBtn.disabled = true;
                submitBtn.innerHTML =
                    '<span class="spinner-border spinner-border-sm me-2"></span>{{ __('signin.sending') }}';

                // Determine form type based on current route
                const isPhoneLogin = '{{ $type }}' === 'phone';

                if (isPhoneLogin) {
                    // Send OTP request for phone login
                    fetch('{{ route('login-phone.otp') }}', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            },
                            body: JSON.stringify({
                                identity: identityInput.value.trim()
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // Redirect to OTP verification page
                                window.location.href = data.redirect;
                            } else {
                                // Show error in error message div
                                const errorDiv = document.getElementById('error-message');
                                errorDiv.textContent = data.message || '{{ __('signin.error') }}';
                                errorDiv.classList.remove('d-none');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            const errorDiv = document.getElementById('error-message');
                            errorDiv.textContent = '{{ __('signin.error') }}';
                            errorDiv.classList.remove('d-none');
                        })
                        .finally(() => {
                            // Reset button state
                            submitBtn.disabled = false;
                            submitBtn.textContent = '{{ __('signin.sign_in') }}';
                        });
                } else {

                    fetch('{{ route('login-email.otp') }}', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            },
                            body: JSON.stringify({
                                identity: identityInput.value.trim(),
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // Redirect to home page
                                window.location.href = data.redirect;
                            } else {
                                // Show error in error message div
                                const errorDiv = document.getElementById('error-message');
                                errorDiv.textContent = data.message || '{{ __('signin.error') }}';
                                errorDiv.classList.remove('d-none');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            const errorDiv = document.getElementById('error-message');
                            errorDiv.textContent = '{{ __('signin.error') }}';
                            errorDiv.classList.remove('d-none');
                        })
                        .finally(() => {
                            // Reset button state
                            submitBtn.disabled = false;
                            submitBtn.textContent = '{{ __('signin.sign_in') }}';
                        });
                }
            });
        });
    </script>
@endsection
