{#
    Shared JavaScript for Wisebee settings forms

    Variables:
    - idPrefix: string prefix for element IDs (e.g., 'wizard_' or 'rs_')
    - uploadUrl: URL for logo upload endpoint
    - errorElementId: ID of error display element (optional)
#}

{% set idPrefix = idPrefix|default('') %}
{% set uploadUrl = uploadUrl|default('/admin/wisebee/setup/upload-logo') %}
{% set errorElementId = errorElementId|default('') %}

<script>
    // Logo upload function
    function wisebeeUploadLogo(prefix) {
        var fileInput = document.getElementById(prefix + 'logo_file');
        var errorEl = document.getElementById('{{ errorElementId }}');

        if (!fileInput.files.length) {
            if (errorEl) {
                errorEl.textContent = 'Please select a file first.';
                errorEl.style.display = 'block';
            } else {
                alert('Please select a file first.');
            }
            return;
        }

        var formData = new FormData();
        formData.append('file', fileInput.files[0]);

        var btn = document.getElementById(prefix + 'upload_logo_btn');
        btn.disabled = true;
        btn.textContent = 'Uploading...';

        fetch('{{ uploadUrl }}', {
            method: 'POST',
            headers: {
                'Accept': 'application/json'
            },
            body: formData
        })
        .then(function(response) {
            if (!response.ok) throw new Error('Upload failed (HTTP ' + response.status + ')');
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                throw new Error('Unexpected response from server');
            }
            return response.json();
        })
        .then(function(result) {
            btn.disabled = false;
            btn.textContent = 'Upload Logo';

            if (result.success) {
                var preview = document.getElementById(prefix + 'logo_preview');
                preview.innerHTML = '';
                if (result.url) {
                    var img = document.createElement('img');
                    img.src = result.url;
                    preview.appendChild(img);
                } else {
                    var span = document.createElement('span');
                    span.style.color = '#27ae60';
                    span.textContent = 'Logo uploaded successfully.';
                    preview.appendChild(span);
                }
                if (errorEl) errorEl.style.display = 'none';
            } else {
                if (errorEl) {
                    errorEl.textContent = result.error || 'Failed to upload logo';
                    errorEl.style.display = 'block';
                } else {
                    alert(result.error || 'Failed to upload logo');
                }
            }
        })
        .catch(function(err) {
            btn.disabled = false;
            btn.textContent = 'Upload Logo';
            if (errorEl) {
                errorEl.textContent = 'Connection error: ' + err.message;
                errorEl.style.display = 'block';
            } else {
                alert('Connection error: ' + err.message);
            }
        });
    }

    // Color picker initialization function
    function wisebeeInitColorPickers(prefix) {
        if (typeof jQuery !== 'undefined' && jQuery.fn.ColorPicker) {
            var $primaryInput = $('#' + prefix + 'widget_primary_color');
            var $secondaryInput = $('#' + prefix + 'widget_secondary_color');

            if ($primaryInput.length) {
                $primaryInput.ColorPicker({
                    onChange: function(hsb, hex, rgb) {
                        $primaryInput.val('#' + hex);
                        $('#' + prefix + 'preview_primary').css('background', '#' + hex);
                    },
                    onSubmit: function(hsb, hex, rgb, el) {
                        $(el).val('#' + hex);
                        $('#' + prefix + 'preview_primary').css('background', '#' + hex);
                        $(el).ColorPickerHide();
                    },
                    onBeforeShow: function() {
                        $(this).ColorPickerSetColor(this.value.replace('#', ''));
                    }
                });

                $primaryInput.on('change keyup', function() {
                    $('#' + prefix + 'preview_primary').css('background', $(this).val());
                });
            }

            if ($secondaryInput.length) {
                $secondaryInput.ColorPicker({
                    onChange: function(hsb, hex, rgb) {
                        $secondaryInput.val('#' + hex);
                        $('#' + prefix + 'preview_secondary').css('background', '#' + hex);
                    },
                    onSubmit: function(hsb, hex, rgb, el) {
                        $(el).val('#' + hex);
                        $('#' + prefix + 'preview_secondary').css('background', '#' + hex);
                        $(el).ColorPickerHide();
                    },
                    onBeforeShow: function() {
                        $(this).ColorPickerSetColor(this.value.replace('#', ''));
                    }
                });

                $secondaryInput.on('change keyup', function() {
                    $('#' + prefix + 'preview_secondary').css('background', $(this).val());
                });
            }
        }
    }
</script>
