$(function () {
    $.ajax({
        url: "http://localhost:8080/inuhouse",
        type: "GET",
        success: function (dogs) {
            const $slider = $('#sliderContainer');
            const slideWidth = 270;
            const centerOffset = 1;


            preloadImages(dogs.map(d => d.image), () => {
                // $('#sliderContainer').html(dogs.map(createSlideHTML).join(''));
                const slidesHTML = generateCarouselHTML(dogs);
                $slider.html(slidesHTML);


                // const totalSlides = slides.length;
                // $slider.html(slidesHTML);
                const totalSlides = dogs.length + 2;

                let currentIndex = 1;

                animateTo(currentIndex);

                $('.right-btn').on('click', function () {
                    if ($slider.is(':animated')) return;

                    currentIndex++;
                    animateTo(currentIndex);

                    if (currentIndex === totalSlides - 1) {
                        // animateTo(currentIndex);
                        requestAnimationFrame(() => {
                            requestAnimationFrame(() => {
                                currentIndex = 1;
                                jumpTo(currentIndex);
                            });
                        });
                    }

                });


                $('.left-btn').on('click', function () {
                    if ($slider.is(':animated')) return;

                    currentIndex--;
                    animateTo(currentIndex);



                    if (currentIndex === 0) {
                        // animateTo(currentIndex);
                        requestAnimationFrame(() => {
                            requestAnimationFrame(() => {
                                currentIndex = totalSlides - 2;
                                jumpTo(currentIndex);
                            });
                        });
                    }

                });

            });


            $('#uploadBtn').on('click', function () {
                const fileInput = $('#fileInput')[0];
                const file = fileInput.files[0];
                if (!file) {
                    $('#uploadResult').html('ファイルを選択してください');
                    return;
                }

                const formData = new FormData();
                formData.append('file', file);

                $.ajax({
                    url: 'http://localhost:8080/upload',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function () {
                        $('#uploadResult').html('成功！');
                    },
                    error: function () {
                        $('#uploadResult').html('やり直してください！');
                    }
                });
            });


            $('#downloadBtn').on('click', function () {
                const fileUrl = 'http://localhost:8080/download-image';
                const a = document.createElement('a');
                a.href = fileUrl;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });


            $(function () {

                $('#goToLogin').on('click', function () {
                    $('#loginModal').fadeIn();
                });

                // $('#goToRegister').on('click', function () {
                //     $('#registerModal').fadeIn();
                // });


                $('#closeLoginModal, #cancelLogin').on('click', function () {
                    $('#loginModal').fadeOut();
                });

                // $('#closeRegisterModal, #cancelRegister').on('click', function () {
                //     $('#registerModal').fadeOut();
                // });


                // $('#submitRegister').on('click', function () {
                //     const username = $('#registerUsername').val().trim();
                //     const email = $('#registerEmail').val().trim();
                //     const password = $('#registerPassword').val().trim();
                //     const confirmPassword = $('#registerConfirmPassword').val().trim();

                //     if (!email || !password || !confirmPassword) {
                //         alert('必須項目をすべて入力してください');
                //         return;
                //     }

                //     if (password !== confirmPassword) {
                //         alert('パスワードが一致しません');
                //         return;
                //     }

                //     const requestData = {
                //         username: username || null,
                //         email: email,
                //         password: password
                //     };

                //     $.ajax({
                //         url: 'http://192.168.1.192:8085/api/user/register',
                //         type: 'POST',
                //         contentType: 'application/json',
                //         data: JSON.stringify(requestData),
                //         success: function () {
                //             alert('登録成功！');
                //             window.location.href = 'index.html'; 
                //             $('#registerModal').fadeOut();
                //         },
                //         error: function () {
                //             alert('登録に失敗しました: ');
                //         }
                //     });
                // });

                $('#submitLogin').on('click', function () {
                    const email = $('#loginEmail').val().trim();
                    const password = $('#loginPassword').val().trim();

                    if (!email || !password) {
                        alert('メールアドレスとパスワードを入力してください');
                        return;
                    }

                    const requestData = {
                        email: email,
                        password: password
                    };

                    $.ajax({
                        url: 'http://192.168.1.192:8085/api/user/login',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(requestData),
                        success: function (response) {
                            const token = response.token;
                            localStorage.setItem('authToken', token);
                            alert('ログイン成功！');
                            window.location.href = 'index.html'; 
                            $('#loginModal').fadeOut();
                        },
                        error: function () {
                            alert('ログインに失敗しました');
                        }
                    });
                });


            });




            function preloadImages(urls, callback) {
                let loaded = 0;
                urls.forEach(src => {
                    const img = new Image();
                    img.onload = () => {
                        loaded++;
                        if (loaded === urls.length) callback();
                    };
                    img.src = src;
                });
            }

            function createSlideHTML(dog) {
                return `
                    <div class="slide">
                        <div class="card flip-card">
                            <div class="flip-inner">
                                <div class="flip-front">
                                    <img src="${dog.image}" alt="${dog.name}" />
                                </div>
                                <div class="flip-back d-flex flex-column justify-content-center align-items-center text-white p-3">
                                    <h4>${dog.name}</h4>
                                    <p class="text-center">${dog.description}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }

            function generateCarouselHTML(dogList) {

                if (!dogList || dogList.length === 0) return '';

                const redundantList = [
                    dogList[dogList.length - 1],
                    ...dogList,
                    dogList[0]
                ];

                return redundantList.map(createSlideHTML).join('');
            }




            function animateTo(index) {
                const offset = slideWidth * (index - centerOffset);
                $slider.css({
                    transform: `translateX(-${offset}px)`,
                    transition: 'transform 0.5s ease'
                });
                updateScale(index);
            }

            function jumpTo(index) {
                const offset = slideWidth * (index - centerOffset);
                $slider.css({
                    transition: 'none',
                    transform: `translateX(-${offset}px)`
                });
                updateScale(index);
            }

            function updateScale(centerIndex) {
                $('#sliderContainer .slide .card').each(function (i) {
                    const scale = i === centerIndex ? 1.1 : 1;
                    $(this).css({
                        transform: `scale(${scale})`,
                        transition: 'transform 0.5s ease'
                    });
                });
            }

        },
        error: function () {
            console.error("犬データの取得に失敗しました。");
        }
    });
});
