@php
    $side_content_row_i = (isset($langCode) && isset($service->side_content[$langCode]['list'])) ? count($service->side_content[$langCode]['list'])+1 : 1; // Initialize field count
    $faq_content_row_i = (isset($langCode) && isset($service->faq_content[$langCode]['list'])) ? count($service->faq_content[$langCode]['list'])+1 : 1; // Initialize field count
@endphp
<script>
    $(document).ready(function () {
        'use strict';
        let side_content_row_i = @json($side_content_row_i); // Initialize field count
        let faq_content_row_i = @json($faq_content_row_i); // Initialize field count

        console.log(side_content_row_i);

        const serviceName = $('.service-name');
        const serviceSlug = $('.service-slug');

        // Cache selectors
        let sideContentContainer = $('#append-side-content-' + '{{ config('app.fallback_locale') }}');
        let faqContentContainer = $('#append-faq-content-' + '{{ config('app.fallback_locale') }}');
        $('.lang-tab').on('click', function () {
            const lang = $(this).data('lang');
            sideContentContainer = $('#append-side-content-' + lang);
            faqContentContainer = $('#append-faq-content-' + lang);
        });



        // Slug Auto Generate
        serviceName.on('input', function () {
            serviceSlug.val($(this).val().trim().replace(/\s+/g, '-').toLowerCase());
        });

        // Function to add new content row
        function addNewRow(container, template) {
            container.append(template).hide().fadeIn(300);
        }

        // Add Side Content Row
        $('.add-new-side-content').on('click', function () {
            let newSideContentRow = `@include('backend.services.partials.side-content-row', ['key' => $side_content_row_key ?? '${side_content_row_i}'])`;
            addNewRow(sideContentContainer, newSideContentRow);
            side_content_row_i++;
        });

        // Add FAQ Content Row
        $('.add-new-faq-content').on('click', function () {
            let newFaqContentRow = `@include('backend.services.partials.faq-content-row', ['key' => $faq_content_row_key ?? '${faq_content_row_i}'])`;
            addNewRow(faqContentContainer, newFaqContentRow);
            faq_content_row_i++;
        });

        // Handle dynamic delete for both side and FAQ content using event delegation
        $(document).on('click', '.delete-field, .delete-faq-field', function () {
            $(this).closest('tr').fadeOut(300, function () {
                $(this).remove();
            });
        });
    });

</script>
