$(function () {
    // CSRF setup
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
    });

    // Initialize Select2 for dropdowns with AJAX source
    $('.select2-ajax').each(function() {
        const $select = $(this);
        const source = $select.data('source');

        if (source) {
            $select.select2({
                placeholder: 'Select an option',
                allowClear: true,
                ajax: {
                    url: `/api/crm/${source}`,
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            search: params.term,
                            page: params.page || 1
                        };
                    },
                    processResults: function (data) {
                        return {
                            results: data.data.map(item => ({
                                id: item.id,
                                text: item.name || item.title || item.label
                            })),
                            pagination: {
                                more: data.current_page < data.last_page
                            }
                        };
                    },
                    cache: true
                }
            });
        } else {
            $select.select2({
                placeholder: 'Select an option',
                allowClear: true
            });
        }
    });

    // Form submission handler
    $('#crmCoreSettingsForm').on('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const data = {};

        // Convert FormData to object
        for (let [key, value] of formData.entries()) {
            data[key] = value;
        }

        // Handle checkboxes - convert to 0/1 for backend
        $('#crmCoreSettingsForm input[type="checkbox"]').each(function() {
            const name = $(this).attr('name');
            data[name] = $(this).is(':checked') ? 1 : 0;
        });

        // Submit via AJAX
        $.ajax({
            url: pageData.urls.update,
            method: 'POST',
            data: data,
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: pageData.labels.success,
                        text: response.message || pageData.labels.settingsUpdated,
                        timer: 2000,
                        showConfirmButton: false,
                        customClass: {
                            confirmButton: 'btn btn-success'
                        },
                        buttonsStyling: false
                    });
                }
            },
            error: function(xhr) {
                let message = pageData.labels.errorOccurred;

                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message = xhr.responseJSON.message;
                } else if (xhr.responseJSON && xhr.responseJSON.errors) {
                    message = Object.values(xhr.responseJSON.errors).flat().join('\n');
                }

                Swal.fire({
                    icon: 'error',
                    title: pageData.labels.error,
                    text: message,
                    customClass: {
                        confirmButton: 'btn btn-danger'
                    },
                    buttonsStyling: false
                });
            }
        });
    });

    // Reset form handler
    $('#crmCoreSettingsForm button[type="reset"]').on('click', function(e) {
        e.preventDefault();
        location.reload();
    });

    // Dynamic field visibility based on other fields
    function handleFieldDependencies() {
        // Show/hide webhook URL field based on webhook notifications toggle
        const webhookEnabled = $('#webhook_notifications').is(':checked');
        $('#webhook_url').closest('.col-md-6').toggle(webhookEnabled);

        // Show/hide task reminder hours based on task reminders toggle
        const taskRemindersEnabled = $('#enable_task_reminders').is(':checked');
        $('#task_reminder_hours').closest('.col-md-6').toggle(taskRemindersEnabled);

        // Show/hide API rate limit based on API access toggle
        const apiEnabled = $('#enable_api_access').is(':checked');
        $('#api_rate_limit').closest('.col-md-6').toggle(apiEnabled);
    }

    // Initial field dependency check
    handleFieldDependencies();

    // Handle field dependency changes
    $('#webhook_notifications, #enable_task_reminders, #enable_api_access').on('change', handleFieldDependencies);

    // Handle duplicate detection fields visibility
    $('#enable_contact_duplicate_detection').on('change', function() {
        const isEnabled = $(this).is(':checked');
        $('#duplicate_detection_fields').closest('.col-md-6').toggle(isEnabled);
    }).trigger('change');

    // Handle auto-generate code fields
    $('.form-check-input[id*="auto_generate"][id*="codes"]').each(function() {
        const $checkbox = $(this);
        const fieldName = $checkbox.attr('id');
        const prefix = fieldName.replace('auto_generate_', '').replace('_codes', '');

        $checkbox.on('change', function() {
            const isEnabled = $(this).is(':checked');
            $(`#${prefix}_code_prefix`).closest('.col-md-6').toggle(isEnabled);
            $(`#${prefix}_code_start_number`).closest('.col-md-6').toggle(isEnabled);
        }).trigger('change');
    });
});