$(document).ready(function() {
    $('img').css('z-index', '');
    datalist = {};
    var isSubmitting = false;
    
    // Form submit işlemi
    $('form').on('submit', function(e) {
        e.preventDefault();
        if (isSubmitting) return;
        isSubmitting = true;

        var formData = new FormData(this);
        var featuresData = {};

        // Bu alanlar haricindekileri featuresData içine ekleyelim
        var excludeKeys = ['csrf_token', 'model', 'title'];

        for (var pair of formData.entries()) {
            var key = pair[0];
            var value = pair[1];

            if (excludeKeys.includes(key)) {
                console.log(key + ': ' + value);  // Haric tutulan verileri doğrudan göster
            } else {
                featuresData[key] = value;  // Diğer verileri featuresData içine ekle
            }
        }

        // JSON formatına çeviriyoruz
        var featuresDataJson = JSON.stringify(featuresData);
        console.log('featuresData:', featuresDataJson);

        // Yeni bir FormData oluşturup gerekli verileri ekleyelim
        var newFormData = new FormData();
        newFormData.append('csrf_token_fronted', formData.get('csrf_token_fronted'));
        newFormData.append('model', formData.get('model'));
        newFormData.append('title', formData.get('title'));
        newFormData.append('features', featuresDataJson);  // JSON formatındaki featuresData'yı ekle

        $.ajax({
            url: window.location.origin + '/panel/public-store',
            type: 'POST',
            data: newFormData,
            processData: false,  // FormData'nın otomatik olarak işlenmesini engelle
            contentType: false,  // FormData ile çalışırken contentType otomatik ayarlanır
            success: function(response) {
                console.log('Form gönderildi:', response);
            },
            error: function(xhr, status, error) {
                console.error('Bir hata oluştu:', error);
            },
            complete: function() {
                isSubmitting = false;
            }
        });
    });

    // Component tabs yapısı - Tüm component'leri tek yerden yönet
    var componentTabs = {
        // Brands component
        brands: function($element) {
            $.ajax({
                url: window.location.origin + '/panel/ajax',
                type: 'POST',
                data: { 'action': 'brands' },
                success: function (data) {
                    $element.html(data);
                    var brand = $element.find('.brand-active');
                    brand.slick({
                        dots: false,
                        infinite: true,
                        speed: 1000,
                        autoplay: true,
                        arrows: false,
                        slidesToShow: 5,
                        slidesToScroll: 1,
                        responsive: [
                            { breakpoint: 1200, settings: { slidesToShow: 5, slidesToScroll: 1, infinite: true } },
                            { breakpoint: 992, settings: { slidesToShow: 4, slidesToScroll: 1 } },
                            { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 1, arrows: false } },
                            { breakpoint: 575, settings: { slidesToShow: 2, slidesToScroll: 1, arrows: false } }
                        ]
                    });
                }
            });
        },

        // Menu component
        menu: function($element) {
            var id = $element.data('id');
            if (id) {
                $.ajax({
                    url: window.location.origin + '/panel/ajax',
                    type: 'POST',
                    dataType: 'json',
                    data: { 'data': id, 'action': 'menus' },
                    success: function (data) {
                        $element.html(data);
                    }
                });
            } else {
                $element.html('<p style="margin-left: 50px;">Lütfen Menu Seçiniz</p>');
            }
        },

        // Sliders component
        sliders: function($element) {
            var id = $element.data('id');
            if (id) {
                $.ajax({
                    url: window.location.origin + '/panel/ajax',
                    type: 'POST',
                    dataType: 'json',
                    data: { 'data': id, 'action': 'sliders' },
                    success: function (data) {
                        $element.html(data);
                        var sliders = $element.find('.slider-active');
                        sliders.slick({
                            autoplay: true,
                            speed: 1000,
                            dots: false,
                            fade: true,
                            arrows: false,
                            responsive: [{ breakpoint: 767, settings: { dots: false, arrows: false } }]
                        });
                    }
                });
            } else {
                $element.html('<p style="margin-left: 50px;">Lütfen Slider Seçiniz</p>');
            }
        },

        // Services component
        services: function($element) {
            var datalist = {
                source: $element.data('v-source'),
                ids: $element.data('v-service_id'),
                limit: $element.data('v-limit'),
                order: $element.data('v-order_by'),
                direction: $element.data('v-direction'),
                module: $element.data('v-module'),
                style: $element.data('v-style')
            };

            $.ajax({
                url: window.location.origin + '/panel/autocompleteAjax',
                type: 'POST',
                dataType: 'json',
                data: { 'data': datalist, 'action': datalist['module'] },
                success: function (data) {
                    $element.html(data);
                }
            });
        },

        // Testimonials component
        testimonials: function($element) {
            var datalist = {
                source: $element.data('v-source'),
                ids: $element.data('v-service_id'),
                limit: $element.data('v-limit'),
                order: $element.data('v-order_by'),
                direction: $element.data('v-direction'),
                module: $element.data('v-module'),
                style: $element.data('v-style')
            };

            $.ajax({
                url: window.location.origin + '/panel/autocompleteAjax',
                type: 'POST',
                dataType: 'json',
                data: { 'data': datalist, 'action': datalist['module'] },
                success: function (data) {
                    $element.html(data);
                    var testimonial = $element.find('.testimonial-active-two');
                    testimonial.slick({
                        dots: false,
                        infinite: true,
                        speed: 1000,
                        autoplay: true,
                        arrows: true,
                        prevArrow: '<button type="button" class="slick-prev"><i class="flaticon-right-arrow"></i></button>',
                        nextArrow: '<button type="button" class="slick-next"><i class="flaticon-right-arrow"></i></button>',
                        appendArrows: ".testimonial-nav-two",
                        slidesToShow: 2,
                        slidesToScroll: 1,
                        responsive: [
                            { breakpoint: 1200, settings: { slidesToShow: 2, slidesToScroll: 1, infinite: true } },
                            { breakpoint: 992, settings: { slidesToShow: 1, slidesToScroll: 1 } },
                            { breakpoint: 767, settings: { slidesToShow: 1, slidesToScroll: 1 } },
                            { breakpoint: 575, settings: { slidesToShow: 1, slidesToScroll: 1 } }
                        ]
                    });
                }
            });
        },

        // Posts component
        posts: function($element) {
            var datalist = {
                source: $element.data('v-source'),
                ids: $element.data('v-service_id'),
                limit: $element.data('v-limit'),
                order: $element.data('v-order_by'),
                direction: $element.data('v-direction'),
                module: $element.data('v-module'),
                style: $element.data('v-style'),
                category_id: $element.data('v-category')
            };

            $.ajax({
                url: window.location.origin + '/panel/autocompleteAjax',
                type: 'POST',
                dataType: 'json',
                data: { 'data': datalist, 'action': datalist['module'] },
                success: function(data) {
                    $element.html(data);
                },
                error: function(xhr, status, error) {
                    console.error('Bir hata oluştu:', error);
                }
            });
        },

        // Projects component
        projects: function($element) {
            var datalist = {
                source: $element.data('v-source'),
                ids: $element.data('v-service_id'),
                limit: $element.data('v-limit'),
                order: $element.data('v-order_by'),
                direction: $element.data('v-direction'),
                module: $element.data('v-module'),
                style: $element.data('v-style'),
                category_id: $element.data('v-category')
            };

            $.ajax({
                url: window.location.origin + '/panel/autocompleteAjax',
                type: 'POST',
                dataType: 'json',
                data: { 'data': datalist, 'action': datalist['module'] },
                success: function(data) {
                    $element.html(data);
                },
                error: function(xhr, status, error) {
                    console.error('Bir hata oluştu:', error);
                }
            });
        }
    };

    // Component'leri çalıştır
    $('[data-component-brands]').each(function() {
        componentTabs.brands($(this));
    });

    $('[data-component-menu]').each(function() {
        componentTabs.menu($(this));
    });

    $('[data-component-sliders]').each(function() {
        componentTabs.sliders($(this));
    });

    $('[data-component-services]').each(function() {
        componentTabs.services($(this));
    });

    $('[data-component-testimonials]').each(function() {
        componentTabs.testimonials($(this));
    });

    $('[data-component-posts]').each(function() {
        componentTabs.posts($(this));
    });

    $('[data-component-projects]').each(function() {
        componentTabs.projects($(this));
    });

    // Yeni component eklemek için kolay yöntem
    // Örnek: $('[data-component-yeni-component]').each(function() { componentTabs.yeniComponent($(this)); });

});