/**
 * Free version of the product metabox scripts.
 * Single-select texture modal, no Bulk Add feature.
 *
 * @package ProductCustomizer
 */
window.detectedMeshes = [];
window.dprcu_availableTextures = window.dprcu_availableTextures || [];

jQuery(document).ready(($) => {
    var $container = $('#steps-container');
    var activeTextureTarget = null; // {$option, stepId, optId}

    // --- INITIALIZE SORTABLE FOR STEPS ---
    function initStepsSortable() {
        $container.sortable({
            items: '.config-step',
            handle: '.step-drag-handle',
            placeholder: 'config-step sortable-placeholder',
            tolerance: 'pointer',
            cursor: 'grabbing',
            opacity: 0.9,
            revert: 150
        });
    }

    // --- INITIALIZE SORTABLE FOR OPTIONS ---
    function initOptionsSortable() {
        $('.options-list').sortable({
            items: '.option-card',
            handle: '.option-drag-handle',
            placeholder: 'option-card sortable-placeholder',
            tolerance: 'pointer',
            cursor: 'grabbing',
            opacity: 0.9,
            revert: 150,
            connectWith: '.options-list' // Allow dragging between steps
        });
    }

    // Initialize sortable on page load
    initStepsSortable();
    initOptionsSortable();

    // --- UPDATE DETECTED PARTS DISPLAY ---
    window.updateDetectedPartsDisplay = (meshNames) => {
        window.detectedMeshes = meshNames || [];
        var $list = $('#detected-parts-list').empty();

        if (!meshNames.length) {
            $list.html('<em>No meshes found in model.</em>');
            return;
        }

        meshNames.forEach((m) => {
            $list.append(`<span class="part-tag">${m}</span>`);
        });

        updateAllMeshSelectBoxes();
        updateAllMeshCheckboxes();
    };

    // --- UPDATE MESH SELECT BOXES (for step targets) ---
    function updateAllMeshSelectBoxes() {
        $('.mesh-select-box').each(function () {
            var $box = $(this);
            var selected = ($box.data('selected') || '').toString().split(',').filter((s) => s.trim());
            $box.empty();

            if (!window.detectedMeshes.length) {
                $box.html('<em>Load model first</em>');
                return;
            }

            window.detectedMeshes.forEach((m) => {
                var isSelected = selected.includes(m);
                var selClass = isSelected ? ' selected' : '';
                var checked = isSelected ? ' checked' : '';
                $box.append(
                    '<label class="mesh-checkbox' + selClass + '">' +
                    '<input type="checkbox" value="' + m + '"' + checked + '> ' + m +
                    '</label>'
                );
            });
        });
    }

    // --- UPDATE MESH CHECKBOXES (for show/hide) ---
    function updateAllMeshCheckboxes() {
        $('.mesh-checks').each(function () {
            var $box = $(this);
            var checked = ($box.data('checked') || '').toString().split(',').filter((s) => s.trim());
            $box.empty();

            if (!window.detectedMeshes.length) {
                $box.html('<em>-</em>');
                return;
            }

            window.detectedMeshes.forEach((m) => {
                var isChecked = checked.includes(m) ? ' checked' : '';
                $box.append(`<label><input type="checkbox" value="${m}"${isChecked}> ${m}</label>`);
            });
        });
    }

    // --- SYNC MESH SELECT BOX TO HIDDEN INPUT ---
    $container.on('change', '.mesh-select-box input[type="checkbox"]', function () {
        var $label = $(this).closest('.mesh-checkbox');
        var $box = $(this).closest('.mesh-select-box');
        var $input = $box.siblings('.targets-input');

        $label.toggleClass('selected', $(this).is(':checked'));

        var vals = [];
        $box.find('input:checked').each(function () {
            vals.push($(this).val());
        });
        $input.val(vals.join(','));
        $box.data('selected', vals.join(','));
    });

    // --- SYNC MESH CHECKS TO HIDDEN INPUT ---
    $container.on('change', '.mesh-checks input[type="checkbox"]', function () {
        var $box = $(this).closest('.mesh-checks');
        var $input = $box.siblings('input[type="hidden"]');
        var vals = [];
        $box.find('input:checked').each(function () {
            vals.push($(this).val());
        });
        $input.val(vals.join(','));
        $box.data('checked', vals.join(','));
    });

    // --- ADD STEP (via AJAX) ---
    $('#add-step-btn').click(() => {
        $('#empty-msg').remove();
        var stepId = `step_${Date.now()}`;
        $.post(dprcu_ajax.ajaxUrl, {
            action: 'dprcu_render_step',
            nonce: dprcu_ajax.nonce,
            step_id: stepId
        }, (response) => {
            if (response.success) {
                $container.append(response.data.html);
                updateAllMeshSelectBoxes();
                initStepsSortable();
                initOptionsSortable();
            } else {
                alert('Error adding step: ' + response.data);
            }
        }, 'json');
    });

    // --- REMOVE STEP ---
    $container.on('click', '.remove-step-btn', function () {
        if (confirm('Remove this step and all its options?')) {
            $(this).closest('.config-step').remove();
            if (!$container.find('.config-step').length) {
                $container.html('<div class="empty-message" id="empty-msg">No steps yet. Click "+ Add Step" to begin.</div>');
            }
        }
    });

    // --- ADD OPTION (via AJAX) ---
    $container.on('click', '.add-option-btn', function () {
        var $step = $(this).closest('.config-step');
        var stepId = $step.data('step-id');
        var optId = `opt_${Date.now()}`;
        $.post(dprcu_ajax.ajaxUrl, {
            action: 'dprcu_render_option',
            nonce: dprcu_ajax.nonce,
            step_id: stepId,
            opt_id: optId
        }, (response) => {
            if (response.success) {
                var $newOption = $(response.data.html);
                $step.find('.options-list').append($newOption);
                updateTexturePreview($newOption);
                updateAllMeshCheckboxes();
                initOptionsSortable();
            } else {
                alert('Error adding option: ' + response.data);
            }
        }, 'json');
    });

    // --- REMOVE OPTION ---
    $container.on('click', '.remove-option-btn', function () {
        $(this).closest('.option-card').remove();
    });

    // --- TEXTURE MODAL (Single-Select) ---
    var $modal = $('#tex-modal');
    var $grid = $('#tex-modal-grid');

    function texThumb(t) {
        return t.img
            ? `<img src="${t.img}">`
            : `<div class="modal-item-color" style="background:${t.color || '#ccc'};width:100%;height:70px;"></div>`;
    }

    // Helper to update texture preview from IDs
    function updateTexturePreview($option) {
        var $preview = $option.find('.texture-preview-multi');
        var $input = $option.find('.texture-ids-input');
        var ids = ($input.val() || '').split(',').filter(s => s.trim());
        var inner = '';

        $preview.empty();

        if (!ids.length) {
            $preview.html('<span class="no-texture">None (geometry only)</span>');
            return;
        }

        ids.forEach((id) => {
            var numId = parseInt(id, 10);
            var t = window.dprcu_availableTextures.find((x) => x.id === numId);
            if (t) {
                inner = t.img
                    ? `<img src="${t.img}" title="${t.name}">`
                    : `<div class="thumb-color-swatch" style="background:${t.color || '#ccc'};" title="${t.name}"></div>`;
                $preview.append(
                    `<div class="texture-thumb" data-id="${t.id}">` +
                    inner +
                    '<span class="remove-tex">&times;</span>' +
                    '</div>'
                );
            }
        });

        $preview.data('texture-ids', ids.join(','));
    }

    // Remove individual texture from option
    $container.on('click', '.remove-tex', function (e) {
        e.stopPropagation();
        var $thumb = $(this).closest('.texture-thumb');
        var $option = $(this).closest('.option-card');
        var $input = $option.find('.texture-ids-input');
        var removeId = $thumb.data('id').toString();

        var ids = ($input.val() || '').split(',').filter((s) => s.trim() && s !== removeId);
        $input.val(ids.join(','));

        updateTexturePreview($option);
    });

    // Open texture modal
    $container.on('click', '.choose-texture-btn', function () {
        var $option = $(this).closest('.option-card');
        var $step = $option.closest('.config-step');
        var $input = $option.find('.texture-ids-input');
        var currentIds = ($input.val() || '').split(',').filter((s) => s.trim());

        activeTextureTarget = {
            $option: $option,
            stepId: $step.data('step-id'),
            optId: $option.data('option-id')
        };

        function renderTexGrid(filterCatId) {
            var catId = filterCatId || '';
            $grid.empty();
            window.dprcu_availableTextures.forEach((t) => {
                if (catId && !t.categories.some((c) => c.id === catId)) return;
                var sel = currentIds.includes(t.id.toString()) ? ' selected' : '';
                $grid.append(
                    '<div class="modal-item' + sel + '" data-id="' + t.id + '" data-name="' + t.name + '" data-img="' + t.img + '">' +
                    texThumb(t) +
                    '<span>' + t.name + '</span>' +
                    '</div>'
                );
            });
        }
        renderTexGrid();
        $('#tex-modal-cat-filter').off('change.texfilter').on('change.texfilter', function () {
            renderTexGrid($(this).val());
            updateModalCount();
        });

        updateModalCount();
        $modal.css('display', 'flex');
    });

    // Single-select: clicking an item deselects all others first
    $grid.on('click', '.modal-item', function () {
        $grid.find('.modal-item.selected').not(this).removeClass('selected');
        $(this).toggleClass('selected');
        updateModalCount();
    });

    // Update selection count in modal
    function updateModalCount() {
        var count = $grid.find('.modal-item.selected').length;
        $('#tex-modal-count').text(`${count} selected`);
    }

    $('#tex-modal-cancel').click(() => {
        $modal.hide();
        activeTextureTarget = null;
    });

    // Select all in texture modal
    $('#tex-modal-select-all').click(() => {
        $grid.find('.modal-item').addClass('selected');
        updateModalCount();
    });

    // Select none in texture modal
    $('#tex-modal-select-none').click(() => {
        $grid.find('.modal-item').removeClass('selected');
        updateModalCount();
    });

    $('#tex-modal-select').click(() => {
        if (!activeTextureTarget) return;

        var $selected = $grid.find('.modal-item.selected');
        var $option = activeTextureTarget.$option;
        var $input = $option.find('.texture-ids-input');

        var ids = [];
        $selected.each(function () {
            ids.push($(this).data('id'));
        });

        $input.val(ids.join(','));
        updateTexturePreview($option);

        $modal.hide();
        activeTextureTarget = null;
    });

    // --- CLEAR ALL TEXTURES ---
    $container.on('click', '.clear-texture-btn', function () {
        var $option = $(this).closest('.option-card');
        $option.find('.texture-ids-input').val('');
        updateTexturePreview($option);
    });

    // --- MODEL UPLOAD ---
    var mediaFrame;
    $('#upload-model-button').click((e) => {
        e.preventDefault();
        if (mediaFrame) {
            mediaFrame.open();
            return;
        }
        mediaFrame = wp.media({
            title: 'Select 3D Model',
            button: { text: 'Use Model' },
            multiple: false
        });
        mediaFrame.on('select', () => {
            var att = mediaFrame.state().get('selection').first().toJSON();
            $('#_3d_model_url_field').val(att.url).trigger('change');
        });
        mediaFrame.open();
        });

    // Initialize texture previews on page load
    $('.option-card').each(function () {
        updateTexturePreview($(this));
    });

    // --- OPTION ICON IMAGE ---
    $container.on('click', '.choose-option-icon-btn', function () {
        const $option = $(this).closest('.option-card');
        const $input = $option.find('.option-icon-input');
        const $preview = $option.find('.icon-preview.option');
        const $clearBtn = $option.find('.clear-option-icon-btn');

        const frame = wp.media({
            title: 'Select Icon Image',
            button: { text: 'Use as Icon' },
            multiple: false
        });
        frame.on('select', () => {
            const att = frame.state().get('selection').first().toJSON();
            $input.val(att.url);
            $preview.attr('src', att.url);
            $clearBtn.show();
        });
        frame.open();
    });

    $container.on('click', '.clear-option-icon-btn', function () {
        const $option = $(this).closest('.option-card');
        const $input = $option.find('.option-icon-input');
        const $preview = $option.find('.icon-preview.option');
        $input.val('');
        $preview.attr('src', '');
        $(this).hide();
    });

    // --- STEP ICON IMAGE ---
    $container.on('click', '.choose-step-icon-btn', function () {
        const $step = $(this).closest('.config-step');
        const $input = $step.find('.step-icon-input');
        const $preview = $step.find('.icon-preview.step');
        const $clearBtn = $step.find('.clear-step-icon-btn');

        const frame = wp.media({
            title: 'Select Icon Image',
            button: { text: 'Use as Icon' },
            multiple: false
        });
        frame.on('select', () => {
            const att = frame.state().get('selection').first().toJSON();
            $input.val(att.url);
            $preview.attr('src', att.url);
            $clearBtn.show();
        });
        frame.open();
    });

    $container.on('click', '.clear-step-icon-btn', function () {
        const $step = $(this).closest('.config-step');
        const $input = $step.find('.step-icon-input');
        const $preview = $step.find('.icon-preview.step');
        $input.val('');
        $preview.attr('src', '');
        $(this).hide();
    });
});



jQuery(document).ready(($) => {
    // Toggle Step Collapse/Expand
    $(document).on('click', '.step-toggle-btn', function () {
        $(this).closest('.config-step').toggleClass('closed');
    });
    // Viewer-only mode toggle
    // When enabled, the steps area is irrelevant so hide it to avoid confusion.
    var $viewerToggle = $('#psc_viewer_only');
    var $stepsArea = $('#psc-steps-area');

    function applyViewerOnlyState() {
        $stepsArea.toggle(!$viewerToggle.is(':checked'));
    }

    $viewerToggle.on('change', applyViewerOnlyState);
    applyViewerOnlyState(); // Apply saved state on page load
});
