jQuery(document).ready(function ($) {

    // --- Initialize WordPress Color Picker ---
    $('.sifency-color-picker').wpColorPicker();

    // --- Slider (Range Input) Logic ---
    function initSliders() {
        $('.sifency-slider-input').each(function () {
            var slider = $(this);
            var value_display = slider.siblings('.sifency-slider-value');
            value_display.text(slider.val());
        });
    }
    initSliders(); // Initialize sliders on page load
    $('body').on('input change', '.sifency-slider-input', function () {
        $(this).siblings('.sifency-slider-value').text($(this).val());
    });

    // --- Media Uploader (Images) ---
    $('body').on('click', '.sifency-media-upload', function (e) {
        e.preventDefault();
        var button = $(this);
        var input = button.siblings('.sifency-media-input');
        var preview = button.siblings('.sifency-media-preview');
        var frame = wp.media({ title: 'Select or Upload Media', button: { text: 'Use this media' }, multiple: false });
        frame.on('select', function () {
            var attachment = frame.state().get('selection').first().toJSON();
            input.val(attachment.id);
            var previewUrl = attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
            preview.html('<img src="' + previewUrl + '" style="max-width:150px; height:auto;" />');
        });
        frame.open();
    });
    $('body').on('click', '.sifency-media-remove', function (e) {
        e.preventDefault();
        $(this).siblings('.sifency-media-input').val('');
        $(this).siblings('.sifency-media-preview').html('');
    });

    // --- Generic File Upload ---
    $('body').on('click', '.sifency-upload-add', function (e) {
        e.preventDefault();
        var button = $(this);
        var input = button.siblings('.sifency-upload-input');
        var filename_display = button.siblings('.sifency-upload-filename');
        var frame = wp.media({ title: 'Select or Upload File', button: { text: 'Use this file' }, multiple: false });
        frame.on('select', function () {
            var attachment = frame.state().get('selection').first().toJSON();
            input.val(attachment.id);
            filename_display.text(attachment.filename).show();
            button.siblings('.sifency-upload-remove').show();
        });
        frame.open();
    });
    $('body').on('click', '.sifency-upload-remove', function (e) {
        e.preventDefault();
        var button = $(this);
        button.siblings('.sifency-upload-input').val('');
        button.siblings('.sifency-upload-filename').text('').hide();
        button.hide();
    });

    // --- Repeater Field ---
    $('.sifency-repeater-items').sortable({ handle: '.sifency-repeater-handle', placeholder: 'repeater-placeholder', forcePlaceholderSize: true });
    $('body').on('click', '.sifency-repeater-add', function (e) {
        e.preventDefault();
        var container = $(this).prev('.sifency-repeater-items');
        var template = $('#' + container.data('template-id')).html();
        var newIndex = container.find('.sifency-repeater-row').length;
        template = template.replace(/__i__/g, newIndex);
        container.append(template);
        // Re-initialize sliders and color pickers for the new row
        setTimeout(function() {
            initSliders();
            container.find('.sifency-color-picker').wpColorPicker();
        }, 100);
    });
    $('body').on('click', '.sifency-repeater-remove', function (e) {
        e.preventDefault();
        $(this).closest('.sifency-repeater-row').remove();
    });
    
    // --- Dependency/Conditional Logic ---
    function checkDependencies() {
        $('[data-dependency-controller]').each(function () {
            var dependent = $(this);
            var controller_id = dependent.data('dependency-controller');
            var operator = dependent.data('dependency-operator');
            var required_val = String(dependent.data('dependency-value'));
            var controller = $('[name="' + controller_id + '"]');
            var controller_val = '';
            if (controller.is(':radio')) {
                controller_val = $('[name="' + controller_id + '"]:checked').val();
            } else {
                controller_val = controller.val();
            }
            var condition_met = (operator === '==') ? (controller_val === required_val) : (controller_val !== required_val);
            if (condition_met) {
                dependent.slideDown();
            } else {
                dependent.slideUp();
            }
        });
    }
    checkDependencies(); // Check on page load
    $('.sifency-metabox-wrapper').on('change', 'input, select', checkDependencies);
});