// Workflow Page JavaScript
(function() {
    'use strict';
    
    // Wait for jQuery to be available
    function initWorkflowPage() {
        if (typeof jQuery === 'undefined') {
            setTimeout(initWorkflowPage, 100);
            return;
        }
        
        jQuery(document).ready(function($) {
            const $workflowSteps = $('#kdsamref-workflow-steps');
            
            if ($workflowSteps.length) {
                $workflowSteps.sortable({
                    handle: '.kdsamref-step-drag-handle',
                    placeholder: 'sortable-placeholder',
                    items: '.kdsamref-workflow-step:not(.kdsamref-workflow-step:first-child, .kdsamref-workflow-step:last-child)',
                    update: function(event, ui) {
                        // Update step numbers after drag
                        updateStepNumbers();
                    },
                    start: function(event, ui) {
                        ui.item.addClass('sortable-ghost');
                    },
                    stop: function(event, ui) {
                        ui.item.removeClass('sortable-ghost');
                    }
                });
                
                $workflowSteps.disableSelection();
            }
            
            // Update status display when select changes
            $(document).on('change', '.kdsamref-step-select', function() {
                const $select = $(this);
                const selectedValue = $select.val();
                const $step = $select.closest('.kdsamref-workflow-step');
                
                if (selectedValue) {
                    const selectedOption = $select.find('option:selected');
                    const statusColor = selectedOption.data('color') || '#007cba';
                    const statusLabel = selectedOption.text();
                    
                    // Update the step display
                    updateStepDisplay($step, selectedValue, statusLabel, statusColor);
                }
            });
        });
    }
    
    // Start initialization
    initWorkflowPage();
})();

function updateStepNumbers() {
    const steps = document.querySelectorAll('.kdsamref-workflow-step');
    steps.forEach((step, index) => {
        const numberElement = step.querySelector('.kdsamref-step-number');
        if (numberElement) {
            numberElement.textContent = index + 1;
        }
    });
}

function updateStepDisplay($step, statusSlug, statusLabel, statusColor) {
    const $selectWrapper = $step.find('.kdsamref-step-select-wrapper');
    
    // Create display HTML with hidden input to preserve form data
    const displayHtml = `
        <div class="kdsamref-step-display">
            <div class="kdsamref-step-status-info">
                <div class="kdsamref-step-status-name" style="color: ${statusColor}">
                    ${statusLabel}
                </div>
                <div class="kdsamref-step-status-slug">${statusSlug}</div>
            </div>
            <div class="kdsamref-step-color-indicator" style="background-color: ${statusColor}"></div>
        </div>
        <input type="hidden" name="kdsamref_settings[workflow_steps][]" value="${statusSlug}" />
    `;
    
    // Replace select with display
    $selectWrapper.html(displayHtml);
}

function addWorkflowStep() {
    const workflowSteps = document.getElementById('kdsamref-workflow-steps');
    const steps = workflowSteps.querySelectorAll('.kdsamref-workflow-step');
    const lastStep = steps[steps.length - 1];
    
    // Create new step element
    const newStep = document.createElement('div');
    newStep.className = 'kdsamref-workflow-step';
    newStep.innerHTML = `
        <div class="kdsamref-step-drag-handle">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="8" cy="8" r="1"></circle>
                <circle cx="16" cy="8" r="1"></circle>
                <circle cx="8" cy="16" r="1"></circle>
                <circle cx="16" cy="16" r="1"></circle>
            </svg>
        </div>
        <div class="kdsamref-step-number">${steps.length}</div>
        <div class="kdsamref-step-content">
            <div class="kdsamref-step-select-wrapper">
                <select name="kdsamref_settings[workflow_steps][]" class="kdsamref-step-select" onchange="updateStepDisplayFromSelect(this)">
                    <option value="">Select a status...</option>
                    ${getStatusOptions()}
                </select>
            </div>
        </div>
        <button type="button" class="kdsamref-step-remove-btn" onclick="removeWorkflowStep(this)">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
        </button>
    `;
    
    // Insert before the last step (completed)
    workflowSteps.insertBefore(newStep, lastStep);
    updateStepNumbers();
}

function updateStepDisplayFromSelect(select) {
    const selectedValue = select.value;
    const step = select.closest('.kdsamref-workflow-step');
    
    if (selectedValue) {
        const selectedOption = select.options[select.selectedIndex];
        const statusColor = selectedOption.dataset.color || '#007cba';
        const statusLabel = selectedOption.textContent;
        
        // Update the step display using vanilla JS
        updateStepDisplayVanilla(step, selectedValue, statusLabel, statusColor);
    }
}

function updateStepDisplayVanilla(stepElement, statusSlug, statusLabel, statusColor) {
    const selectWrapper = stepElement.querySelector('.kdsamref-step-select-wrapper');
    
    // Create display HTML with hidden input to preserve form data
    const displayHtml = `
        <div class="kdsamref-step-display">
            <div class="kdsamref-step-status-info">
                <div class="kdsamref-step-status-name" style="color: ${statusColor}">
                    ${statusLabel}
                </div>
                <div class="kdsamref-step-status-slug">${statusSlug}</div>
            </div>
            <div class="kdsamref-step-color-indicator" style="background-color: ${statusColor}"></div>
        </div>
        <input type="hidden" name="kdsamref_settings[workflow_steps][]" value="${statusSlug}" />
    `;
    
    // Replace select with display
    selectWrapper.innerHTML = displayHtml;
}

function removeWorkflowStep(button) {
    const step = button.closest('.kdsamref-workflow-step');
    if (step) {
        step.remove();
        updateStepNumbers();
    }
}

function getStatusOptions() {
    // Get available statuses from WordPress/WooCommerce
    let options = '';
    
    // Add WooCommerce default statuses
    const defaultStatuses = {
        'processing': 'Processing',
        'preparing': 'Preparing',
        'ready-pickup': 'Ready for Pickup',
        'completed': 'Completed',
        'cancelled': 'Cancelled'
    };
    
    Object.keys(defaultStatuses).forEach(status => {
        options += `<option value="${status}">${defaultStatuses[status]}</option>`;
    });
    
    // Add custom statuses if available
    if (typeof kdsamrefData !== 'undefined' && kdsamrefData.customStatuses) {
        Object.keys(kdsamrefData.customStatuses).forEach(slug => {
            const status = kdsamrefData.customStatuses[slug];
            options += `<option value="${slug}" data-color="${status.color || '#007cba'}">${status.label}</option>`;
        });
    }
    
    return options;
}