(function ($, wp) {
    'use strict';

    wp.customize.controlConstructor['newsxo-hf-repeater'] =
        wp.customize.Control.extend({

            ready: function () {
                const control = this;
                const params = control.params;

                const $root = control.container.find('.newsxo-hf-repeater-control');
                const $list = $root.find('.newsxo-hf-repeater-list');
                const $input = $root.find('.newsxo-hf-repeater-value');

                let values = [];
                let originalDefaults = [];

                try {
                    values = JSON.parse(params.value) || [];
                } catch (e) { values = []; }

                try {
                    originalDefaults = JSON.parse(params.default_items) || [];
                } catch (e) { originalDefaults = []; }

                function updateInput() {
                    $input.val(JSON.stringify(values)).trigger('change');
                }

                function getTitle(val) {
                    return params.select_choices?.[val] || val || 'Item';
                }

                function toggleItem($item) {
                    $item.toggleClass('is-open');
                    $item.find('.newsxo-item-fields').slideToggle(150);
                }

                function getTargetId(selectValue) {
                    const sectionId = (params.element_sections || {})[selectValue];
                    const panelId = (params.element_panels || {})[selectValue];
                    return {
                        id: sectionId || panelId || null,
                        type: sectionId ? 'section' : (panelId ? 'panel' : null)
                    };
                }

                function navigateToTarget(target) {
                   if (!target.id) return;

                    if (target.type === 'section' && wp.customize.section(target.id)) {
                        wp.customize.section(target.id).focus();
                    } else if (target.type === 'panel' && wp.customize.panel(target.id)) {
                        wp.customize.panel(target.id).focus();
                    }
                }

                function renderItem(item, index) {
                    const uid = Date.now() + '_' + index;
                    const title = getTitle(item.select);
                    const target = getTargetId(item.select);
                    
                    // Handle "Add New" state
                    const isOpenClass = item._open ? 'is-open' : '';
                    const isOpenStyle = item._open ? 'style="display: block;"' : 'style="display: none;"';
                    delete item._open;

                    let html = `
                    <li class="newsxo-hf-repeater-item ${isOpenClass}" data-index="${index}">
                        <div class="newsxo-item-title">
                            <span>${title}</span>
                            <div class="newsxo-item-controls">
                                <button type="button" class="newsxo-reset-item" title="Reset to Default">&#x21ba;</button>
                                <button type="button" class="newsxo-remove">&times;</button>
                            </div>
                        </div>
                        <div class="newsxo-item-fields" ${isOpenStyle}>`;

                    /* SELECT FIELD */
                    if (params.fields.select) {
                        html += `<div class="newsxo-field-wrapper"><label class="newsxo-field-label">${params.select_label}</label><select class="newsxo-field-select">`;
                        $.each(params.select_choices, (key, label) => {
                            const isSelected = item.select === key ? 'selected' : '';
                            const isDisabled = (params.disabled_choices || []).includes(key) ? 'disabled' : '';
                            html += `<option value="${key}" ${isSelected} ${isDisabled}>${label}</option>`;
                        });
                        html += `</select></div>`;
                    }

                    /* COLUMN RANGE & NUMBER */
                    if (params.fields.column) {
                        const colVal = item.column;
                        html += `
                        <div class="newsxo-field-wrapper newsxo-column-sync-wrapper">
                            <div class="newsxo-label-row">
                                <label class="newsxo-field-label">${params.column_label}</label>
                                <div class="newsxo-number-input-wrap">
                                    <input type="number" class="newsxo-field-column-number" min="1" max="100" step="0.01" lang="en" value="${colVal}">
                                </div>
                            </div>
                            <div class="newsxo-field-range">
                                <input type="range" class="newsxo-field-column-range" min="1" max="100" step="0.01" value="${colVal}">
                            </div>
                        </div>`;
                    }

                    /* POSITION RADIOS */
                    if (params.fields.position) {
                        html += `
                        <div class="newsxo-field-wrapper">
                            <label class="newsxo-field-label">${params.position_label}</label>
                            <div class="newsxo-field-position">
                                <label><input type="radio" name="pos_${uid}" value="left" ${item.position === 'left' ? 'checked' : ''}>Left</label>
                                <label><input type="radio" name="pos_${uid}" value="center" ${item.position === 'center' ? 'checked' : ''}>Center</label>
                                <label><input type="radio" name="pos_${uid}" value="right" ${item.position === 'right' ? 'checked' : ''}>Right</label>
                            </div>
                        </div>`;
                    }

                    /* EDIT BUTTON */
                    if (target.id) {
                        html += `
                        <div class="newsxo-field-wrapper"><button type="button" class="button newsxo-edit-element" data-target-id="${target.id}" data-target-type="${target.type}">
                            <span class="dashicons dashicons-edit"></span> ${params.edit_button_text || 'Edit'}
                        </button></div>`;
                    }

                    html += `</div></li>`;
                    const $item = $(html);

                    /* EVENTS */
                    $item.find('.newsxo-item-title span').on('click', () => toggleItem($item));
                    
                    $item.find('.newsxo-remove').on('click', () => {
                        values.splice(index, 1);
                        renderAll();
                    });

                    $item.find('.newsxo-field-column-range, .newsxo-field-column-number').on('input', function() {
                        let inputVal = $(this).val();
                        
                        if (inputVal.endsWith('.')) {
                            return;
                        }

                        let val = parseFloat(inputVal);

                        if (isNaN(val)) return;

                        if (val > 100) val = 100;
                        if (val < 1) val = 1;

                        if ($(this).hasClass('newsxo-field-column-range')) {
                            $item.find('.newsxo-field-column-number').val(val);
                        } else {
                            $item.find('.newsxo-field-column-range').val(val);
                        }

                        values[index].column = val;
                        updateInput();
                    });

                    $item.find('.newsxo-field-column-number').on('blur', function() {
                        let val = parseFloat($(this).val());
                        if (isNaN(val) || val < 1) val = 1;
                        if (val > 100) val = 100;
                        
                        val = Math.round(val * 100) / 100;
                        $(this).val(val);
                        $item.find('.newsxo-field-column-range').val(val);
                        
                        values[index].column = val;
                        updateInput();
                    });

                    $item.find('.newsxo-field-select').on('change', function() {
                        values[index].select = this.value;
                        renderAll();
                    });

                    $item.find('input[type="radio"]').on('change', function() {
                        if (this.name.startsWith('pos_')) values[index].position = this.value;
                        updateInput();
                    });

                    $item.find('.newsxo-edit-element').on('click', function() {
                        const clickedTarget = {
                            id: $(this).data('target-id'),
                            type: $(this).data('target-type')
                        };
                        navigateToTarget(clickedTarget);
                    });

                    $item.find('.newsxo-reset-item').on('click', function (e) {

                        e.preventDefault();
                        e.stopPropagation();
                        if (originalDefaults[index]) {
                            values[index] = $.extend(true, {}, originalDefaults[index]);
                            renderAll();
                        }
                    });

                    return $item;
                }

                function renderAll() {
                    $list.empty();
                    values.forEach((item, i) => $list.append(renderItem(item, i)));
                    updateInput();
                }

                $root.find('.newsxo-add-item').on('click', function () {
                    const newItem = $.extend(true, {}, originalDefaults[0] || {});
                    newItem._open = true;
                    values.push(newItem);
                    renderAll();
                    $list.animate({ scrollTop: $list.prop("scrollHeight") }, 500);
                });

                $list.sortable({
                    handle: '.newsxo-item-title',
                    update: function () {
                        const sorted = [];
                        $list.find('.newsxo-hf-repeater-item').each(function () {
                            sorted.push(values[$(this).data('index')]);
                        });
                        values = sorted;
                        renderAll();
                    }
                });

                renderAll();
            }
        });

})(jQuery, wp);