<template>
    <div>
        <ul class="flex space-x-2 rtl:space-x-reverse">
            <li>
                <a href="javascript:;" class="text-primary hover:underline">Price</a>
            </li>
            <li class="before:content-['/'] ltr:before:mr-2 rtl:before:ml-2">
                <span>Cost Price</span>
            </li>
        </ul>

        <div class="pt-5">
            <!-- Collection Selection and Logs -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                <!-- Collection Selection Panel -->
                <div class="panel h-full p-10">
                    <multiselect v-model="collection" :options="collections" class="custom-multiselect mt-1 mb-5"
                        :searchable="true" placeholder="Select collection" selected-label="" select-label=""
                        deselect-label="" label="title" @update:model-value="updateSelected">
                    </multiselect>

                    <div class="flex flex-col items-center justify-center">
                        <div
                            class="w-[70px] h-[70px] sm:w-[100px] sm:h-[100px] shadow-[1px_2px_12px_0_rgba(31,45,61,0.10)] rounded-full border border-[#e0e6ed] dark:border-[#1b2e4b] flex justify-center items-center">
                            <count-up class="text-primary text-xl sm:text-3xl text-center" :start-val="countinitial"
                                :end-val="total" :duration="7">
                            </count-up>
                        </div>
                        <h4
                            class="text-[#3b3f5c] text-xs sm:text-[15px] mt-4 text-center dark:text-white-dark font-semibold">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                                xmlns="http://www.w3.org/2000/svg"
                                class="w-5 h-5 sm:w-6 sm:h-6 text-primary mx-auto mb-2">
                                <path opacity="0.5"
                                    d="M6.28571 19C3.91878 19 2 17.1038 2 14.7647C2 12.4256 3.91878 10.5294 6.28571 10.5294C6.56983 10.5294 6.8475 10.5567 7.11616 10.6089M14.381 8.02721C14.9767 7.81911 15.6178 7.70588 16.2857 7.70588C16.9404 7.70588 17.5693 7.81468 18.1551 8.01498M7.11616 10.6089C6.88706 9.9978 6.7619 9.33687 6.7619 8.64706C6.7619 5.52827 9.32028 3 12.4762 3C15.4159 3 17.8371 5.19371 18.1551 8.01498M7.11616 10.6089C7.68059 10.7184 8.20528 10.9374 8.66667 11.2426M18.1551 8.01498C20.393 8.78024 22 10.8811 22 13.3529C22 16.0599 20.0726 18.3221 17.5 18.8722"
                                    stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                <path d="M12 22V16M12 22L14 20M12 22L10 20" stroke="currentColor" stroke-width="1.5"
                                    stroke-linecap="round" stroke-linejoin="round" />
                            </svg>
                            Collections
                        </h4>
                    </div>
                </div>

                <!-- Operation Logs Panel -->
                <div class="panel h-full p-6">
                    <div class="flex items-center justify-between mb-5">
                        <div>
                            <h5 class="font-semibold text-lg dark:text-white-light">Recent Operations</h5>
                            <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Last 5 cost price updates</p>
                        </div>
                        <button type="button" @click="loadLogs" class="btn btn-sm btn-primary" :disabled="loadingLogs">
                            <svg v-if="!loadingLogs" width="16" height="16" viewBox="0 0 24 24" fill="none"
                                xmlns="http://www.w3.org/2000/svg" class="inline-block mr-1">
                                <path
                                    d="M4 4V9H4.58152M19.9381 11C19.446 7.05369 16.0796 4 12 4C8.64262 4 5.76829 6.06817 4.58152 9M4.58152 9H9M20 20V15H19.4185M19.4185 15C18.2317 17.9318 15.3574 20 12 20C7.92038 20 4.55399 16.9463 4.06189 13M19.4185 15H15"
                                    stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                    stroke-linejoin="round" />
                            </svg>
                            <svg v-else viewBox="0 0 24 24" width="16" height="16" stroke="currentColor"
                                stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"
                                class="inline-block mr-1 animate-[spin_1s_linear_infinite]">
                                <line x1="12" y1="2" x2="12" y2="6"></line>
                                <line x1="12" y1="18" x2="12" y2="22"></line>
                                <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                                <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                                <line x1="2" y1="12" x2="6" y2="12"></line>
                                <line x1="18" y1="12" x2="22" y2="12"></line>
                                <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                                <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
                            </svg>
                            Refresh
                        </button>
                    </div>

                    <div v-if="loadingLogs && operationLogs.length === 0" class="flex items-center justify-center py-8">
                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    </div>

                    <div v-else-if="operationLogs.length === 0"
                        class="text-center py-8 text-gray-500 dark:text-gray-400">
                        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"
                            class="mx-auto mb-3 opacity-50">
                            <path
                                d="M9 12H15M9 16H15M17 21H7C5.89543 21 5 20.1046 5 19V5C5 3.89543 5.89543 3 7 3H12.5858C12.851 3 13.1054 3.10536 13.2929 3.29289L18.7071 8.70711C18.8946 8.89464 19 9.149 19 9.41421V19C19 20.1046 18.1046 21 17 21Z"
                                stroke="currentColor" stroke-width="2" stroke-linecap="round" />
                        </svg>
                        <p>No operations logged yet</p>
                    </div>

                    <div v-else class="space-y-2 max-h-[500px] overflow-y-auto">
                        <div v-for="log in operationLogs" :key="log.id"
                            class="px-3 py-2.5 rounded-lg border transition-all hover:shadow-sm" :class="log.status === 'success'
                                ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'
                                : 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'">
                            <div class="flex items-center justify-between gap-3">
                                <!-- Status Badge -->
                                <span
                                    class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium shrink-0"
                                    :class="log.status === 'success'
                                        ? 'bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100'
                                        : 'bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-100'">
                                    <svg v-if="log.status === 'success'" width="10" height="10" viewBox="0 0 24 24"
                                        fill="none" xmlns="http://www.w3.org/2000/svg" class="mr-1">
                                        <path d="M20 6L9 17L4 12" stroke="currentColor" stroke-width="2"
                                            stroke-linecap="round" stroke-linejoin="round" />
                                    </svg>
                                    <svg v-else width="10" height="10" viewBox="0 0 24 24" fill="none"
                                        xmlns="http://www.w3.org/2000/svg" class="mr-1">
                                        <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" />
                                        <path d="M15 9L9 15M9 9L15 15" stroke="currentColor" stroke-width="2"
                                            stroke-linecap="round" />
                                    </svg>
                                    {{ log.status === 'success' ? 'OK' : 'Error' }}
                                </span>

                                <!-- Collection Title -->
                                <div class="flex-1 min-w-0">
                                    <h6 class="font-semibold text-sm text-gray-900 dark:text-white truncate">{{
                                        log.collection_title }}</h6>
                                </div>

                                <!-- Test Mode Badge -->
                                <span v-if="log.demo_mode"
                                    class="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300 shrink-0">
                                    Test
                                </span>

                                <!-- Variants Info -->
                                <span v-if="log.total_variants > 0"
                                    class="text-xs text-gray-600 dark:text-gray-400 shrink-0">
                                    {{ log.updated_variants }}/{{ log.total_variants }}
                                </span>

                                <!-- Date -->
                                <span class="text-xs text-gray-500 dark:text-gray-500 shrink-0 whitespace-nowrap">
                                    {{ log.executed_at_human }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Test Mode & Only Draft Checkboxes - Always Visible -->
            <div class="panel">
                <div class="flex flex-col md:flex-row items-center justify-between gap-4">
                    <div class="flex flex-col gap-3">
                        <label class="inline-flex items-center cursor-pointer">
                            <input type="checkbox" class="form-checkbox text-success" v-model="test_mode_cost" />
                            <span class="ml-2 text-gray-700 dark:text-gray-300">Test mode enabled (simulation
                                only)</span>
                        </label>
                        <label class="inline-flex items-center cursor-pointer">
                            <input type="checkbox" class="form-checkbox text-primary" v-model="only_draft" />
                            <span class="ml-2 text-gray-700 dark:text-gray-300">Only draft</span>
                        </label>
                    </div>
                    <button type="button" class="btn btn-success flex items-center space-x-2" @click="showAlert(1)"
                        :disabled="updating_cost || !isConfigValid || !collectionSelected">
                        <svg v-if="!updating_cost" xmlns="http://www.w3.org/2000/svg"
                            enable-background="new 0 0 24 24" height="24px" viewBox="0 0 24 24" width="24px"
                            fill="white" class="h-5 w-5">
                            <g>
                                <rect fill="none" height="24" width="24" x="0" />
                            </g>
                            <g>
                                <g>
                                    <g>
                                        <path
                                            d="M21,10.12h-6.78l2.74-2.82c-2.73-2.7-7.15-2.8-9.88-0.1c-2.73,2.71-2.73,7.08,0,9.79s7.15,2.71,9.88,0 C18.32,15.65,19,14.08,19,12.1h2c0,1.98-0.88,4.55-2.64,6.29c-3.51,3.48-9.21,3.48-12.72,0c-3.5-3.47-3.53-9.11-0.02-12.58 s9.14-3.47,12.65,0L21,3V10.12z M12.5,8v4.25l3.5,2.08l-0.72,1.21L11,13V8H12.5z" />
                                    </g>
                                </g>
                            </g>
                        </svg>
                        <svg v-else viewBox="0 0 24 24" width="24" height="24" stroke="currentColor"
                            stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"
                            class="inline-block h-5 w-5 shrink-0 animate-[spin_2s_linear_infinite]">
                            <line x1="12" y1="2" x2="12" y2="6"></line>
                            <line x1="12" y1="18" x2="12" y2="22"></line>
                            <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                            <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                            <line x1="2" y1="12" x2="6" y2="12"></line>
                            <line x1="18" y1="12" x2="22" y2="12"></line>
                            <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                            <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
                        </svg>
                        <span v-if="!updating_cost">Update Cost Prices</span>
                        <span v-else>Updating...</span>
                    </button>
                </div>
            </div>

            <!-- Include compare price update (same as /price) -->
            <div class="panel border border-gray-200 dark:border-gray-600 mt-6 mb-8" v-if="collectionSelected && collection">
                <div class="mb-4">
                    <label class="inline-flex items-center cursor-pointer">
                        <input type="checkbox" class="form-checkbox text-primary" v-model="includeComparePriceUpdate" />
                        <span class="ml-2 font-medium text-gray-700 dark:text-gray-300">Incluir actualización de precios comparables</span>
                    </label>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1 ml-6">Si está marcado, después de ejecutar la actualización de cost price se actualizarán los precios comparables de esta colección con la configuración siguiente.</p>
                </div>

                <div v-if="includeComparePriceUpdate" class="space-y-4 pt-2 border-t border-gray-200 dark:border-gray-600">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Método de cálculo</label>
                        <div class="flex flex-wrap gap-4">
                            <label class="inline-flex items-center cursor-pointer">
                                <input type="radio" class="form-radio text-primary" v-model="comparePriceMethod" value="compare_price" />
                                <span class="ml-2">Calculate from compare price</span>
                            </label>
                            <label class="inline-flex items-center cursor-pointer">
                                <input type="radio" class="form-radio text-primary" v-model="comparePriceMethod" value="sale_price" />
                                <span class="ml-2">Calculate from sale price</span>
                            </label>
                        </div>
                    </div>

                    <div v-if="comparePriceMethod === 'compare_price'" class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Action type</label>
                            <select v-model="comparePriceAction" class="form-select">
                                <option value="Increment">Increment</option>
                                <option value="Decrement">Decrement</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Operation type</label>
                            <select v-model="comparePriceOperation" class="form-select">
                                <option value="Percent">Percent</option>
                                <option value="Value">Value</option>
                            </select>
                        </div>
                        <div class="sm:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Value</label>
                            <div class="flex">
                                <div v-if="comparePriceOperation === 'Value'" class="bg-[#eee] dark:bg-[#1b2e4b] flex items-center px-3 border border-[#e0e6ed] dark:border-[#17263c] ltr:rounded-l-md rtl:rounded-r-md" style="color: #4361ee;">$</div>
                                <div v-else class="bg-[#eee] dark:bg-[#1b2e4b] flex items-center px-3 border border-[#e0e6ed] dark:border-[#17263c] ltr:rounded-l-md rtl:rounded-r-md" style="color: #4361ee;">%</div>
                                <input type="number" step="0.01" min="0" v-model.number="comparePriceValue" class="form-input rounded-none" />
                                <div class="bg-[#eee] dark:bg-[#1b2e4b] flex items-center px-3 border ltr:border-l-0 rtl:border-r-0 border-[#e0e6ed] dark:border-[#17263c] ltr:rounded-r-md rtl:rounded-l-md">.00</div>
                            </div>
                        </div>
                    </div>

                    <div v-else class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Calculation type</label>
                            <div class="flex flex-col gap-2">
                                <label class="inline-flex items-center cursor-pointer">
                                    <input type="radio" class="form-radio text-primary" v-model="comparePriceCalculationType" value="fixed" />
                                    <span class="ml-2">Fixed Amount</span>
                                </label>
                                <label class="inline-flex items-center cursor-pointer">
                                    <input type="radio" class="form-radio text-primary" v-model="comparePriceCalculationType" value="percentage" />
                                    <span class="ml-2">Percentage</span>
                                </label>
                                <label class="inline-flex items-center cursor-pointer">
                                    <input type="radio" class="form-radio text-primary" v-model="comparePriceCalculationType" value="discount_based" />
                                    <span class="ml-2">Discount-based (Shopify compatibility)</span>
                                </label>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                <span v-if="comparePriceCalculationType === 'fixed'">Fixed amount to add</span>
                                <span v-else-if="comparePriceCalculationType === 'percentage'">Percentage of sale price</span>
                                <span v-else>Discount percentage</span>
                            </label>
                            <div class="flex">
                                <div v-if="comparePriceCalculationType === 'fixed'" class="bg-[#eee] dark:bg-[#1b2e4b] flex items-center px-3 border border-[#e0e6ed] dark:border-[#17263c] ltr:rounded-l-md rtl:rounded-r-md" style="color: #4361ee;">$</div>
                                <input type="number" :step="comparePriceCalculationType === 'fixed' ? '0.01' : '0.1'" :min="0" :max="comparePriceCalculationType === 'discount_based' ? 99.99 : undefined" v-model.number="comparePriceAmount" class="form-input" :class="comparePriceCalculationType === 'fixed' ? 'rounded-none' : 'ltr:rounded-l-md rtl:rounded-r-md'" />
                                <div v-if="comparePriceCalculationType !== 'fixed'" class="bg-[#eee] dark:bg-[#1b2e4b] flex items-center px-3 border ltr:border-l-0 rtl:border-r-0 border-[#e0e6ed] dark:border-[#17263c] ltr:rounded-r-md rtl:rounded-l-md" style="color: #4361ee;">%</div>
                                <div v-else class="bg-[#eee] dark:bg-[#1b2e4b] flex items-center px-3 border ltr:border-l-0 rtl:border-r-0 border-[#e0e6ed] dark:border-[#17263c] ltr:rounded-r-md rtl:rounded-l-md">.00</div>
                            </div>
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Redondeo de precios comparables</label>
                        <div class="space-y-2">
                            <label class="flex items-center cursor-pointer p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50">
                                <input type="radio" class="form-radio text-primary" v-model="comparePriceRoundingOption" value="default" />
                                <span class="ml-2 text-sm">Default (round to nearest integer)</span>
                            </label>
                            <label class="flex items-center cursor-pointer p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50">
                                <input type="radio" class="form-radio text-primary" v-model="comparePriceRoundingOption" value="round_to_99_99" />
                                <span class="ml-2 text-sm">Round to .99</span>
                            </label>
                            <label class="flex items-center cursor-pointer p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50">
                                <input type="radio" class="form-radio text-primary" v-model="comparePriceRoundingOption" value="round_to_hundreds" />
                                <span class="ml-2 text-sm">Round to hundreds .00</span>
                            </label>
                            <label class="flex items-center cursor-pointer p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50">
                                <input type="radio" class="form-radio text-primary" v-model="comparePriceRoundingOption" value="round_to_hundreds_minus_one" />
                                <span class="ml-2 text-sm">Round to hundreds minus 1</span>
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Cost Configuration Form - Shows when collection is selected -->
            <div v-if="collectionSelected" class="space-y-5">
                <!-- Product Selection Section -->
                <div class="panel">
                    <div class="mb-5">
                        <h5 class="font-semibold text-lg dark:text-white-light">Product Selection</h5>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                            Select specific products to update (leave empty to process all products in the collection)
                        </p>
                    </div>
                    <div v-if="loadingProducts" class="flex items-center justify-center py-4">
                        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
                        <span class="ml-2 text-sm text-gray-600 dark:text-gray-400">Loading products...</span>
                    </div>
                    <multiselect v-else v-model="selectedProducts" :options="collectionProducts"
                        class="custom-multiselect" :searchable="true" :multiple="true"
                        placeholder="Select products (optional - leave empty for all products)" selected-label=""
                        select-label="" deselect-label="" label="title" track-by="id" :close-on-select="false"
                        :clear-on-select="false" :preserve-search="true">
                        <template #noOptions>
                            <span>No products found</span>
                        </template>
                        <template #noResult>
                            <span>No products found</span>
                        </template>
                    </multiselect>
                    <p v-if="selectedProducts.length > 0" class="mt-2 text-sm text-gray-600 dark:text-gray-400">
                        {{ selectedProducts.length }} product(s) selected
                    </p>
                </div>

                <!-- Profit Ranges Section -->
                <div class="panel">
                    <div class="flex items-center justify-between mb-5">
                        <div>
                            <h5 class="font-semibold text-lg dark:text-white-light">Profit Ranges</h5>
                            <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Define profit margins for different
                                cost ranges</p>
                        </div>
                        <button type="button" class="btn btn-primary" @click="addRange">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
                                xmlns="http://www.w3.org/2000/svg" class="inline-block mr-1">
                                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="1.5" />
                                <path d="M15 12L12 12M12 12L9 12M12 12L12 9M12 12L12 15" stroke="currentColor"
                                    stroke-width="1.5" stroke-linecap="round" />
                            </svg>
                            Add Range
                        </button>
                    </div>

                    <div class="space-y-4">
                        <div v-for="(range, index) in profitRanges" :key="index"
                            class="p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:shadow-md transition-shadow">
                            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                                <!-- Min Cost -->
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Min Cost ($)
                                    </label>
                                    <div class="flex">
                                        <div class="bg-[#eee] flex justify-center items-center ltr:rounded-l-md rtl:rounded-r-md px-3 font-semibold border ltr:border-r-0 rtl:border-l-0 border-[#e0e6ed] dark:border-[#17263c] dark:bg-[#1b2e4b]"
                                            style="color: #4361ee;">
                                            $
                                        </div>
                                        <input type="number" v-model="range.min_cost"
                                            class="form-input rounded-none ltr:rounded-r-md rtl:rounded-l-md"
                                            placeholder="0" step="0.01" min="0" />
                                    </div>
                                </div>

                                <!-- Max Cost -->
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Max Cost ($)
                                    </label>
                                    <div class="flex">
                                        <div class="bg-[#eee] flex justify-center items-center ltr:rounded-l-md rtl:rounded-r-md px-3 font-semibold border ltr:border-r-0 rtl:border-l-0 border-[#e0e6ed] dark:border-[#17263c] dark:bg-[#1b2e4b]"
                                            style="color: #4361ee;">
                                            $
                                        </div>
                                        <input type="number" v-model="range.max_cost"
                                            class="form-input rounded-none ltr:rounded-r-md rtl:rounded-l-md"
                                            placeholder="1000" step="0.01" min="0" />
                                    </div>
                                </div>

                                <!-- Profit (absolute or %) -->
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                        Profit ({{ range.profit_type === 'percentage' ? '%' : '$' }})
                                    </label>
                                    <div class="flex flex-wrap gap-2 items-stretch">
                                        <select v-model="range.profit_type"
                                            class="form-select rounded-md border border-[#e0e6ed] dark:border-[#17263c] dark:bg-[#1b2e4b] shrink-0 w-24">
                                            <option value="absolute">$ (abs)</option>
                                            <option value="percentage">%</option>
                                        </select>
                                        <div class="flex flex-1 min-w-[100px]">
                                            <div v-if="range.profit_type === 'absolute'"
                                                class="bg-[#eee] flex justify-center items-center ltr:rounded-l-md rtl:rounded-r-md px-3 font-semibold border ltr:border-r-0 rtl:border-l-0 border-[#e0e6ed] dark:border-[#17263c] dark:bg-[#1b2e4b]"
                                                style="color: #4361ee;">$</div>
                                            <input type="number" v-model="range.profit"
                                                class="form-input flex-1 rounded-none ltr:rounded-r-md rtl:rounded-l-md"
                                                :placeholder="range.profit_type === 'percentage' ? '95' : '200'"
                                                :step="range.profit_type === 'percentage' ? '0.01' : '0.01'"
                                                :min="range.profit_type === 'percentage' ? 0 : 0" />
                                            <div v-if="range.profit_type === 'percentage'"
                                                class="bg-[#eee] flex justify-center items-center ltr:rounded-r-md rtl:rounded-l-md px-2 font-semibold border ltr:border-l-0 rtl:border-r-0 border-[#e0e6ed] dark:border-[#17263c] dark:bg-[#1b2e4b]"
                                                style="color: #4361ee;">%</div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Delete Button -->
                                <div>
                                    <button type="button" @click="removeRange(index)"
                                        class="btn btn-danger w-full md:w-auto">
                                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
                                            xmlns="http://www.w3.org/2000/svg">
                                            <path d="M20.5001 6H3.5" stroke="currentColor" stroke-width="1.5"
                                                stroke-linecap="round" />
                                            <path
                                                d="M18.8332 8.5L18.3732 15.3991C18.1962 18.054 18.1077 19.3815 17.2427 20.1907C16.3777 21 15.0473 21 12.3865 21H11.6132C8.95235 21 7.62195 21 6.75694 20.1907C5.89194 19.3815 5.80344 18.054 5.62644 15.3991L5.1665 8.5"
                                                stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                        </svg>
                                        <span class="hidden md:inline ml-1">Remove</span>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div v-if="profitRanges.length === 0" class="text-center py-8 text-gray-500 dark:text-gray-400">
                            <p>No profit ranges defined yet. Click "Add Range" to create one.</p>
                        </div>
                    </div>
                </div>

                <!-- Expenses Section -->
                <div class="panel">
                    <div class="mb-5">
                        <h5 class="font-semibold text-lg dark:text-white-light">Expenses Configuration</h5>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Configure fixed and variable expenses
                        </p>
                    </div>

                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
                        <!-- Shipping -->
                        <div
                            class="panel bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-800/20 border border-blue-200 dark:border-blue-700">
                            <div class="mb-3 flex items-center">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                                    xmlns="http://www.w3.org/2000/svg" class="text-blue-600 dark:text-blue-400 mr-2">
                                    <path
                                        d="M2 3L2 10C2 10.9319 2 11.3978 2.15224 11.7654C2.35523 12.2554 2.74458 12.6448 3.23463 12.8478C3.60218 13 4.06812 13 5 13H9M22 21V14C22 13.0681 22 12.6022 21.8478 12.2346C21.6448 11.7446 21.2554 11.3552 20.7654 11.1522C20.3978 11 19.9319 11 19 11H5C4.06812 11 3.60218 11 3.23463 11.1522C2.74458 11.3552 2.35523 11.7446 2.15224 12.2346C2 12.6022 2 13.0681 2 14V21"
                                        stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
                                        stroke-linejoin="round" />
                                </svg>
                                <h6 class="font-semibold text-blue-900 dark:text-blue-100">Shipping Cost</h6>
                            </div>
                            <p class="text-xs text-blue-700 dark:text-blue-300 mb-3">Always absolute value</p>
                            <div class="flex">
                                <div
                                    class="bg-blue-200 dark:bg-blue-900 flex justify-center items-center ltr:rounded-l-md rtl:rounded-r-md px-3 font-semibold border ltr:border-r-0 rtl:border-l-0 border-blue-300 dark:border-blue-700 text-blue-700 dark:text-blue-300">
                                    $
                                </div>
                                <input type="number" v-model="expenses.shipping"
                                    class="form-input rounded-none ltr:rounded-r-md rtl:rounded-l-md"
                                    placeholder="50.00" step="0.01" min="0" />
                            </div>
                        </div>

                        <!-- Fix Gateway -->
                        <div
                            class="panel bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-900/20 dark:to-purple-800/20 border border-purple-200 dark:border-purple-700">
                            <div class="mb-3 flex items-center">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                                    xmlns="http://www.w3.org/2000/svg"
                                    class="text-purple-600 dark:text-purple-400 mr-2">
                                    <path d="M9 11L12 14L22 4" stroke="currentColor" stroke-width="1.5"
                                        stroke-linecap="round" stroke-linejoin="round" />
                                    <path
                                        d="M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3"
                                        stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                </svg>
                                <h6 class="font-semibold text-purple-900 dark:text-purple-100">Fix Gateway Fee</h6>
                            </div>
                            <p class="text-xs text-purple-700 dark:text-purple-300 mb-3">Always percentage (applied at
                                the end)</p>
                            <div class="flex">
                                <input type="number" v-model="expenses.fix_gateway"
                                    class="form-input ltr:rounded-l-md rtl:rounded-r-md rounded-none" placeholder="3.00"
                                    step="0.01" min="0" max="100" />
                                <div
                                    class="bg-purple-200 dark:bg-purple-900 flex justify-center items-center ltr:rounded-r-md rtl:rounded-l-md px-3 font-semibold border ltr:border-l-0 rtl:border-r-0 border-purple-300 dark:border-purple-700 text-purple-700 dark:text-purple-300">
                                    %
                                </div>
                            </div>
                        </div>

                        <!-- Commission -->
                        <div
                            class="panel bg-gradient-to-br from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-800/20 border border-green-200 dark:border-green-700">
                            <div class="mb-3 flex items-center">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                                    xmlns="http://www.w3.org/2000/svg" class="text-green-600 dark:text-green-400 mr-2">
                                    <path d="M16 8L18 10L22 6" stroke="currentColor" stroke-width="1.5"
                                        stroke-linecap="round" stroke-linejoin="round" />
                                    <path
                                        d="M2 12C2 8.22876 2 6.34315 3.17157 5.17157C4.34315 4 6.22876 4 10 4H11C14.7712 4 16.6569 4 17.8284 5.17157C19 6.34315 19 8.22876 19 12C19 15.7712 19 17.6569 17.8284 18.8284C16.6569 20 14.7712 20 11 20H10C6.22876 20 4.34315 20 3.17157 18.8284C2 17.6569 2 15.7712 2 12Z"
                                        stroke="currentColor" stroke-width="1.5" />
                                </svg>
                                <h6 class="font-semibold text-green-900 dark:text-green-100">Sales Commission</h6>
                            </div>
                            <p class="text-xs text-green-700 dark:text-green-300 mb-3">Can be percentage or absolute
                                value</p>
                            <div class="mb-3">
                                <div class="flex items-center space-x-4">
                                    <label class="flex items-center cursor-pointer">
                                        <input type="radio" v-model="expenses.commission_type" value="percentage"
                                            class="form-radio text-green-600 border-green-300" />
                                        <span class="ml-2 text-sm text-green-900 dark:text-green-100">Percentage
                                            (%)</span>
                                    </label>
                                    <label class="flex items-center cursor-pointer">
                                        <input type="radio" v-model="expenses.commission_type" value="absolute"
                                            class="form-radio text-green-600 border-green-300" />
                                        <span class="ml-2 text-sm text-green-900 dark:text-green-100">Absolute
                                            ($)</span>
                                    </label>
                                </div>
                            </div>
                            <div class="flex">
                                <div v-if="expenses.commission_type === 'absolute'"
                                    class="bg-green-200 dark:bg-green-900 flex justify-center items-center ltr:rounded-l-md rtl:rounded-r-md px-3 font-semibold border ltr:border-r-0 rtl:border-l-0 border-green-300 dark:border-green-700 text-green-700 dark:text-green-300">
                                    $
                                </div>
                                <input type="number" v-model="expenses.commission_value"
                                    :class="expenses.commission_type === 'absolute' ? 'form-input rounded-none ltr:rounded-r-md rtl:rounded-l-md' : 'form-input ltr:rounded-l-md rtl:rounded-r-md rounded-none'"
                                    placeholder="100.00" step="0.01" min="0" />
                                <div v-if="expenses.commission_type === 'percentage'"
                                    class="bg-green-200 dark:bg-green-900 flex justify-center items-center ltr:rounded-r-md rtl:rounded-l-md px-3 font-semibold border ltr:border-l-0 rtl:border-r-0 border-green-300 dark:border-green-700 text-green-700 dark:text-green-300">
                                    %
                                </div>
                            </div>
                        </div>

                        <!-- Extras -->
                        <div
                            class="panel bg-gradient-to-br from-yellow-50 to-yellow-100 dark:from-yellow-900/20 dark:to-yellow-800/20 border border-yellow-200 dark:border-yellow-700">
                            <div class="mb-3 flex items-center">
                                <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                                    xmlns="http://www.w3.org/2000/svg"
                                    class="text-yellow-600 dark:text-yellow-400 mr-2">
                                    <path d="M12 6V18" stroke="currentColor" stroke-width="1.5"
                                        stroke-linecap="round" />
                                    <path
                                        d="M15 9.5C15 8.11929 13.6569 7 12 7C10.3431 7 9 8.11929 9 9.5C9 10.8807 10.3431 12 12 12C13.6569 12 15 13.1193 15 14.5C15 15.8807 13.6569 17 12 17C10.3431 17 9 15.8807 9 14.5"
                                        stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                                    <path
                                        d="M22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12Z"
                                        stroke="currentColor" stroke-width="1.5" />
                                </svg>
                                <h6 class="font-semibold text-yellow-900 dark:text-yellow-100">Extra Costs</h6>
                            </div>
                            <p class="text-xs text-yellow-700 dark:text-yellow-300 mb-3">Can be percentage or absolute
                                value</p>
                            <div class="mb-3">
                                <div class="flex items-center space-x-4">
                                    <label class="flex items-center cursor-pointer">
                                        <input type="radio" v-model="expenses.extras_type" value="percentage"
                                            class="form-radio text-yellow-600 border-yellow-300" />
                                        <span class="ml-2 text-sm text-yellow-900 dark:text-yellow-100">Percentage
                                            (%)</span>
                                    </label>
                                    <label class="flex items-center cursor-pointer">
                                        <input type="radio" v-model="expenses.extras_type" value="absolute"
                                            class="form-radio text-yellow-600 border-yellow-300" />
                                        <span class="ml-2 text-sm text-yellow-900 dark:text-yellow-100">Absolute
                                            ($)</span>
                                    </label>
                                </div>
                            </div>
                            <div class="flex">
                                <div v-if="expenses.extras_type === 'absolute'"
                                    class="bg-yellow-200 dark:bg-yellow-900 flex justify-center items-center ltr:rounded-l-md rtl:rounded-r-md px-3 font-semibold border ltr:border-r-0 rtl:border-l-0 border-yellow-300 dark:border-yellow-700 text-yellow-700 dark:text-yellow-300">
                                    $
                                </div>
                                <input type="number" v-model="expenses.extras"
                                    :class="expenses.extras_type === 'absolute' ? 'form-input rounded-none ltr:rounded-r-md rtl:rounded-l-md' : 'form-input ltr:rounded-l-md rtl:rounded-r-md rounded-none'"
                                    placeholder="0.00" step="0.01" min="0" />
                                <div v-if="expenses.extras_type === 'percentage'"
                                    class="bg-yellow-200 dark:bg-yellow-900 flex justify-center items-center ltr:rounded-r-md rtl:rounded-l-md px-3 font-semibold border ltr:border-l-0 rtl:border-r-0 border-yellow-300 dark:border-yellow-700 text-yellow-700 dark:text-yellow-300">
                                    %
                                </div>
                            </div>
                            <p v-if="expenses.extras_type === 'percentage'"
                                class="text-xs text-yellow-700 dark:text-yellow-300 mt-2">
                                Calculated on: Cost + Profit + Fix Gateway Fee
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Price Rounding Options -->
                <div class="panel">
                    <div class="mb-5">
                        <h5 class="font-semibold text-lg dark:text-white-light">Price Rounding Options</h5>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Select how the final sale price should
                            be rounded</p>
                    </div>

                    <div class="space-y-3">
                        <label
                            class="flex items-center cursor-pointer p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                            <input type="radio" class="form-radio text-primary" v-model="roundingOption"
                                value="default" />
                            <span class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">
                                Default (round to nearest integer)
                            </span>
                        </label>
                        <label
                            class="flex items-center cursor-pointer p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                            <input type="radio" class="form-radio text-primary" v-model="roundingOption"
                                value="round_to_99_99" />
                            <span class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">
                                Round to .99 (round to nearest 100, then subtract 1 and add 0.99)
                            </span>
                        </label>
                        <label
                            class="flex items-center cursor-pointer p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                            <input type="radio" class="form-radio text-primary" v-model="roundingOption"
                                value="round_to_hundreds" />
                            <span class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">
                                Round to hundreds .00 (round up to nearest 100)
                            </span>
                        </label>
                        <label
                            class="flex items-center cursor-pointer p-3 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                            <input type="radio" class="form-radio text-primary" v-model="roundingOption"
                                value="round_to_hundreds_minus_one" />
                            <span class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">
                                Round to hundreds minus 1 (round up to nearest 100, then subtract 1)
                            </span>
                        </label>
                    </div>
                </div>

                <!-- Progress Bar (only shown when updating in non-demo mode) -->
                <div v-if="showProgress || (updating_cost && !test_mode_cost)" class="panel">
                    <div class="mb-4">
                        <div class="flex items-center justify-between mb-2">
                            <h5 class="font-semibold text-lg dark:text-white-light">Updating Prices</h5>
                            <span class="text-sm text-gray-600 dark:text-gray-400">
                                {{ progressData ? `${progressData.processed} / ${progressData.total}` : '0 / 0' }}
                            </span>
                        </div>
                        <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-3 overflow-hidden">
                            <div class="bg-gradient-to-r from-primary to-primary-dark h-3 rounded-full transition-all duration-300 ease-out flex items-center justify-end pr-2"
                                :style="{ width: progressData && progressData.total > 0 ? `${Math.min(100, (progressData.processed / progressData.total) * 100)}%` : '0%' }">
                                <span class="text-xs text-white font-semibold">
                                    {{ progressData && progressData.total > 0 ? Math.round((progressData.processed /
                                        progressData.total) * 100) : 0 }}%
                                </span>
                            </div>
                        </div>
                        <div v-if="progressData?.current_variant" class="mt-2 text-sm text-gray-600 dark:text-gray-400">
                            <span class="inline-flex items-center">
                                <svg class="animate-spin h-4 w-4 mr-2 text-primary" xmlns="http://www.w3.org/2000/svg"
                                    fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
                                        stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor"
                                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
                                    </path>
                                </svg>
                                Processing: {{ progressData.current_variant }}
                            </span>
                        </div>
                        <div v-if="progressData?.errors > 0" class="mt-2 text-sm text-red-600 dark:text-red-400">
                            Errors: {{ progressData.errors }}
                        </div>
                    </div>
                </div>


                <!-- Results Table -->
                <div class="panel pb-0">
                    <h5 class="font-semibold text-lg dark:text-white-light mb-5">
                        Calculation Results
                        <span class="text-sm font-normal text-gray-500 dark:text-gray-400 ml-2">
                            ({{ rows.length }} variants processed)
                        </span>
                    </h5>
                    <div class="datatable overflow-x-auto">
                        <vue3-datatable :rows="rows" :columns="cols" :totalRows="rows?.length" :columnFilter="true"
                            skin="whitespace-nowrap bh-table-hover"
                            firstArrow='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 rtl:rotate-180"> <path d="M13 19L7 12L13 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> <path opacity="0.5" d="M16.9998 19L10.9998 12L16.9998 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg>'
                            lastArrow='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 rtl:rotate-180"> <path d="M11 19L17 12L11 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> <path opacity="0.5" d="M6.99976 19L12.9998 12L6.99976 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg> '
                            previousArrow='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 rtl:rotate-180"> <path d="M15 5L9 12L15 19" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg>'
                            nextArrow='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 rtl:rotate-180"> <path d="M9 5L15 12L9 19" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg>'>
                        </vue3-datatable>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import Multiselect from '@suadelabs/vue3-multiselect';
import '@suadelabs/vue3-multiselect/dist/vue3-multiselect.css';
import { router } from '@inertiajs/vue3'
import CountUp from 'vue-countup-v3';
import axios from 'axios';
import Swal from 'sweetalert2';
import { useAppStore } from '@/stores/index';
import Vue3Datatable from '@bhplugin/vue3-datatable';

interface ProfitRange {
    min_cost: number;
    max_cost: number;
    profit: number;
    profit_type: 'absolute' | 'percentage';
}

interface Expenses {
    shipping: number;
    fix_gateway: number;
    commission_type: 'percentage' | 'absolute';
    commission_value: number;
    extras_type: 'percentage' | 'absolute';
    extras: number;
}

const { collections, total } = defineProps({
    collections: Object,
    total: Object
});

const store = useAppStore();
const collection = ref([]);
const countinitial = ref<number>(0);
const countend = ref<number>(0);
const collectionSelected = ref<boolean>(false);
const updating_cost = ref<boolean>(false);
const test_mode_cost = ref<boolean>(true);
const only_draft = ref<boolean>(true); // Default: checked
const operationLogs = ref<any[]>([]);
const loadingLogs = ref<boolean>(false);

// Product selection
const collectionProducts = ref<any[]>([]);
const selectedProducts = ref<any[]>([]);
const loadingProducts = ref<boolean>(false);

// Progress tracking
const showProgress = ref<boolean>(false);
const progressData = ref<any>(null);
const progressPollingInterval = ref<any>(null);
const progressCompletedShown = ref<boolean>(false); // Flag to prevent multiple completion toasts

// Include compare price update (same as /price)
const includeComparePriceUpdate = ref<boolean>(false);
const comparePriceMethod = ref<'compare_price' | 'sale_price'>('compare_price');
const comparePriceAction = ref<string>('Increment');
const comparePriceOperation = ref<string>('Percent');
const comparePriceValue = ref<number>(0);
const comparePriceCalculationType = ref<string>('fixed');
const comparePriceAmount = ref<number>(0);
const comparePriceRoundingOption = ref<string>('default');
const updatingComparePrice = ref<boolean>(false);

// Default values for reset
const defaultProfitRanges: ProfitRange[] = [
    { min_cost: 0, max_cost: 1000, profit: 200, profit_type: 'absolute' }
];

const defaultExpenses: Expenses = {
    shipping: 50,
    fix_gateway: 3.5,
    commission_type: 'absolute',
    commission_value: 50,
    extras_type: 'absolute',
    extras: 0
};

const profitRanges = ref<ProfitRange[]>(JSON.parse(JSON.stringify(defaultProfitRanges)));

const expenses = ref<Expenses>(JSON.parse(JSON.stringify(defaultExpenses)));

const roundingOption = ref<string>('default'); // 'default', 'round_to_99_99', 'round_to_hundreds', 'round_to_hundreds_minus_one'

const cols = ref([
    { field: 'product_title', title: 'Product', isUnique: true, width: '200px' },
    { field: 'variant_title', title: 'Variant', width: '150px' },
    { field: 'before_sale_price', title: 'Sale Price (Before)', width: '120px' },
    { field: 'before_price', title: 'Cost Price', width: '100px' },
    { field: 'calculation_breakdown.profit', title: '+ Profit', width: '90px' },
    { field: 'calculation_breakdown.shipping', title: '+ Shipping', width: '90px' },
    { field: 'calculation_breakdown.commission', title: '+ Commission', width: '110px' },
    { field: 'calculation_breakdown.fix_gateway', title: '+ Gateway', width: '100px' },
    { field: 'calculation_breakdown.extras', title: '+ Extras', width: '90px' },
    { field: 'after_sale_price', title: '= Sale Price (After)', width: '120px' },
    { field: 'after_compare_price', title: 'Compare Price', width: '120px' },
]) || [];

const rows = ref([]);

function resetToDefaults(): void {
    // Reset profit ranges to defaults
    profitRanges.value = JSON.parse(JSON.stringify(defaultProfitRanges));

    // Reset expenses to defaults
    expenses.value = JSON.parse(JSON.stringify(defaultExpenses));

    // Reset rounding option to default
    roundingOption.value = 'default';

    // Clear results table
    rows.value = [];

    // Clear product selection
    selectedProducts.value = [];
}

const isConfigValid = computed(() => {
    if (profitRanges.value.length === 0) return false;

    for (const range of profitRanges.value) {
        if (range.min_cost >= range.max_cost) return false;
        if (range.profit < 0) return false;
    }

    if (expenses.value.shipping < 0 || expenses.value.fix_gateway < 0 ||
        expenses.value.commission_value < 0 || expenses.value.extras < 0) {
        return false;
    }

    return true;
});

async function updateSelected(): Promise<void> {
    countend.value = 0;
    try {
        // Reset to defaults first when changing collection
        resetToDefaults();

        // Reset product selection
        selectedProducts.value = [];
        collectionProducts.value = [];

        collectionSelected.value = true;

        // Load products from collection
        if (collection.value && collection.value.id) {
            await loadCollectionProducts(collection.value.id);
            await loadSavedConfiguration(collection.value.id);
        }
    } catch (error) {
        console.error('Error al enviar la solicitud:', error);
    }
}

async function loadCollectionProducts(collectionId: string): Promise<void> {
    try {
        loadingProducts.value = true;
        const response = await axios.get('/get/collection/products', {
            params: { collection_id: collectionId }
        });

        if (response.data.status === 200 && response.data.data) {
            collectionProducts.value = response.data.data;
        }
    } catch (error: any) {
        console.error('Error loading collection products:', error);
        collectionProducts.value = [];
    } finally {
        loadingProducts.value = false;
    }
}

async function loadSavedConfiguration(collectionId: string): Promise<void> {
    try {
        const response = await axios.get('/get/collection/cost_configuration', {
            params: { collection_id: collectionId }
        });

        if (response.data.status === 200 && response.data.data) {
            const config = response.data.data;

            // Load profit ranges if they exist
            if (config.profit_ranges && config.profit_ranges.length > 0) {
                profitRanges.value = config.profit_ranges.map((range: any) => ({
                    min_cost: parseFloat(range.min_cost) || 0,
                    max_cost: parseFloat(range.max_cost) || 0,
                    profit: parseFloat(range.profit) || 0,
                    profit_type: range.profit_type === 'percentage' ? 'percentage' : 'absolute'
                }));
            }

            // Load expenses if they exist
            if (config.expenses) {
                expenses.value = {
                    shipping: parseFloat(config.expenses.shipping) || 50,
                    fix_gateway: parseFloat(config.expenses.fix_gateway) || 3.5,
                    commission_type: config.expenses.commission_type || 'absolute',
                    commission_value: parseFloat(config.expenses.commission_value) || 50,
                    extras_type: config.expenses.extras_type || 'absolute',
                    extras: parseFloat(config.expenses.extras) || 0
                };
            }

            // Load rounding option if it exists
            if (config.rounding_option) {
                roundingOption.value = config.rounding_option;
            }

            // Show notification that configuration was loaded
            Swal.fire({
                icon: 'info',
                title: 'Configuration Loaded',
                text: 'Saved profit ranges and expenses have been loaded for this collection.',
                timer: 2000,
                showConfirmButton: false,
                customClass: 'sweet-alerts'
            });
        }
    } catch (error: any) {
        // If no configuration found (404), reset to defaults
        if (error.response && error.response.status === 404) {
            // No saved configuration, reset to defaults (already reset in updateSelected, but ensure it's done)
            resetToDefaults();
            console.log('No saved configuration found for this collection, using defaults');
        } else {
            console.error('Error loading saved configuration:', error);
            // On other errors, also reset to defaults to ensure clean state
            resetToDefaults();
        }
    }
}

async function loadLogs(): Promise<void> {
    try {
        loadingLogs.value = true;
        const response = await axios.get('/get/collection/cost_price_logs', {
            params: { limit: 5 }
        });

        if (response.data.status === 200 && response.data.data) {
            operationLogs.value = response.data.data;
        }
    } catch (error) {
        console.error('Error loading operation logs:', error);
    } finally {
        loadingLogs.value = false;
    }
}

// Load logs when component mounts
onMounted(() => {
    loadLogs();
});

function addRange() {
    const lastRange = profitRanges.value[profitRanges.value.length - 1];
    const newMinCost = lastRange ? parseFloat(lastRange.max_cost.toString()) + 1 : 0;

    profitRanges.value.push({
        min_cost: newMinCost,
        max_cost: newMinCost + 1000,
        profit: 0,
        profit_type: 'absolute'
    });
}

function removeRange(index: number) {
    if (profitRanges.value.length === 1) {
        Swal.fire({
            icon: 'warning',
            title: 'Cannot Remove',
            text: 'You must have at least one profit range.',
            confirmButtonColor: '#3085d6'
        });
        return;
    }
    profitRanges.value.splice(index, 1);
}

function updateShopify(demo): void {
    try {
        updating_cost.value = true;

        // If not in demo mode, show progress bar immediately
        if (!demo) {
            showProgress.value = true;
            progressData.value = {
                total: 0,
                processed: 0,
                errors: 0,
                status: 'processing',
                current_variant: 'Initializing...'
            };
        }

        const url = "/update/collection/cost_price";
        const title_ok = "Cost price updated!";

        const payload = {
            collection_id: collection.value.id,
            profit_ranges: profitRanges.value,
            expenses: expenses.value,
            rounding_option: roundingOption.value,
            demo: demo,
            only_draft: only_draft.value,
            selected_product_ids: selectedProducts.value.length > 0
                ? selectedProducts.value.map((p: any) => p.id)
                : null // null means all products
        };

        axios.post(url, payload).then((response) => {
            // Check if this is an "Accepted" response (202) with progress_id for async processing
            if (response.status === 202 && response.data?.data?.progress_id) {
                const progressId = response.data.data.progress_id;

                showProgress.value = true;
                progressData.value = {
                    total: 0,
                    processed: 0,
                    errors: 0,
                    status: 'processing',
                    current_variant: 'Initializing...'
                };

                // Start polling immediately
                startProgressPolling(progressId);
                return; // Exit early, processing continues in background
            }

            // For demo mode or synchronous responses, handle normally
            // Try different possible response structures
            let progressId = null;
            if (response.data?.data?.summary?.progress_id) {
                progressId = response.data.data.summary.progress_id;
            } else if (response.data?.summary?.progress_id) {
                progressId = response.data.summary.progress_id;
            } else if (response.data?.data?.progress_id) {
                progressId = response.data.data.progress_id;
            }

            // If not in demo mode and we have a progress ID, start polling
            if (!demo && progressId) {
                showProgress.value = true;
                progressData.value = {
                    total: 0,
                    processed: 0,
                    errors: 0,
                    status: 'processing',
                    current_variant: null
                };

                // Start polling for progress immediately
                startProgressPolling(progressId);
            } else {
                // Demo mode or no progress ID - show results immediately
                Swal.fire({
                    title: title_ok,
                    text: 'All collections updated.',
                    icon: 'success',
                    customClass: 'sweet-alerts'
                });
                updating_cost.value = false;

                // Reload operation logs after update
                loadLogs();

                // Flatten calculation_breakdown for table display
                const processedData = response.data.data.data.map(item => {
                    return {
                        ...item,
                        before_sale_price: item.before_sale_price ? (item.before_sale_price % 1 === 0 ? `$${item.before_sale_price}` : `$${item.before_sale_price.toFixed(2)}`) : '$0',
                        'calculation_breakdown.profit': item.calculation_breakdown?.profit ? `$${Math.round(item.calculation_breakdown.profit)}` : '$0',
                        'calculation_breakdown.shipping': item.calculation_breakdown?.shipping ? `$${Math.round(item.calculation_breakdown.shipping)}` : '$0',
                        'calculation_breakdown.commission': item.calculation_breakdown?.commission ? `$${Math.round(item.calculation_breakdown.commission)}` : '$0',
                        'calculation_breakdown.fix_gateway': item.calculation_breakdown?.fix_gateway ? `$${Math.round(item.calculation_breakdown.fix_gateway)}` : '$0',
                        'calculation_breakdown.extras': item.calculation_breakdown?.extras ? `$${Math.round(item.calculation_breakdown.extras)}` : '$0',
                        before_price: item.before_price ? `$${Math.round(item.before_price)}` : '$0',
                        after_sale_price: item.after_sale_price ? (item.after_sale_price % 1 === 0 ? `$${Math.round(item.after_sale_price)}` : `$${item.after_sale_price.toFixed(2)}`) : '$0',
                        after_compare_price: item.after_compare_price ? `$${Math.round(item.after_compare_price)}` : '$0'
                    };
                });

                rows.value = processedData;

                // If checkbox checked, run compare price update for this collection
                runComparePriceUpdate();
            }
        }).catch((error) => {
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: 'Something went wrong!',
                customClass: 'sweet-alerts'
            });
            updating_cost.value = false;
            showProgress.value = false;
            if (progressPollingInterval.value) {
                clearInterval(progressPollingInterval.value);
                progressPollingInterval.value = null;
            }
            console.error(error);
        });
    } catch (error) {
        console.error('Error al enviar la solicitud:', error);
        updating_cost.value = false;
        showProgress.value = false;
    }
}

/** Run compare price update for current collection (when "Incluir actualización de precios comparables" is checked). */
function runComparePriceUpdate(): Promise<void> {
    if (!collection.value?.id || !includeComparePriceUpdate.value) return Promise.resolve();

    const collectionId = collection.value.id;
    const rounding = comparePriceRoundingOption.value;

    if (comparePriceMethod.value === 'compare_price') {
        const action = comparePriceAction.value;
        const operation = comparePriceOperation.value;
        const price = Number(comparePriceValue.value) || 0;
        if (!action || !operation || price < 0) return Promise.resolve();
        updatingComparePrice.value = true;
        return axios.post('/update/collection/reference_price', {
            collection_id: collectionId,
            action,
            operation,
            price,
            rounding_option: rounding,
            demo: false,
            only_draft: only_draft.value,
        }).then(() => {
            updatingComparePrice.value = false;
            Swal.fire({
                icon: 'success',
                title: 'Precios comparables actualizados',
                text: 'Los precios comparables se actualizaron correctamente para esta colección.',
                showConfirmButton: false,
                timer: 2000,
                toast: true,
                position: 'top-end',
            });
        }).catch((err) => {
            updatingComparePrice.value = false;
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: err?.response?.data?.message || 'Error al actualizar precios comparables.',
            });
        });
    }

    const calculationType = comparePriceCalculationType.value;
    const amount = Number(comparePriceAmount.value) || 0;
    if (!calculationType || amount < 0 || (calculationType === 'discount_based' && amount >= 100)) return Promise.resolve();
    updatingComparePrice.value = true;
    return axios.post('/update/collection/reference_price_from_sale', {
        collection_id: collectionId,
        amount,
        calculation_type: calculationType,
        rounding_option: rounding,
        demo: false,
        only_draft: only_draft.value,
    }).then(() => {
        updatingComparePrice.value = false;
        Swal.fire({
            icon: 'success',
            title: 'Precios comparables actualizados',
            text: 'Los precios comparables se actualizaron correctamente para esta colección.',
            showConfirmButton: false,
            timer: 2000,
            toast: true,
            position: 'top-end',
        });
    }).catch((err) => {
        updatingComparePrice.value = false;
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: err?.response?.data?.message || 'Error al actualizar precios comparables.',
        });
    });
}

function startProgressPolling(progressId: string): void {
    // Reset completion flag when starting new polling
    progressCompletedShown.value = false;

    // Poll function
    const pollProgress = () => {
        // If we already showed completion, don't poll anymore
        if (progressCompletedShown.value) {
            return;
        }

        axios.get('/get/collection/cost_price_progress', {
            params: { progress_id: progressId }
        }).then((response) => {
            if (response.data.status === 200 && response.data.data) {
                const data = response.data.data;
                progressData.value = data;

                // If completed, stop polling and show results (only once)
                if (data.status === 'completed' && !progressCompletedShown.value) {
                    // Set flag first to prevent multiple executions
                    progressCompletedShown.value = true;

                    clearInterval(progressPollingInterval.value);
                    progressPollingInterval.value = null;
                    showProgress.value = false;
                    updating_cost.value = false;

                    Swal.fire({
                        title: 'Cost price updated!',
                        text: `Successfully updated ${response.data.data.processed} variants.${response.data.data.errors > 0 ? ` ${response.data.data.errors} errors occurred.` : ''}`,
                        icon: 'success',
                        customClass: 'sweet-alerts'
                    });

                    // Reload operation logs after update
                    loadLogs();
                    // If checkbox checked, run compare price update for this collection
                    runComparePriceUpdate();
                }
            } else if (response.data.status === 404) {
                // Progress not found - might have expired or completed
                // Only clear if we haven't shown completion already
                if (!progressCompletedShown.value) {
                    clearInterval(progressPollingInterval.value);
                    progressPollingInterval.value = null;
                    showProgress.value = false;
                    updating_cost.value = false;
                }
            }
        }).catch((error) => {
            // Continue polling even on error (unless already completed)
            if (progressCompletedShown.value) {
                clearInterval(progressPollingInterval.value);
                progressPollingInterval.value = null;
            }
        });
    };

    // Poll immediately, then every 1 second
    pollProgress();
    progressPollingInterval.value = setInterval(() => {
        pollProgress();
    }, 1000); // 1 second = 1000ms

    // Stop polling after 10 minutes (safety timeout)
    setTimeout(() => {
        if (progressPollingInterval.value) {
            clearInterval(progressPollingInterval.value);
            progressPollingInterval.value = null;
            showProgress.value = false;
            updating_cost.value = false;
        }
    }, 600000);
}

const showAlert = async (type: number) => {
    if (type === 1) {
        // Validate configuration
        if (!isConfigValid.value) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Configuration',
                text: 'Please check your profit ranges and expenses values.',
                confirmButtonColor: '#3085d6'
            });
            return;
        }

        Swal.fire({
            icon: 'warning',
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            showCancelButton: true,
            confirmButtonText: 'Update cost price',
            padding: '2em',
            customClass: 'sweet-alerts',
        }).then((result) => {
            if (result.value) {
                updateShopify(test_mode_cost.value);
            }
        });
    }
};
</script>

<style scoped>
.form-input:focus {
    border-color: #4361ee;
    box-shadow: 0 0 0 1px #4361ee;
}
</style>
