<style>
    .clone-card {
        border: none;
        border-radius: 15px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
        background: #fff;
        overflow: hidden;
    }

    .clone-card .card-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        padding: 20px;
        border: none;
    }

    .clone-card .card-header h4 {
        margin: 0;
        font-weight: 600;
        letter-spacing: 0.5px;
    }

    .form-control-premium {
        border-radius: 10px;
        border: 1px solid #e0e0e0;
        padding: 12px 15px;
        height: auto;
        transition: all 0.3s ease;
    }

    .form-control-premium:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.1);
    }

    .custom-checkbox-premium .custom-control-label::before {
        border-radius: 6px;
        width: 20px;
        height: 20px;
        top: 2px;
    }

    .custom-checkbox-premium .custom-control-label::after {
        width: 20px;
        height: 20px;
        top: 2px;
    }

    .btn-premium {
        border-radius: 10px;
        padding: 12px 25px;
        font-weight: 600;
        transition: all 0.3s ease;
    }

    .btn-submit {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        border: none;
    }

    .btn-submit:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        color: #fff;
    }

    /* Steps UI */
    .clone-steps-container {
        background: var(--soft-background);
        border-radius: 15px;
        padding: 25px;
        margin-top: 30px;
        display: none;
    }

    .clone-steps {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .clone-step {
        display: flex;
        align-items: flex-start;
        margin-bottom: 20px;
        position: relative;
        opacity: 0.4;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .clone-step:not(:last-child)::after {
        content: '';
        position: absolute;
        left: 17px;
        top: 35px;
        width: 2px;
        height: calc(100% - 15px);
        background: #e0e0e0;
        z-index: 1;
    }

    .clone-step.active {
        opacity: 1;
        transform: translateX(10px);
    }

    .clone-step.completed {
        opacity: 1;
    }

    .clone-step.completed:not(:last-child)::after {
        background: #28a745;
    }

    .step-icon {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #fff;
        border: 2px solid #e0e0e0;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        font-weight: bold;
        z-index: 2;
        transition: all 0.3s ease;
        flex-shrink: 0;
    }

    .clone-step.active .step-icon {
        border-color: #667eea;
        color: #667eea;
        box-shadow: 0 0 15px rgba(102, 126, 234, 0.3);
        animation: pulse 2s infinite;
    }

    .clone-step.completed .step-icon {
        background: #28a745;
        border-color: #28a745;
        color: #fff;
    }

    .step-content h5 {
        margin: 0 0 5px 0;
        font-size: 16px;
        font-weight: 600;
    }

    .step-content p {
        margin: 0;
        font-size: 13px;
        color: #6c757d;
    }

    @keyframes pulse {
        0% {
            box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.4);
        }

        70% {
            box-shadow: 0 0 0 10px rgba(102, 126, 234, 0);
        }

        100% {
            box-shadow: 0 0 0 0 rgba(102, 126, 234, 0);
        }
    }

    .progress-premium {
        height: 10px;
        border-radius: 5px;
        background-color: #e9ecef;
        margin-bottom: 25px;
    }

    .progress-bar-premium {
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        border-radius: 5px;
    }
</style>

<div class="row justify-content-center">
    <div class="col-md-10">
        <div class="clone-card card">
            <div class="card-header">
                <h4><i class="fas fa-copy mr-2"></i> <?= lang('clone_a_restaurant'); ?></h4>
            </div>
            <form action="<?= base_url("admin/queue/run_clone"); ?>" method="post" id="cloneForm">
                <?= csrf(); ?>
                <div class="card-body p-15">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold"><?= lang('clone_from_user'); ?> </label>
                                <select name="old_user_id" id="old_user_id" class="form-control select2 form-control-premium">
                                    <option value=""><?= lang('select'); ?></option>
                                    <?php foreach ($userList as  $key => $row) : ?>
                                        <option value="<?= $row['id'] ?>"> <?= $row['username']; ?> / <?= $row['email']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold"><?= lang('clone_for_user'); ?></label>
                                <select name="new_user_id" id="new_user_id" class="form-control select2 form-control-premium">
                                    <option value=""><?= lang('select'); ?></option>
                                    <?php foreach ($newRestaurant as  $key => $new) : ?>
                                        <option value="<?= $new->user_id ?>"> <?= $new->username; ?> / <?= $new->email; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group mt-3">
                        <label class="font-weight-bold mb-10"><?= lang('select_data_to_clone'); ?></label>

                        <div class="cloneItemslist d-flex gap-30">
                            <div class="custom-control custom-checkbox custom-checkbox-premium mb-4">
                                <input type="checkbox" name="clone_items" class="custom-control-input" id="clone_items" value="1" checked>
                                <label class="custom-control-label pl-2" for="clone_items">
                                    <span class="d-block font-weight-bold"><?= lang('items_products'); ?></span>
                                    <small class="text-muted"><?= lang('items_categories_extras_sizes_packages'); ?></small>
                                </label>
                            </div>
                            <div class="custom-control custom-checkbox custom-checkbox-premium mb-4">
                                <input type="checkbox" name="clone_settings" class="custom-control-input" id="clone_settings" value="1" checked>
                                <label class="custom-control-label pl-2" for="clone_settings">
                                    <span class="d-block font-weight-bold"><?= lang('settings_config'); ?></span>
                                    <small class="text-muted"><?= lang('user_settings_delivery_areas_hotel_list'); ?></small>
                                </label>
                            </div>
                            <div class="custom-control custom-checkbox custom-checkbox-premium mb-4">
                                <input type="checkbox" name="clone_tables" class="custom-control-input" id="clone_tables" value="1" checked>
                                <label class="custom-control-label pl-2" for="clone_tables">
                                    <span class="d-block font-weight-bold"><?= lang('tables_areas'); ?></span>
                                    <small class="text-muted"><?= lang('table_list_and_areas'); ?></small>
                                </label>
                            </div>
                            <div class="custom-control custom-checkbox custom-checkbox-premium mb-4">
                                <input type="checkbox" name="clone_others" class="custom-control-input" id="clone_others" value="1" checked>
                                <label class="custom-control-label pl-2" for="clone_others">
                                    <span class="d-block font-weight-bold"><?= lang('others'); ?></span>
                                    <small class="text-muted"><?= lang('allergens_menu_types'); ?></small>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Progress Section -->
                    <div id="progressBarContainer" style="display: none;">
                        <hr class="my-4">
                        <div class="progress progress-premium">
                            <div id="progressBar" class="progress-bar progress-bar-premium" role="progressbar" style="width: 0%"></div>
                        </div>
                        <div id="progressText" class="text-center font-weight-bold mb-4" style="color: #764ba2;">Initializing...</div>

                        <div class="clone-steps-container" style="display: block;">
                            <ul class="clone-steps" id="stepsList">
                                <!-- Steps will be dynamically added here -->
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-light p-10">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex gap-10">
                            <button type="button" id="clearQueueBtn" class="btn btn-default">
                                <i class="fas fa-broom mr-1"></i> <?= lang('clear_queue'); ?>
                            </button>
                            <button type="button" id="resetBtn" class="btn btn-default">
                                <i class="fas fa-undo mr-1"></i> <?= lang('reset'); ?>
                            </button>
                        </div>
                        <button type="submit" class="btn btn-submit btn-primary px-5">
                            <?= lang('start_cloning'); ?> <i class="fas fa-arrow-right ml-2"></i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        var totalTasks = 0;
        var completedTasks = 0;
        var visualQueue = [];
        var isAnimating = false;

        $('#cloneForm').submit(function(event) {
            event.preventDefault();
            let url = $(this).attr('action');

            $('#progressBarContainer').fadeIn();
            $('#progressBar').width('0%');
            $('#progressText').text('Initializing...');
            $('#stepsList').html('');
            $('.btn-premium').prop('disabled', true);

            visualQueue = [];
            isAnimating = false;

            $.ajax({
                url: url,
                method: 'POST',
                dataType: 'json',
                data: $(this).serialize(),
                success: function(response) {
                    if (response.status == 1) {
                        totalTasks = response.totalTasks;
                        completedTasks = 0;
                        updateProgress(0, totalTasks);
                        processQueue();
                    } else {
                        $('#progressText').text('Error: ' + (response.error || 'Initialization failed')).addClass('text-danger');
                        $('.btn-premium').prop('disabled', false);
                    }
                },
                error: function() {
                    $('#progressText').text('Error occurred during initialization.').addClass('text-danger');
                    $('.btn-premium').prop('disabled', false);
                }
            });
        });

        function processQueue() {
            $.ajax({
                url: '<?= base_url("admin/queue/process_queue"); ?>',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.status == 1) {
                        if (response.completed_items && response.completed_items.length > 0) {
                            response.completed_items.forEach(function(item) {
                                visualQueue.push(item);
                            });
                            if (!isAnimating) {
                                processVisualQueue();
                            }
                        }

                        if (response.pending > 0) {
                            setTimeout(processQueue, 2000);
                        }
                    } else {
                        $('#progressText').text('Error: ' + (response.error || 'Processing failed')).addClass('text-danger');
                        $('.btn-premium').prop('disabled', false);
                    }
                },
                error: function() {
                    $('#progressText').text('Error occurred during processing.').addClass('text-danger');
                    $('.btn-premium').prop('disabled', false);
                }
            });
        }

        function processVisualQueue() {
            if (visualQueue.length === 0) {
                isAnimating = false;
                checkCompletion();
                return;
            }

            isAnimating = true;
            let item = visualQueue.shift();

            // Add the step as "Active"
            let stepId = 'step_' + item.table_name.replace(/[^a-z0-9]/gi, '_') + '_' + Date.now();
            let displayName = item.table_name.replace(/_/g, ' ').toUpperCase();

            // Deactivate previous active steps
            $('.clone-step.active').addClass('completed').removeClass('active').find('i').removeClass('fa-spinner fa-spin').addClass('fa-check');
            $('.clone-step.completed .step-content p').text('Completed successfully');

            let stepHtml = `
                <li class="clone-step active" id="${stepId}">
                    <div class="step-icon">
                        <i class="fas fa-spinner fa-spin"></i>
                    </div>
                    <div class="step-content">
                        <h5>${displayName}</h5>
                        <p>Processing...</p>
                    </div>
                </li>
            `;

            $(stepHtml).hide().appendTo('#stepsList').slideDown(500);

            // Update progress bar based on visual completion, not just background completion
            completedTasks++;
            updateProgress(completedTasks, totalTasks);

            // Wait for 3 seconds before moving to the next one to make it feel "premium"
            setTimeout(function() {
                $('#' + stepId).addClass('completed').removeClass('active');
                $('#' + stepId + ' .step-icon i').removeClass('fa-spinner fa-spin').addClass('fa-check');
                $('#' + stepId + ' .step-content p').text('Completed successfully');

                processVisualQueue();
            }, 3000);
        }

        function checkCompletion() {
            if (visualQueue.length === 0 && !isAnimating) {
                // Check if we actually finished all tasks
                $.get('<?= base_url("admin/queue/process_queue"); ?>', function(response) {
                    let res = JSON.parse(response);
                    if (res.pending === 0) {
                        $('#progressText').text('Cloning complete!').css('color', '#28a745');
                        $('.btn-premium').prop('disabled', false);
                    }
                });
            }
        }

        $('#clearQueueBtn').click(function() {
            if (confirm('Are you sure you want to clear the entire cloning queue?')) {
                $.ajax({
                    url: '<?= base_url("admin/queue/clear_queue"); ?>',
                    method: 'GET',
                    dataType: 'json',
                    success: function(response) {
                        if (response.status == 1) {
                            location.reload();
                        }
                    }
                });
            }
        });

        $('#resetBtn').click(function() {
            let new_user_id = $('#new_user_id').val();
            if (!new_user_id) {
                alert('Please select a target user first.');
                return;
            }

            if (confirm('Are you sure you want to reset all data for this restaurant? This will remove EVERYTHING.')) {
                $('#progressBarContainer').fadeIn();
                $('#progressBar').width('0%');
                $('#progressText').text('Resetting data...').css('color', '#dc3545');
                $('#stepsList').html('');
                $('.btn-premium').prop('disabled', true);

                $.ajax({
                    url: '<?= base_url("admin/queue/reset_clone"); ?>',
                    method: 'POST',
                    dataType: 'json',
                    data: {
                        'new_user_id': new_user_id,
                        '<?= $this->security->get_csrf_token_name(); ?>': '<?= $this->security->get_csrf_hash(); ?>'
                    },
                    success: function(response) {
                        if (response.status == 1) {
                            $('#progressText').text('Data reset successfully!').css('color', '#28a745');
                            $('#progressBar').width('100%').addClass('bg-danger');
                            $('.btn-premium').prop('disabled', false);
                        } else {
                            $('#progressText').text('Error: ' + (response.error || 'Reset failed')).addClass('text-danger');
                            $('.btn-premium').prop('disabled', false);
                        }
                    },
                    error: function() {
                        $('#progressText').text('Error occurred during reset.').addClass('text-danger');
                        $('.btn-premium').prop('disabled', false);
                    }
                });
            }
        });

        function updateProgress(progress, total) {
            var percentage = total > 0 ? (progress / total) * 100 : 0;
            $('#progressBar').css('width', percentage + '%');
            $('#progressText').text('Cloning in progress... ' + Math.round(percentage) + '%');
        }
    });
</script>