<template>
    <div>
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Đổ Dầu</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="/">Trang chủ</a></li>
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Quản lý Dầu</a></li>
                    <li class="breadcrumb-item"><router-link :to="{ name: 'FuelRefillList' }">Lịch sử Đổ Dầu
                        </router-link></li>
                    <li class="breadcrumb-item active" aria-current="page">{{ isEditMode ? 'Cập nhật đổ dầu' : 'Đổ dầu mới' }}</li>
                </ol>
            </div>
        </div>

        <!-- Form -->
        <div class="row row-sm">
            <div class="col-lg-12">
                <div class="card shadow-none">
                    <div class="card-header bg-primary text-white">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-gas-pump me-2"></i>
                            {{ isEditMode ? 'Cập nhật thông tin đổ dầu' : 'Ghi nhận đổ dầu' }}
                        </h5>
                    </div>
                    <div class="card-body">
                        <form @submit.prevent="save">
                            <div class="row">
                                <!-- LEFT COLUMN (col-9) -->
                                <div class="col-lg-9">
                                    <!-- 1. Upload hình ảnh -->
                                    <div class="card bg-warning bg-opacity-10 mb-3">
                                        <div class="card-header bg-warning">
                                            <h6 class="mb-0">
                                                <i class="fas fa-camera me-2"></i>Upload Hình Ảnh
                                                <span class="text-danger">(Bắt buộc 4 ảnh)</span>
                                            </h6>
                                        </div>
                                        <div class="card-body">
                                            <!-- Khu vực upload nhiều ảnh -->
                                            <div class="mb-4">
                                                <div 
                                                    class="multi-upload-zone" 
                                                    :class="{ 'dragging': isDragging }"
                                                    @click="triggerMultipleFileInput"
                                                    @drop.prevent="handleDrop"
                                                    @dragover.prevent="handleDragOver"
                                                    @dragleave="isDragging = false">
                                                    <i class="fas fa-cloud-upload-alt fa-3x text-primary mb-3"></i>
                                                    <h6 class="mb-2">Kéo thả hoặc click để chọn ảnh</h6>
                                                    <p class="text-muted mb-0">Tối đa 4 ảnh, mỗi ảnh không quá 5MB</p>
                                                </div>
                                                <input 
                                                    type="file" 
                                                    ref="multipleFileInput" 
                                                    @change="handleMultipleFileSelect"
                                                    accept="image/*" 
                                                    multiple
                                                    style="display: none;">
                                            </div>

                                            <!-- Viewer bao quanh tất cả ảnh -->
                                            <div v-viewer="{navbar: false, title: false, toolbar: true}">
                                                <!-- Ảnh đã chọn (chờ sắp xếp) -->
                                                <div v-if="pendingImages.length > 0" class="mb-4">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-images me-2"></i>Ảnh đã chọn ({{ pendingImages.length }})
                                                        <small class="text-muted">- Click chọn ảnh, sau đó click vào slot bên dưới</small>
                                                    </label>
                                                    <div class="pending-images-grid">
                                                        <div 
                                                            v-for="(img, index) in pendingImages" 
                                                            :key="index"
                                                            class="pending-image-item"
                                                            :class="{ 'selected': selectedPendingImage === index }"
                                                            @dblclick="selectPendingImage(index)"
                                                            draggable="true"
                                                            @dragstart="handleImageDragStart($event, index)">
                                                            <img :src="img.preview" class="pending-image">
                                                            <button 
                                                                type="button" 
                                                                class="btn-remove-pending"
                                                                @click.stop="removePendingImage(index)">
                                                                <i class="fas fa-times"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- 4 Slot ảnh -->
                                                <div>
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-sort-amount-down me-2"></i>Sắp xếp vào các loại ảnh
                                                        <span class="text-danger">*</span>
                                                    </label>
                                                    <div class="row">
                                                        <!-- Slot 1: Ảnh ODO trước -->
                                                        <div class="col-lg-3 col-md-6 mb-3">
                                                            <label class="form-label fw-bold text-center d-block">1. ODO trước</label>
                                                            <div 
                                                                class="image-slot" 
                                                                :class="{ 'has-image': previews[0], 'can-drop': selectedPendingImage !== null }"
                                                                @click="!previews[0] && assignImageToSlot(0)"
                                                                @drop.prevent="handleSlotDrop($event, 0)"
                                                                @dragover.prevent="handleSlotDragOver">
                                                                <img v-if="previews[0]" :src="previews[0]" class="slot-image">
                                                                <div v-else class="slot-placeholder">
                                                                    <i class="fas fa-tachometer-alt fa-2x text-muted mb-2"></i>
                                                                    <p class="mb-0 small">Click hoặc kéo ảnh vào đây</p>
                                                                </div>
                                                            </div>
                                                            <button 
                                                                v-if="previews[0]" 
                                                                type="button"
                                                                class="btn btn-sm btn-danger mt-2 w-100" 
                                                                @click.stop="removeImage(0)">
                                                                <i class="fas fa-trash me-1"></i>Xóa
                                                            </button>
                                                        </div>

                                                        <!-- Slot 2: Ảnh ODO sau -->
                                                        <div class="col-lg-3 col-md-6 mb-3">
                                                            <label class="form-label fw-bold text-center d-block">2. ODO sau</label>
                                                            <div 
                                                                class="image-slot" 
                                                                :class="{ 'has-image': previews[1], 'can-drop': selectedPendingImage !== null }"
                                                                @click="!previews[1] && assignImageToSlot(1)"
                                                                @drop.prevent="handleSlotDrop($event, 1)"
                                                                @dragover.prevent="handleSlotDragOver">
                                                                <img v-if="previews[1]" :src="previews[1]" class="slot-image">
                                                                <div v-else class="slot-placeholder">
                                                                    <i class="fas fa-tachometer-alt fa-2x text-muted mb-2"></i>
                                                                    <p class="mb-0 small">Click hoặc kéo ảnh vào đây</p>
                                                                </div>
                                                            </div>
                                                            <button 
                                                                v-if="previews[1]" 
                                                                type="button"
                                                                class="btn btn-sm btn-danger mt-2 w-100" 
                                                                @click.stop="removeImage(1)">
                                                                <i class="fas fa-trash me-1"></i>Xóa
                                                            </button>
                                                        </div>

                                                        <!-- Slot 3: Ảnh cây dầu -->
                                                        <div class="col-lg-3 col-md-6 mb-3">
                                                            <label class="form-label fw-bold text-center d-block">3. Cây dầu</label>
                                                            <div 
                                                                class="image-slot" 
                                                                :class="{ 'has-image': previews[2], 'can-drop': selectedPendingImage !== null }"
                                                                @click="!previews[2] && assignImageToSlot(2)"
                                                                @drop.prevent="handleSlotDrop($event, 2)"
                                                                @dragover.prevent="handleSlotDragOver">
                                                                <img v-if="previews[2]" :src="previews[2]" class="slot-image">
                                                                <div v-else class="slot-placeholder">
                                                                    <i class="fas fa-gas-pump fa-2x text-muted mb-2"></i>
                                                                    <p class="mb-0 small">Click hoặc kéo ảnh vào đây</p>
                                                                </div>
                                                            </div>
                                                            <button 
                                                                v-if="previews[2]" 
                                                                type="button"
                                                                class="btn btn-sm btn-danger mt-2 w-100" 
                                                                @click.stop="removeImage(2)">
                                                                <i class="fas fa-trash me-1"></i>Xóa
                                                            </button>
                                                        </div>

                                                        <!-- Slot 4: Ảnh hóa đơn -->
                                                        <div class="col-lg-3 col-md-6 mb-3">
                                                            <label class="form-label fw-bold text-center d-block">4. Hóa đơn</label>
                                                            <div 
                                                                class="image-slot" 
                                                                :class="{ 'has-image': previews[3], 'can-drop': selectedPendingImage !== null }"
                                                                @click="!previews[3] && assignImageToSlot(3)"
                                                                @drop.prevent="handleSlotDrop($event, 3)"
                                                                @dragover.prevent="handleSlotDragOver">
                                                                <img v-if="previews[3]" :src="previews[3]" class="slot-image">
                                                                <div v-else class="slot-placeholder">
                                                                    <i class="fas fa-receipt fa-2x text-muted mb-2"></i>
                                                                    <p class="mb-0 small">Click hoặc kéo ảnh vào đây</p>
                                                                </div>
                                                            </div>
                                                            <button 
                                                                v-if="previews[3]" 
                                                                type="button"
                                                                class="btn btn-sm btn-danger mt-2 w-100" 
                                                                @click.stop="removeImage(3)">
                                                                <i class="fas fa-trash me-1"></i>Xóa
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <small class="text-danger fw-bold">
                                                <i class="fas fa-info-circle me-1"></i>
                                                Bắt buộc phải sắp xếp đủ 4 ảnh vào các slot trước khi lưu
                                            </small>
                                        </div>
                                    </div>

                                    <!-- 2. Thông tin cơ bản -->
                                    <div class="card mb-3">
                                        <div class="card-header bg-primary text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-info-circle me-2"></i>Thông tin cơ bản
                                            </h6>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label fw-bold">Xe <span
                                                            class="text-danger">*</span></label>
                                                    <v-select 
                                                        v-model="form.TruckId" 
                                                        :reduce="(option) => option.Id"
                                                        label="LicensePlate" 
                                                        :options="availableTrucks"
                                                        placeholder="-- Chọn xe --"
                                                        :clearable="false"
                                                        @option:selected="onTruckSelected">
                                                        <template #option="truck">
                                                            <div>
                                                                <strong>{{ truck.LicensePlate }}</strong>
                                                                <div class="small text-muted">
                                                                    {{ truck.AgencyName }} - Định mức: {{ truck.FuelQuotaPer100Km }} L/100km
                                                                </div>
                                                            </div>
                                                        </template>
                                                        <template #selected-option="truck">
                                                            {{ truck.LicensePlate }} - {{ truck.AgencyName }} ({{ truck.FuelQuotaPer100Km }} L/100km)
                                                        </template>
                                                    </v-select>
                                                    <small class="text-muted" v-if="selectedTruck">Định mức: {{
                                                        selectedTruck.FuelQuotaPer100Km }} L/100km</small>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Lái xe (tùy chọn)</label>
                                                    <v-select v-model="form.DriverId" :reduce="(option) => option.Id"
                                                        label="UserName" :filterable="false" :options="drivers"
                                                        @search="searchDrivers" placeholder="Mặc định: người dùng hiện tại"
                                                        :clearable="true">
                                                        <template #no-options="{ search, searching, loading }">
                                                            Gõ từ khóa để tìm lái xe...
                                                        </template>
                                                        <template v-slot:option="option">
                                                            {{ option.UserName }} ({{ option.FullName }})
                                                        </template>
                                                        <template v-slot:selected-option="option">
                                                            {{ option.UserName }} ({{ option.FullName }})
                                                        </template>
                                                    </v-select>
                                                    <small class="text-muted">Để trống nếu đổ dầu cho chính mình</small>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label fw-bold">Thời gian đổ dầu <span
                                                            class="text-danger">*</span></label>
                                                    <VueDatePicker v-model="form.RefillTime" placeholder="Chọn thời gian"
                                                        :max-date="new Date()" auto-apply />
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 3. Thông tin ODO và Dầu -->
                                    <div class="card mb-3">
                                        <div class="card-header bg-info text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-tachometer-alt me-2"></i>Thông tin ODO và Dầu
                                            </h6>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label fw-bold">ODO trước đó <span
                                                            class="text-danger">*</span></label>
                                                    <input type="number" class="form-control"
                                                        v-model.number="form.PreviousOdo" placeholder="Nhập ODO trước đó"
                                                        required min="0" @input="calculateDifference">
                                                    <small class="text-muted">Tự động cập nhật khi chọn xe, có thể chỉnh sửa</small>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label fw-bold">ODO hiện tại <span
                                                            class="text-danger">*</span></label>
                                                    <input type="number" class="form-control"
                                                        v-model.number="form.CurrentOdo" placeholder="Nhập ODO hiện tại"
                                                        required min="0" @input="calculateDifference">
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label fw-bold">Số tiền (VND) <span
                                                            class="text-danger">*</span></label>
                                                    <input type="number" class="form-control" v-model.number="form.Amount"
                                                        placeholder="Nhập số tiền" required min="0" step="1"
                                                        @input="calculateDifference">
                                                    <small class="text-muted">{{ formatCurrency(form.Amount) }}</small>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label fw-bold">Đơn giá (VND/lít) <span
                                                            class="text-danger">*</span></label>
                                                    <input type="number" class="form-control"
                                                        v-model.number="form.UnitPrice" placeholder="Nhập đơn giá" required
                                                        min="0" step="1" @input="calculateDifference">
                                                    <small class="text-muted">{{ formatNumber(form.UnitPrice) }}
                                                        VND/lít</small>
                                                </div>
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Km đã chạy</label>
                                                    <input type="text" class="form-control bg-success text-white fw-bold"
                                                        :value="formatNumber(calculated.DistanceKm) + ' km'" readonly>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 4. Phương thức thanh toán -->
                                    <div class="card mb-3">
                                        <div class="card-header bg-success text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-credit-card me-2"></i>Phương thức thanh toán
                                            </h6>
                                        </div>
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label fw-bold">Phương thức <span
                                                            class="text-danger">*</span></label>
                                                    <div class="btn-group w-100" role="group">
                                                        <input type="radio" class="btn-check" id="paymentCard" :value="1"
                                                            v-model="form.PaymentMethod" autocomplete="off">
                                                        <label class="btn btn-outline-primary" for="paymentCard">
                                                            <i class="fas fa-credit-card me-2"></i>Thẻ tín dụng
                                                        </label>

                                                        <input type="radio" class="btn-check" id="paymentCash" :value="2"
                                                            v-model="form.PaymentMethod" autocomplete="off">
                                                        <label class="btn btn-outline-success" for="paymentCash">
                                                            <i class="fas fa-money-bill-wave me-2"></i>Tiền mặt
                                                        </label>
                                                    </div>
                                                </div>

                                                <div class="col-md-6 mb-3" v-if="form.PaymentMethod === 1">
                                                    <label class="form-label fw-bold">Chọn thẻ <span
                                                            class="text-danger">*</span></label>
                                                    <v-select label="CardNumber" :options="fuelCards"
                                                        v-model="form.FuelCardId" :reduce="(option) => option.Id"
                                                        placeholder="Chọn thẻ..."
                                                        :filter-by="(option, label, search) => {
                                                            const searchLower = search.toLowerCase();
                                                            return (option.CardNumber && option.CardNumber.toLowerCase().includes(searchLower)) ||
                                                                   (option.CardholderName && option.CardholderName.toLowerCase().includes(searchLower)) ||
                                                                   (option.BankName && option.BankName.toLowerCase().includes(searchLower)) ||
                                                                   (option.ResponsibleUserName && option.ResponsibleUserName.toLowerCase().includes(searchLower));
                                                        }">
                                                        <template #option="{ CardNumber, CardholderName, BankName, ResponsibleUserName }">
                                                            <div>
                                                                <strong>{{ CardNumber }}</strong>
                                                                <div class="small text-muted">
                                                                    {{ CardholderName }} - {{ BankName }}
                                                                    <span v-if="ResponsibleUserName" class="badge bg-primary ms-1">
                                                                        <i class="fas fa-user me-1"></i>{{ ResponsibleUserName }}
                                                                    </span>
                                                                </div>
                                                            </div>
                                                        </template>
                                                    </v-select>
                                                </div>

                                                <!-- Gợi ý giao dịch chưa đối soát -->
                                                <div class="col-md-12 mb-3" v-if="form.PaymentMethod === 1 && loadingTransactions">
                                                    <div class="text-center text-muted">
                                                        <span class="spinner-border spinner-border-sm me-2"></span>
                                                        Đang tải gợi ý giao dịch...
                                                    </div>
                                                </div>

                                                <div class="col-md-12 mb-3" v-if="form.PaymentMethod === 1 && !loadingTransactions && suggestedTransactions.length > 0">
                                                    <label class="form-label fw-bold">
                                                        <i class="fas fa-lightbulb me-2 text-warning"></i>Gợi ý giao dịch chưa đối soát
                                                    </label>
                                                    <v-select 
                                                        v-model="selectedTransaction" 
                                                        :options="suggestedTransactions"
                                                        :reduce="(option) => option"
                                                        placeholder="-- Chọn giao dịch để tự động điền --"
                                                        :clearable="true"
                                                        @option:selected="onTransactionSelected">
                                                        <template #option="transaction">
                                                            <div>
                                                                <strong>{{ formatCurrency(transaction.Amount) }}</strong>
                                                                <div class="small text-muted">
                                                                    {{ new Date(transaction.TransactionDate).toLocaleString('vi-VN') }} - {{ transaction.Location }}
                                                                </div>
                                                            </div>
                                                        </template>
                                                        <template #selected-option="transaction">
                                                            {{ formatCurrency(transaction.Amount) }} - {{ new Date(transaction.TransactionDate).toLocaleTimeString('vi-VN') }}
                                                        </template>
                                                    </v-select>
                                                    <small class="text-muted">
                                                        <i class="fas fa-info-circle me-1"></i>
                                                        Tìm thấy {{ suggestedTransactions.length }} giao dịch chưa đối soát trong ngày
                                                    </small>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Tên cây xăng</label>
                                                    <input type="text" class="form-control" v-model="form.StationName"
                                                        placeholder="VD: Petrolimex Hải Phòng">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Địa chỉ cây xăng</label>
                                                    <input type="text" class="form-control" v-model="form.StationAddress"
                                                        placeholder="VD: 30 Lạch Tray, Hải Phòng">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- RIGHT COLUMN (col-3) - Sticky Sidebar -->
                                <div class="col-lg-3">
                                    <div class="card mb-3 sticky-sidebar">
                                        <div class="card-header bg-secondary text-white">
                                            <h6 class="mb-0">
                                                <i class="fas fa-calculator me-2"></i>Tính toán
                                            </h6>
                                        </div>
                                        <div class="card-body">

                                            <!-- Định mức xe -->
                                            <div class="mb-3">
                                                <label class="form-label-small">Định mức xe</label>
                                                <input type="text" class="form-control form-control-sm bg-white"
                                                    :value="form.FuelQuotaPer100Km + ' L/100km'" readonly>
                                            </div>

                                            <!-- Lít thực tế -->
                                            <div class="mb-3">
                                                <label class="form-label-small">Lít thực tế</label>
                                                <input type="text"
                                                    class="form-control form-control-sm bg-info text-white fw-bold"
                                                    :value="formatLiters(calculated.ActualLiters)" readonly>
                                                <small class="text-info fw-bold">
                                                    <i class="fas fa-tachometer-alt me-1"></i>
                                                    {{ calculated.ActualConsumptionPer100Km.toFixed(2) }} L/100km
                                                </small>
                                            </div>

                                            <!-- Lít khoán -->
                                            <div class="mb-3">
                                                <label class="form-label-small">Lít khoán</label>
                                                <input type="text"
                                                    class="form-control form-control-sm bg-warning text-dark fw-bold"
                                                    :value="formatLiters(calculated.QuotaLiters)" readonly>
                                            </div>

                                            <!-- Chênh lệch -->
                                            <div class="mb-3">
                                                <label class="form-label-small">Chênh lệch</label>
                                                <input type="text" class="form-control form-control-sm fw-bold"
                                                    :class="getDifferenceInputClass()" :value="getDifferenceText()" readonly>
                                                <small :class="getDifferenceTextClass()">
                                                    {{ getDifferenceMessage() }}
                                                </small>
                                            </div>

                                            <hr>

                                            <!-- Ghi chú -->
                                            <div class="mb-3">
                                                <label class="form-label-small">Ghi chú</label>
                                                <textarea class="form-control form-control-sm" v-model="form.Notes" rows="3"
                                                    placeholder="Nhập ghi chú (tùy chọn)"></textarea>
                                            </div>

                                            <hr>

                                            <!-- Action Buttons -->
                                            <div class="d-grid gap-2">
                                                <button type="button" class="btn btn-success" @click="saveAndReset" :disabled="saving || isEditMode">
                                                    <span v-if="saving && saveAction === 'reset'" class="spinner-border spinner-border-sm me-2"></span>
                                                    <i v-else class="fas fa-redo me-2"></i>
                                                    {{ (saving && saveAction === 'reset') ? 'Đang lưu...' : 'Lưu' }}
                                                </button>
                                                <button type="submit" class="btn btn-primary" :disabled="saving">
                                                    <span v-if="saving && saveAction === 'goBack'" class="spinner-border spinner-border-sm me-2"></span>
                                                    <i v-else class="fas fa-save me-2"></i>
                                                    {{ (saving && saveAction === 'goBack') ? 'Đang lưu...' : 'Lưu và quay lại' }}
                                                </button>
                                                <button type="button" class="btn btn-secondary" @click="goBack"
                                                    :disabled="saving">
                                                    <i class="fas fa-arrow-left me-2"></i>Quay lại
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import fuelCardService from '@/services/fuelCardService';
import truckService from '@/services/truckService';
import staffService from '@/services/staffService';
import { useToast } from 'vue-toastification';
import VueDatePicker from '@vuepic/vue-datepicker';
import _ from 'lodash';

const router = useRouter();
const route = useRoute();
const toast = useToast();

//#region DATA
const saving = ref(false);
const loading = ref(false);
const loadingTrucks = ref(false);
const availableTrucks = ref([]);
const fuelCards = reactive([]);
const selectedTruck = ref(null);
const isEditMode = ref(false);
const refillId = ref(0);

const form = reactive({
    Id: 0, // NEW: 0 = create, >0 = update
    TruckId: null,
    DriverId: null, // NEW: Optional driver ID for entering refill on behalf of another driver
    FuelCardId: null,
    CurrentOdo: 0,
    PreviousOdo: 0,
    Amount: 0,
    UnitPrice: 0,
    PaymentMethod: 1,
    StationName: '',
    StationAddress: '',
    RefillTime: new Date(),
    Notes: '',
    FuelQuotaPer100Km: 0,
    Files: [null, null, null, null],
    MediaTypes: [10, 11, 12, 13]
});

// Track existing media IDs for update optimization
const existingMediaIds = reactive([0, 0, 0, 0]); // 0 = new upload, >0 = keep existing

const drivers = reactive([]); // NEW: List of drivers for v-select

// Suggested transactions for auto-fill
const suggestedTransactions = ref([]);
const selectedTransaction = ref(null);
const loadingTransactions = ref(false);

// Image management
const previews = reactive([null, null, null, null]);
const pendingImages = ref([]); // Ảnh chờ sắp xếp vào slot
const selectedPendingImage = ref(null); // Index của ảnh đang được chọn từ pending
const isDragging = ref(false); // Trạng thái khi drag file vào upload zone
const multipleFileInput = ref(null); // Ref cho input file multiple
const saveAction = ref('goBack'); // 'goBack' hoặc 'reset' - hành động sau khi lưu thành công

const calculated = computed(() => {
    const distanceKm = form.CurrentOdo - form.PreviousOdo;
    const actualLiters = form.Amount > 0 && form.UnitPrice > 0 ? form.Amount / form.UnitPrice : 0;
    const quotaLiters = distanceKm > 0 && form.FuelQuotaPer100Km > 0 
        ? (distanceKm * form.FuelQuotaPer100Km) / 100 
        : 0;
    const differenceLiters = quotaLiters - actualLiters;
    
    // Calculate actual consumption per 100km
    const actualConsumptionPer100Km = distanceKm > 0 && actualLiters > 0
        ? (actualLiters / distanceKm) * 100
        : 0;

    return {
        DistanceKm: distanceKm >= 0 ? distanceKm : 0,
        ActualLiters: actualLiters >= 0 ? actualLiters : 0,
        QuotaLiters: quotaLiters >= 0 ? quotaLiters : 0,
        DifferenceLiters: differenceLiters,
        ActualConsumptionPer100Km: actualConsumptionPer100Km >= 0 ? actualConsumptionPer100Km : 0
    };
});
//#endregion

//#region LIFECYCLE
onMounted(async () => {
    // Check if we're in edit mode
    const id = route.params.id;
    if (id && parseInt(id) > 0) {
        isEditMode.value = true;
        refillId.value = parseInt(id);
        form.Id = parseInt(id);
    }

    await Promise.all([
        loadAvailableTrucks(),
        loadActiveFuelCards()
    ]);

    // Load refill data if in edit mode
    if (isEditMode.value) {
        await loadRefillData();
    }
});

// Watch for changes in FuelCardId and RefillTime to load suggested transactions
watch([() => form.FuelCardId, () => form.RefillTime], async ([cardId, refillTime]) => {
    if (cardId && refillTime && form.PaymentMethod === 1) {
        await loadUnreconciledTransactions(cardId, refillTime);
    } else {
        suggestedTransactions.value = [];
        selectedTransaction.value = null;
    }
});
//#endregion

//#region FUNCTIONS
function formatNumber(value) {
    if (value == null || value == undefined) return '0';
    return new Intl.NumberFormat('vi-VN').format(value);
}

function formatCurrency(value) {
    if (value == null || value == undefined || value === 0) return '0 ₫';
    return new Intl.NumberFormat('vi-VN', {
        style: 'currency',
        currency: 'VND'
    }).format(value);
}

function formatLiters(value) {
    if (value == null || value == undefined) return '0.00 L';
    return `${parseFloat(value).toFixed(2)} L`;
}

async function loadAvailableTrucks() {
    loadingTrucks.value = true;
    try {
        const result = await truckService.getTrucksByAgency();

        // Kiểm tra các cấu trúc response có thể có
        let trucks = [];
        if (result != null) {
            if (Array.isArray(result)) {
                trucks = result;
            } else if (result.Items && Array.isArray(result.Items)) {
                trucks = result.Items;
            } else if (result.Data && Array.isArray(result.Data)) {
                trucks = result.Data;
            } else if (result.Result && Array.isArray(result.Result)) {
                trucks = result.Result;
            }
        }

        availableTrucks.value = trucks;
    } catch (error) {
        console.error('Error loading trucks by agency:', error);
        availableTrucks.value = [];
    } finally {
        loadingTrucks.value = false;
    }
}

async function onTruckSelected() {
    const truck = availableTrucks.value.find(t => t.Id === form.TruckId);
    if (truck) {
        selectedTruck.value = truck;
        form.FuelQuotaPer100Km = truck.FuelQuotaPer100Km || 0;
        
        // Load PreviousOdo from last refill via API
        try {
            const odoInfo = await truckService.getLastRefillOdo(form.TruckId);
            if (odoInfo && odoInfo.LastRefillOdo !== null && odoInfo.LastRefillOdo !== undefined) {
                form.PreviousOdo = odoInfo.LastRefillOdo;
            } else {
                form.PreviousOdo = 0;
            }
        } catch (error) {
            console.error('Error loading last refill ODO:', error);
            form.PreviousOdo = 0;
        }
        
        calculateDifference();
    }
}

async function loadActiveFuelCards() {
    try {
        const result = await fuelCardService.getActiveCards();
        if (result && result.length > 0) {
            fuelCards.splice(0, fuelCards.length);
            result.forEach(card => {
                fuelCards.push(card);
            });
        }
    } catch (error) {
        console.error('Error loading fuel cards:', error);
    }
}

const searchDrivers = async (keyword, loading) => {
    if (keyword && keyword.length > 0) {
        loading(true);
        await searchDriversDebounce(loading, keyword);
    }
};

const searchDriversDebounce = _.debounce(async (loading, keyword) => {
    drivers.splice(0, drivers.length);
    
    try {
        const result = await staffService.sugDriver(keyword);
        if (result != null && result.length > 0) {
            result.forEach(driver => {
                drivers.push(driver);
            });
        }
    } catch (error) {
        console.error('Error searching drivers:', error);
    } finally {
        loading(false);
    }
}, 500);

async function loadUnreconciledTransactions(fuelCardId, date) {
    loadingTransactions.value = true;
    try {
        const transactions = await fuelCardService.getUnreconciledTransactions(fuelCardId, date);
        suggestedTransactions.value = transactions || [];
    } catch (error) {
        console.error('Error loading unreconciled transactions:', error);
        suggestedTransactions.value = [];
    } finally {
        loadingTransactions.value = false;
    }
}

function onTransactionSelected(transaction) {
    if (!transaction) {
        selectedTransaction.value = null;
        return;
    }
    
    selectedTransaction.value = transaction;
    
    // Auto-fill Amount
    form.Amount = transaction.Amount;
    
    // Parse station name and address from Location
    // Format: "PLX_HAI PHONG_CH 30 - HAI PHONG - VNM;Vietnam"
    if (transaction.Location) {
        const locationParts = transaction.Location.split(' - ');
        if (locationParts.length > 0) {
            form.StationName = locationParts[0].replace(/_/g, ' ').trim();
        }
        if (locationParts.length > 1) {
            form.StationAddress = locationParts[1].trim();
        }
    }
    
    // Recalculate difference
    calculateDifference();
    
    toast.info(`Đã điền thông tin từ giao dịch ${formatCurrency(transaction.Amount)}`);
}

function calculateDifference() {
    // Calculation is done automatically via computed property
}

function getDifferenceCardClass() {
    if (calculated.value.DifferenceLiters > 0) {
        return 'border-success';
    } else if (calculated.value.DifferenceLiters < 0) {
        return 'border-danger';
    }
    return 'border-secondary';
}

function getDifferenceInputClass() {
    if (calculated.value.DifferenceLiters > 0) {
        return 'bg-success text-white';
    } else if (calculated.value.DifferenceLiters < 0) {
        return 'bg-danger text-white';
    }
    return 'bg-secondary text-white';
}

function getDifferenceTextClass() {
    if (calculated.value.DifferenceLiters > 0) {
        return 'text-success fw-bold';
    } else if (calculated.value.DifferenceLiters < 0) {
        return 'text-danger fw-bold';
    }
    return 'text-muted';
}

function getDifferenceText() {
    const diff = calculated.value.DifferenceLiters;
    const icon = diff > 0 ? '↑' : diff < 0 ? '↓' : '';
    return `${icon} ${formatLiters(Math.abs(diff))}`;
}

function getDifferenceMessage() {
    const diff = calculated.value.DifferenceLiters;
    if (diff > 0) {
        return '✓ Lái xe được hưởng (tiết kiệm dầu)';
    } else if (diff < 0) {
        return '✗ Lái xe phải bù (dùng nhiều dầu hơn định mức)';
    }
    return 'Không có chênh lệch';
}

// ============ MULTIPLE FILE UPLOAD FUNCTIONS ============

function triggerMultipleFileInput() {
    multipleFileInput.value?.click();
}

function handleMultipleFileSelect(event) {
    const files = Array.from(event.target.files || []);
    processFiles(files);
    // Reset input
    if (multipleFileInput.value) {
        multipleFileInput.value.value = '';
    }
}

function handleDrop(event) {
    isDragging.value = false;
    const files = Array.from(event.dataTransfer.files || []);
    processFiles(files);
}

function handleDragOver(event) {
    isDragging.value = true;
}

function processFiles(files) {
    // Lọc chỉ lấy file ảnh
    const imageFiles = files.filter(file => file.type.startsWith('image/'));
    
    if (imageFiles.length === 0) {
        toast.warning('Không tìm thấy file ảnh nào');
        return;
    }
    
    // Kiểm tra số lượng ảnh tối đa
    const currentTotal = pendingImages.value.length + previews.filter(p => p !== null).length;
    const availableSlots = 4 - currentTotal;
    
    if (availableSlots <= 0) {
        toast.warning('Đã đủ 4 ảnh. Vui lòng xóa bớt ảnh nếu muốn thêm mới.');
        return;
    }
    
    const filesToAdd = imageFiles.slice(0, availableSlots);
    
    if (imageFiles.length > availableSlots) {
        toast.info(`Chỉ thêm được ${availableSlots} ảnh (đã chọn ${imageFiles.length} ảnh)`);
    }
    
    // Validate và thêm vào pending
    filesToAdd.forEach(file => {
        // Validate file size (max 5MB)
        if (file.size > 5 * 1024 * 1024) {
            toast.error(`File ${file.name} quá lớn (max 5MB)`);
            return;
        }
        
        // Create preview
        const reader = new FileReader();
        reader.onload = (e) => {
            pendingImages.value.push({
                file: file,
                preview: e.target.result
            });
        };
        reader.readAsDataURL(file);
    });
    
    toast.success(`Đã thêm ${filesToAdd.length} ảnh. Vui lòng sắp xếp vào các slot.`);
}

// ============ PENDING IMAGE MANAGEMENT ============

function selectPendingImage(index) {
    if (selectedPendingImage.value === index) {
        selectedPendingImage.value = null; // Deselect
    } else {
        selectedPendingImage.value = index;
    }
}

function removePendingImage(index) {
    pendingImages.value.splice(index, 1);
    if (selectedPendingImage.value === index) {
        selectedPendingImage.value = null;
    } else if (selectedPendingImage.value !== null && selectedPendingImage.value > index) {
        selectedPendingImage.value--;
    }
}

// ============ DRAG & DROP TO SLOT ============

function handleImageDragStart(event, imageIndex) {
    event.dataTransfer.effectAllowed = 'move';
    event.dataTransfer.setData('imageIndex', imageIndex.toString());
}

function handleSlotDragOver(event) {
    event.dataTransfer.dropEffect = 'move';
}

function handleSlotDrop(event, slotIndex) {
    const imageIndex = parseInt(event.dataTransfer.getData('imageIndex'));
    if (imageIndex >= 0 && imageIndex < pendingImages.value.length) {
        assignPendingImageToSlot(imageIndex, slotIndex);
    }
}

// ============ ASSIGN IMAGE TO SLOT ============

function assignImageToSlot(slotIndex) {
    if (selectedPendingImage.value === null) {
        toast.info('Vui lòng chọn một ảnh từ danh sách "Ảnh đã chọn" trước');
        return;
    }
    
    assignPendingImageToSlot(selectedPendingImage.value, slotIndex);
}

function assignPendingImageToSlot(pendingIndex, slotIndex) {
    const pendingImage = pendingImages.value[pendingIndex];
    if (!pendingImage) return;
    
    // Nếu slot đã có ảnh, trả ảnh cũ về pending
    if (previews[slotIndex] && form.Files[slotIndex]) {
        pendingImages.value.push({
            file: form.Files[slotIndex],
            preview: previews[slotIndex]
        });
    }
    
    // Gán ảnh mới vào slot
    form.Files[slotIndex] = pendingImage.file;
    previews[slotIndex] = pendingImage.preview;
    
    // Xác định media type dựa vào slot
    const mediaTypes = [10, 11, 12, 13]; // ODO trước, ODO sau, Cây dầu, Hóa đơn
    form.MediaTypes[slotIndex] = mediaTypes[slotIndex];
    
    // In edit mode, mark this position as needing new upload
    if (isEditMode.value) {
        existingMediaIds[slotIndex] = 0;
    }
    
    // Xóa ảnh khỏi pending
    pendingImages.value.splice(pendingIndex, 1);
    
    // Reset selection
    selectedPendingImage.value = null;
    
    const slotNames = ['ODO trước', 'ODO sau', 'Cây dầu', 'Hóa đơn'];
    toast.success(`Đã gán ảnh vào slot "${slotNames[slotIndex]}"`);
}

// ============ REMOVE IMAGE FROM SLOT ============

function removeImage(index) {
    // Nếu có ảnh trong slot, trả về pending (trừ khi là ảnh từ edit mode)
    if (previews[index] && form.Files[index]) {
        // Chỉ trả về pending nếu không phải ảnh cũ từ edit mode
        if (!isEditMode.value || existingMediaIds[index] === 0) {
            pendingImages.value.push({
                file: form.Files[index],
                preview: previews[index]
            });
        }
    }
    
    form.Files[index] = null;
    previews[index] = null;
    
    // In edit mode, mark this position as needing new upload
    if (isEditMode.value) {
        existingMediaIds[index] = 0;
    }
}

async function save() {
    // Set saveAction to 'goBack' if not already set by saveAndReset
    if (saveAction.value !== 'reset') {
        saveAction.value = 'goBack';
    }
    
    // Validation
    if (!form.TruckId) {
        toast.warning('Vui lòng chọn xe');
        return;
    }

    if (form.PreviousOdo <= 0) {
        toast.warning('Vui lòng nhập ODO trước đó');
        return;
    }

    if (form.CurrentOdo <= 0) {
        toast.warning('Vui lòng nhập ODO hiện tại');
        return;
    }

    if (form.CurrentOdo < form.PreviousOdo) {
        toast.warning(`ODO hiện tại (${formatNumber(form.CurrentOdo)}) phải lớn hơn hoặc bằng ODO trước đó (${formatNumber(form.PreviousOdo)})`);
        return;
    }

    if (form.Amount <= 0) {
        toast.warning('Vui lòng nhập số tiền');
        return;
    }

    if (form.UnitPrice <= 0) {
        toast.warning('Vui lòng nhập đơn giá');
        return;
    }

    if (form.PaymentMethod === 1 && !form.FuelCardId) {
        toast.warning('Vui lòng chọn thẻ khi thanh toán bằng thẻ tín dụng');
        return;
    }

    // Check images: For create mode, all 4 required. For update mode, at least keep existing or upload new
    if (isEditMode.value) {
        // In edit mode: check if we have at least one image (existing or new)
        const hasImages = existingMediaIds.some(id => id > 0) || form.Files.some(f => f !== null);
        if (!hasImages) {
            toast.warning('Vui lòng giữ lại hoặc upload ít nhất 1 ảnh');
            return;
        }
    } else {
        // In create mode: all 4 images required
        const uploadedCount = form.Files.filter(f => f !== null).length;
        if (uploadedCount < 4) {
            toast.warning(`Vui lòng upload đủ 4 ảnh (hiện tại: ${uploadedCount}/4)`);
            return;
        }
    }

    saving.value = true;
    try {
        // Create FormData
        const formData = new FormData();
        formData.append('Id', form.Id); // 0 = create, >0 = update
        formData.append('TruckId', form.TruckId);
        
        // Add DriverId if selected (for entering refill on behalf of another driver)
        if (form.DriverId) {
            formData.append('DriverId', form.DriverId);
        }
        
        if (form.FuelCardId) {
            formData.append('FuelCardId', form.FuelCardId);
        }
        
        // Add FuelCardTransactionId if a transaction was selected (for auto-reconciliation)
        if (selectedTransaction.value && selectedTransaction.value.Id) {
            formData.append('FuelCardTransactionId', selectedTransaction.value.Id);
        }
        
        formData.append('PreviousOdo', form.PreviousOdo);
        formData.append('CurrentOdo', form.CurrentOdo);
        formData.append('Amount', form.Amount);
        formData.append('UnitPrice', form.UnitPrice);
        formData.append('PaymentMethod', form.PaymentMethod);
        formData.append('RefillTime', form.RefillTime.toISOString());
        
        if (form.StationName) {
            formData.append('StationName', form.StationName);
        }
        if (form.StationAddress) {
            formData.append('StationAddress', form.StationAddress);
        }
        if (form.Notes) {
            formData.append('Notes', form.Notes);
        }

        // Append files and media types based on mode
        if (isEditMode.value) {
            // Update mode: always send ExistingMediaIds to preserve existing images
            // Append ExistingMediaIds array
            existingMediaIds.forEach(mediaId => {
                formData.append('ExistingMediaIds', mediaId);
            });
            
            // Append only new files (where existingMediaIds[index] === 0)
            form.Files.forEach((file, index) => {
                if (file) {
                    formData.append('Files', file);
                    formData.append('MediaTypes', form.MediaTypes[index]);
                }
            });
        } else {
            // Create mode: append all files
            form.Files.forEach((file, index) => {
                if (file) {
                    formData.append('Files', file);
                    formData.append('MediaTypes', form.MediaTypes[index]);
                }
            });
        }

        const result = await fuelCardService.createOrUpdateRefill(formData);
        if (result && result.Result === 1) {
            toast.success(result.Message || (isEditMode.value ? 'Cập nhật thông tin đổ dầu thành công' : 'Đổ dầu thành công'));
            
            // Xử lý theo saveAction
            if (saveAction.value === 'reset') {
                resetForm();
            } else {
                goBack();
            }
        } else {
            toast.error(result.Message || 'Không thể lưu thông tin đổ dầu');
        }
    } catch (error) {
        console.error('Error saving refill:', error);
        toast.error('Có lỗi xảy ra khi lưu thông tin đổ dầu');
    } finally {
        saving.value = false;
    }
}

function saveAndReset() {
    saveAction.value = 'reset';
    save();
}

function resetForm() {
    // Reset form data
    form.Id = 0;
    form.TruckId = null;
    form.DriverId = null;
    form.FuelCardId = null;
    form.PreviousOdo = 0;
    form.CurrentOdo = 0;
    form.Amount = 0;
    form.UnitPrice = 0;
    form.PaymentMethod = 2; // Default to cash
    form.StationName = '';
    form.StationAddress = '';
    form.RefillTime = new Date();
    form.Notes = '';
    form.FuelQuotaPer100Km = 0;
    form.Files = [null, null, null, null];
    form.MediaTypes = [10, 11, 12, 13];
    
    // Reset previews
    previews[0] = null;
    previews[1] = null;
    previews[2] = null;
    previews[3] = null;
    
    // Reset pending images
    pendingImages.value = [];
    selectedPendingImage.value = null;
    
    // Reset selections
    selectedTruck.value = null;
    selectedDriver.value = null;
    selectedCard.value = null;
    selectedTransaction.value = null;
    
    // Reset saveAction back to default
    saveAction.value = 'goBack';
    
    toast.info('Form đã được reset. Bạn có thể nhập đổ dầu mới.');
}

async function loadRefillData() {
    loading.value = true;
    try {
        const data = await fuelCardService.getRefillById(refillId.value);
        if (data) {
            // Populate form with existing data
            form.TruckId = data.TruckId;
            form.DriverId = data.DriverId;
            form.FuelCardId = data.FuelCardId;
            form.CurrentOdo = data.CurrentOdo;
            form.PreviousOdo = data.PreviousOdo;
            form.Amount = data.Amount;
            form.UnitPrice = data.UnitPrice;
            form.PaymentMethod = data.PaymentMethod;
            form.StationName = data.StationName || '';
            form.StationAddress = data.StationAddress || '';
            form.RefillTime = new Date(data.RefillTime);
            form.Notes = data.Notes || '';
            form.FuelQuotaPer100Km = data.FuelQuotaPer100Km;

            // Find and set selected truck
            const truck = availableTrucks.value.find(t => t.Id === data.TruckId);
            if (truck) {
                selectedTruck.value = truck;
            }

            // If DriverId exists, create a driver option from API data to avoid v-select error
            if (data.DriverId && data.DriverId > 0) {
                const driverOption = {
                    Id: data.DriverId,
                    UserName: data.DriverName || '',
                    FullName: data.DriverFullName || ''
                };
                drivers.push(driverOption);
            }

            // Load existing media items and display previews
            if (data.MediaItems && data.MediaItems.length > 0) {
                data.MediaItems.forEach((media, index) => {
                    if (index < 4) {
                        existingMediaIds[index] = media.Id;
                        previews[index] = media.MediaUrl;
                    }
                });
                //toast.success('Đã tải thông tin đổ dầu. Bạn có thể giữ nguyên hoặc thay đổi ảnh.');
            } else {
                toast.info('Lưu ý: Bạn cần upload lại 4 ảnh khi cập nhật thông tin đổ dầu');
            }

            // Load selected transaction if exists (for reconciled refills)
            if (data.FuelCardTransactionId) {
                try {
                    const transaction = await fuelCardService.getTransactionById(data.FuelCardTransactionId);
                    if (transaction) {
                        selectedTransaction.value = transaction;
                        // Add the selected transaction to the suggestions list so it appears in dropdown
                        suggestedTransactions.value = [transaction];
                    }
                } catch (error) {
                    console.error('Error loading transaction details:', error);
                    // Don't show error to user, just log it
                }
            }

            // Load suggested transactions for the dropdown (if payment method is Card)
            if (form.PaymentMethod === 1 && form.FuelCardId && form.RefillTime) {
                await loadUnreconciledTransactions(form.FuelCardId, form.RefillTime);
                
                // If there was a previously selected transaction, make sure it's in the list
                if (selectedTransaction.value) {
                    const existsInList = suggestedTransactions.value.some(t => t.Id === selectedTransaction.value.Id);
                    if (!existsInList) {
                        // Add the selected transaction at the beginning of the list
                        suggestedTransactions.value = [selectedTransaction.value, ...suggestedTransactions.value];
                    }
                }
            }
        } else {
            toast.error('Không tìm thấy thông tin đổ dầu');
            goBack();
        }
    } catch (error) {
        console.error('Error loading refill data:', error);
        toast.error('Có lỗi xảy ra khi tải thông tin đổ dầu');
        goBack();
    } finally {
        loading.value = false;
    }
}

function goBack() {
    router.push({ name: 'FuelRefillList' });
}
//#endregion
</script>

<style scoped>
/* ============ STICKY SIDEBAR ============ */
.sticky-sidebar {
    position: sticky;
    top: 20px;
    max-height: calc(100vh - 40px);
    overflow-y: auto;
}

/* ============ FORM LABELS ============ */
.form-label-small {
    font-size: 0.75rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
    text-transform: uppercase;
    color: #6c757d;
    display: block;
}

.form-label {
    font-weight: 500;
}

.fw-bold {
    font-weight: 600 !important;
}

/* ============ FORM CONTROLS ============ */
.form-control-sm {
    font-size: 0.875rem;
    padding: 0.25rem 0.5rem;
}

.card {
    border-width: 2px;
}

/* ============ MULTI-UPLOAD ZONE ============ */
.multi-upload-zone {
    border: 3px dashed #dee2e6;
    border-radius: 12px;
    padding: 40px 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    min-height: 150px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.multi-upload-zone:hover {
    border-color: #0d6efd;
    background: linear-gradient(135deg, #e7f1ff 0%, #cfe2ff 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(13, 110, 253, 0.15);
}

.multi-upload-zone.dragging {
    border-color: #198754;
    background: linear-gradient(135deg, #d1e7dd 0%, #a3cfbb 100%);
    transform: scale(1.02);
    box-shadow: 0 6px 20px rgba(25, 135, 84, 0.2);
}

/* ============ PENDING IMAGES GRID ============ */
.pending-images-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 15px;
    margin-top: 10px;
}

.pending-image-item {
    position: relative;
    border: 3px solid #dee2e6;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s ease;
    aspect-ratio: 1;
    background-color: #f8f9fa;
}

.pending-image-item:hover {
    border-color: #0d6efd;
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.pending-image-item.selected {
    border-color: #198754;
    border-width: 4px;
    box-shadow: 0 0 0 3px rgba(25, 135, 84, 0.2);
    transform: scale(1.05);
}

.pending-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

.btn-remove-pending {
    position: absolute;
    top: 5px;
    right: 5px;
    background-color: rgba(220, 53, 69, 0.9);
    color: white;
    border: none;
    border-radius: 50%;
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
    font-size: 14px;
    padding: 0;
}

.btn-remove-pending:hover {
    background-color: rgba(220, 53, 69, 1);
    transform: scale(1.1);
}

/* ============ IMAGE SLOTS ============ */
.image-slot {
    border: 3px dashed #dee2e6;
    border-radius: 8px;
    padding: 10px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    min-height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f9fa;
    position: relative;
}

.image-slot:hover {
    border-color: #0d6efd;
    background-color: #e7f1ff;
    transform: translateY(-2px);
}

.image-slot.has-image {
    border-style: solid;
    border-color: #198754;
    background-color: #d1e7dd;
}

.image-slot.can-drop {
    animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
    0%, 100% {
        border-color: #0d6efd;
        box-shadow: 0 0 0 0 rgba(13, 110, 253, 0.4);
    }
    50% {
        border-color: #0a58ca;
        box-shadow: 0 0 0 8px rgba(13, 110, 253, 0);
    }
}

.slot-placeholder {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #6c757d;
}

.slot-image {
    max-width: 100%;
    max-height: 180px;
    border-radius: 4px;
    object-fit: cover;
}

/* ============ RESPONSIVE ============ */
@media (max-width: 992px) {
    .sticky-sidebar {
        position: relative;
        top: 0;
        max-height: none;
    }
    
    .pending-images-grid {
        grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    }
}

@media (max-width: 576px) {
    .multi-upload-zone {
        padding: 30px 15px;
        min-height: 120px;
    }
    
    .pending-images-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .image-slot {
        min-height: 150px;
    }
}
</style>

