<script setup>
import { toast } from 'bulma-toast'
import { SelectBox } from 'tedir-select'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  organizations: {
    type: Array,
    default: () => []
  },
  orderSources: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'ordersImported'])

const isOpen = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// Get user's current organization from cookie
const organizationIdCookie = useCookie('logship_organization_id')

// Form state
const form = ref({
  organizationId: organizationIdCookie.value || '',
  orderSourceId: '',
  marketplace: 'ebay',
  docStatus: 'CO', // Default to Completed
  csvFile: null,
  csvFileName: ''
})

// Document status options
const docStatusOptions = [
  { value: 'CO', label: 'Completed' },
  { value: 'DR', label: 'Draft' }
]

// Sort order sources by name
const sortedOrderSources = computed(() => {
  if (!props.orderSources) return []
  return [...props.orderSources].sort((a, b) => {
    const nameA = (a.Name || a.identifier || a.name || '').toLowerCase()
    const nameB = (b.Name || b.identifier || b.name || '').toLowerCase()
    return nameA.localeCompare(nameB)
  })
})

// Watch for order source changes to fetch its details
watch(() => form.value.orderSourceId, async (newOrderSourceId) => {
  if (newOrderSourceId) {
    try {
      const res = await $fetch(`/api/settings/order-sources/${newOrderSourceId}`, {
        headers: useRequestHeaders(['cookie'])
      })
      selectedOrderSource.value = res
      console.log('Selected order source:', res)
      console.log('Marketplace:', res?.Marketplace?.identifier)
    } catch (error) {
      console.error('Error fetching order source:', error)
      selectedOrderSource.value = null
    }
  } else {
    selectedOrderSource.value = null
  }
})

// Step tracking: 'upload' | 'preview' | 'importing' | 'done'
const currentStep = ref('upload')
const loading = ref(false)
const importResult = ref(null)

// Parsed CSV data
const parsedOrders = ref([])
const editingRowIndex = ref(null)

// Selected order source details (includes pricelist info)
const selectedOrderSource = ref(null)

// Product search
const productOptions = ref([])
const loadingProducts = ref(false)

// Sort organizations by name
const sortedOrganizations = computed(() => {
  if (!props.organizations) return []
  return [...props.organizations].sort((a, b) => {
    const nameA = (a.Name || a.identifier || a.name || '').toLowerCase()
    const nameB = (b.Name || b.identifier || b.name || '').toLowerCase()
    return nameA.localeCompare(nameB)
  })
})

// Marketplace options
const marketplaceOptions = [
  { value: 'ebay', label: 'eBay' },
  { value: 'temu', label: 'Temu' },
  { value: 'amazon', label: 'Amazon' }
]

// Detect marketplace from selected order source
const detectedMarketplace = computed(() => {
  if (!selectedOrderSource.value) return null
  const identifier = (selectedOrderSource.value?.Marketplace?.identifier || '').toLowerCase()
  if (identifier.includes('ebay')) return 'ebay'
  if (identifier.includes('temu')) return 'temu'
  if (identifier.includes('amazon')) return 'amazon'
  return null
})

// Marketplace color for badge
const marketplaceColor = computed(() => {
  switch (detectedMarketplace.value) {
    case 'ebay': return { bg: '#e8f0fe', color: '#1a73e8', border: '#1a73e8', label: 'eBay' }
    case 'temu': return { bg: '#fef3e8', color: '#e8760a', border: '#e8760a', label: 'Temu' }
    case 'amazon': return { bg: '#fff3e0', color: '#ff9900', border: '#ff9900', label: 'Amazon' }
    default: return null
  }
})

// Effective marketplace: from order source if detected, otherwise from manual selection
const effectiveMarketplace = computed(() => {
  return detectedMarketplace.value || form.value.marketplace
})

// CSV field mappings for eBay (German column names)
const ebayFieldMappings = {
  orderNumber: 'Bestellnummer',
  salesProtocolNumber: 'Verkaufsprotokollnummer',
  buyerUsername: 'Nutzername des Käufers',
  buyerName: 'Name des Käufers',
  buyerEmail: 'E-Mail des Käufers',
  buyerNote: 'Hinweis des Käufers',
  buyerAddress1: 'Adresse 1 des Käufers',
  buyerAddress2: 'Adresse 2 des Käufers',
  buyerCity: 'Wohnort des Käufers',
  buyerState: 'Bundesland des Käufers',
  buyerPostal: 'PLZ des Käufers',
  buyerCountry: 'Land des Käufers',
  recipientName: 'Name des Empfängers',
  recipientPhone: 'Telefonnummer des Empfängers',
  shipAddress1: 'Adresse 1 des Empfängers',
  shipAddress2: 'Adresse 2 des Empfängers',
  shipCity: 'Versand nach - Ort',
  shipState: 'Versand nach - Bundesland',
  shipPostal: 'Versand nach - PLZ',
  shipCountry: 'Versand nach - Land',
  itemNumber: 'Artikelnummer',
  itemTitle: 'Angebotstitel',
  sku: 'Bestandseinheit',
  quantity: 'Anzahl',
  soldFor: 'Verkauft für',
  shippingCost: 'Verpackung und Versand',
  grandTotal: 'Gesamtbetrag',
  soldDate: 'Verkauft am',
  paymentDate: 'Zahlungsdatum',
  transactionId: 'Transaktionsnummer',
  variantDetails: 'Variantendetails',
  shippingService: 'Versandservice',
  trackingNumber: 'Sendungsnummer'
}

// CSV field mappings for Temu (English column names, comma separated)
const temuFieldMappings = {
  orderNumber: 'Order ID',
  orderStatus: 'order status',
  orderItemId: 'Order item ID',
  productName: 'product name',
  variation: 'variation',
  sku: 'contribution sku',
  skuId: 'SKU ID',
  quantity: 'quantity purchased',
  recipientName: 'recipient name',
  recipientFirstName: 'recipient first name',
  recipientLastName: 'recipient last name',
  recipientPhone: 'recipient phone number',
  shipAddress1: 'ship address 1',
  shipAddress2: 'ship address 2',
  shipAddress3: 'ship address 3',
  district: 'district',
  shipCity: 'ship city',
  shipState: 'ship state',
  shipPostal: 'ship postal code (Must be shipped to the following zip code.)',
  shipCountry: 'ship country',
  buyerEmail: 'virtual email',
  purchaseDate: 'purchase date',
  soldFor: 'goods base price',
  grandTotal: 'Base price total  after discount',
  basePriceTotal: 'Base price total',
  trackingNumber: 'tracking number',
  carrier: 'carrier'
}

// CSV field mappings for Amazon (tab-separated, English column names)
// Supports both "Unshipped Orders" (no prices) and "Order Report" (with prices) formats
const amazonFieldMappings = {
  orderNumber: 'order-id',
  orderItemId: 'order-item-id',
  purchaseDate: 'purchase-date',
  paymentsDate: 'payments-date',
  promiseDate: 'promise-date',
  buyerEmail: 'buyer-email',
  buyerName: 'buyer-name',
  buyerPhone: 'buyer-phone-number',
  sku: 'sku',
  productName: 'product-name',
  quantity: 'quantity-purchased',
  quantityShipped: 'quantity-shipped',
  quantityToShip: 'quantity-to-ship',
  currency: 'currency',
  itemPrice: 'item-price',
  itemTax: 'item-tax',
  shippingPrice: 'shipping-price',
  shippingTax: 'shipping-tax',
  shipServiceLevel: 'ship-service-level',
  recipientName: 'recipient-name',
  shipAddress1: 'ship-address-1',
  shipAddress2: 'ship-address-2',
  shipAddress3: 'ship-address-3',
  shipCity: 'ship-city',
  shipState: 'ship-state',
  shipPostal: 'ship-postal-code',
  shipCountry: 'ship-country',
  shipPhoneNumber: 'ship-phone-number',
  deliveryInstructions: 'delivery-Instructions',
  isBusinessOrder: 'is-business-order',
  purchaseOrderNumber: 'purchase-order-number',
  isPrime: 'is-prime',
}

// Get field mappings based on marketplace
const getFieldMappings = (marketplace) => {
  switch (marketplace) {
    case 'temu':
      return temuFieldMappings
    case 'amazon':
      return amazonFieldMappings
    case 'ebay':
    default:
      return ebayFieldMappings
  }
}

// Get CSV separator based on marketplace
const getCSVSeparator = (marketplace) => {
  switch (marketplace) {
    case 'temu':
      return ','
    case 'amazon':
      return '\t'
    case 'ebay':
    default:
      return ';'
  }
}

// Handle file upload
const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    form.value.csvFile = file
    form.value.csvFileName = file.name
  }
}

// Parse German price format: "14,99 €" -> 14.99
const parseGermanPrice = (priceStr) => {
  if (!priceStr || priceStr === '') return 0
  // Remove currency symbols and whitespace
  let cleaned = priceStr.replace(/[€\s]/g, '').trim()
  // Replace German decimal comma with dot
  cleaned = cleaned.replace(',', '.')
  const value = parseFloat(cleaned)
  return isNaN(value) ? 0 : value
}

// Parse German date format: "01-Feb-26" -> ISO date string
const parseGermanDate = (dateStr) => {
  if (!dateStr || dateStr === '') return null

  const monthMap = {
    'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04',
    'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08',
    'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'
  }

  const parts = dateStr.split('-')
  if (parts.length !== 3) return null

  const day = parts[0].padStart(2, '0')
  const month = monthMap[parts[1]] || '01'
  let year = parts[2]

  // Convert 2-digit year to 4-digit
  if (year.length === 2) {
    year = parseInt(year) > 50 ? '19' + year : '20' + year
  }

  return `${year}-${month}-${day}`
}

// Parse CSV content
const parseCSV = (content, marketplace) => {
  console.log('=== CSV PARSING DEBUG ===')
  console.log('Marketplace:', marketplace)

  // Remove BOM if present (common in Excel-exported CSVs)
  if (content.charCodeAt(0) === 0xFEFF) {
    content = content.slice(1)
    console.log('BOM removed')
  }

  console.log('Content length:', content.length)
  console.log('First 500 chars:', content.substring(0, 500))
  console.log('First char code:', content.charCodeAt(0))

  // Get separator and field mappings based on marketplace
  const separator = getCSVSeparator(marketplace)
  const fieldMappings = getFieldMappings(marketplace)
  console.log('Using separator:', JSON.stringify(separator))

  // Split by lines, handling both \r\n and \n
  const lines = content.split(/\r?\n/)
  console.log('Number of lines:', lines.length)

  if (lines.length < 2) {
    throw new Error('CSV file must have at least a header row and one data row')
  }

  // Parse header row (separator based on marketplace, fields may be quoted)
  const parseRow = (row) => {
    const fields = []
    let current = ''
    let inQuotes = false

    for (let i = 0; i < row.length; i++) {
      const char = row[i]

      if (char === '"') {
        if (inQuotes && row[i + 1] === '"') {
          current += '"'
          i++ // Skip next quote
        } else {
          inQuotes = !inQuotes
        }
      } else if (char === separator && !inQuotes) {
        fields.push(current.trim())
        current = ''
      } else {
        current += char
      }
    }
    fields.push(current.trim())

    return fields
  }

  // Find the first non-empty line as the header row
  let headerLineIndex = 0
  while (headerLineIndex < lines.length && lines[headerLineIndex].trim() === '') {
    headerLineIndex++
  }

  if (headerLineIndex >= lines.length) {
    throw new Error('No header row found in CSV file')
  }

  console.log('Header line index:', headerLineIndex)
  console.log('Header line content:', lines[headerLineIndex].substring(0, 200))

  const headers = parseRow(lines[headerLineIndex])
  console.log('Parsed headers count:', headers.length)
  console.log('First 10 headers:', headers.slice(0, 10))
  console.log('Header[0] exact:', JSON.stringify(headers[0]))
  console.log('Header[1] exact:', JSON.stringify(headers[1]))
  console.log('Expected orderNumber column name:', JSON.stringify(fieldMappings.orderNumber))

  // Find column indices for the fields we need
  const getColumnIndex = (fieldKey) => {
    const columnName = fieldMappings[fieldKey]
    // Try exact match first, then try trimmed match
    let idx = headers.findIndex(h => h === columnName)
    if (idx === -1) {
      // Try with trimmed values
      idx = headers.findIndex(h => h.trim() === columnName.trim())
    }
    if (idx === -1 && fieldKey === 'orderNumber') {
      console.log('orderNumber not found! Looking for:', JSON.stringify(columnName))
      console.log('Available headers:', headers.map((h, i) => `[${i}]=${JSON.stringify(h)}`).slice(0, 5))
    }
    return idx
  }

  const columnIndices = {}
  for (const [key, value] of Object.entries(fieldMappings)) {
    columnIndices[key] = getColumnIndex(key)
  }

  console.log('Column indices:', columnIndices)
  console.log('orderNumber index:', columnIndices.orderNumber)
  console.log('Header at orderNumber index:', headers[columnIndices.orderNumber])

  // Parse data rows (skip empty rows and start after header)
  const rawRows = []
  const dataStartIndex = headerLineIndex + 1
  console.log('Data starts at line index:', dataStartIndex)

  for (let i = dataStartIndex; i < lines.length; i++) {
    const line = lines[i].trim()
    if (!line) continue

    const fields = parseRow(line)

    if (i <= dataStartIndex + 2) {
      console.log(`Row ${i} fields count:`, fields.length)
      console.log(`Row ${i} first 5 fields:`, fields.slice(0, 5))
    }

    // Skip rows that are clearly metadata (like "2;Verkaufsprotokoll(e) heruntergeladen;")
    const orderNumber = fields[columnIndices.orderNumber]
    if (!orderNumber || orderNumber === '' || orderNumber.includes('Verkaufsprotokoll')) {
      console.log(`Row ${i} skipped (metadata or empty)`)
      continue
    }

    // Parse the row
    const getValue = (key) => {
      const idx = columnIndices[key]
      if (idx === -1 || idx >= fields.length) return ''
      return fields[idx]?.replace(/"/g, '').trim() || ''
    }

    // Build recipient name - for Temu, combine first and last name if recipientName is empty
    let recipientName = getValue('recipientName')
    if (!recipientName && marketplace === 'temu') {
      const firstName = getValue('recipientFirstName')
      const lastName = getValue('recipientLastName')
      recipientName = [firstName, lastName].filter(Boolean).join(' ')
    }

    // Build ship address - for Temu/Amazon, combine address1, address2, address3
    let shipAddress1 = getValue('shipAddress1')
    let shipAddress2 = getValue('shipAddress2')
    if (marketplace === 'temu' || marketplace === 'amazon') {
      const address3 = getValue('shipAddress3')
      const district = getValue('district')
      shipAddress2 = [shipAddress2, address3, district].filter(Boolean).join(', ')
    }

    // Parse quantity - handle spaces in Temu format (e.g., "1    ")
    const quantityStr = getValue('quantity').replace(/\s/g, '')
    const quantity = parseInt(quantityStr) || 1

    // Parse dates - Amazon uses ISO format, eBay uses German format
    let soldDate, paymentDate
    if (marketplace === 'amazon') {
      const purchaseDateStr = getValue('purchaseDate')
      const paymentsDateStr = getValue('paymentsDate')
      soldDate = purchaseDateStr ? purchaseDateStr.substring(0, 10) : null
      paymentDate = paymentsDateStr ? paymentsDateStr.substring(0, 10) : null
    } else {
      soldDate = parseGermanDate(getValue('soldDate'))
      paymentDate = parseGermanDate(getValue('paymentDate'))
    }

    // Get phone - Amazon has buyerPhone and shipPhoneNumber
    const recipientPhone = getValue('recipientPhone') || getValue('shipPhoneNumber') || getValue('buyerPhone')

    // Get price - Amazon "Order Report" has item-price, "Unshipped Orders" has no price
    let soldFor, shippingCost, grandTotal
    if (marketplace === 'amazon') {
      soldFor = parseFloat(getValue('itemPrice')) || 0
      shippingCost = parseFloat(getValue('shippingPrice')) || 0
      grandTotal = soldFor + shippingCost
    } else {
      soldFor = parseGermanPrice(getValue('soldFor'))
      shippingCost = parseGermanPrice(getValue('shippingCost'))
      grandTotal = parseGermanPrice(getValue('grandTotal'))
    }

    // Get buyer note - Amazon has delivery instructions
    const buyerNote = getValue('buyerNote') || getValue('deliveryInstructions')

    rawRows.push({
      orderNumber: getValue('orderNumber'),
      salesProtocolNumber: getValue('salesProtocolNumber'),
      buyerUsername: getValue('buyerUsername'),
      buyerName: getValue('buyerName') || recipientName,
      buyerEmail: getValue('buyerEmail'),
      buyerNote: buyerNote,
      buyerAddress1: getValue('buyerAddress1'),
      buyerAddress2: getValue('buyerAddress2'),
      buyerCity: getValue('buyerCity'),
      buyerState: getValue('buyerState'),
      buyerPostal: getValue('buyerPostal'),
      buyerCountry: getValue('buyerCountry'),
      recipientName: recipientName,
      recipientPhone: recipientPhone,
      shipAddress1: shipAddress1,
      shipAddress2: shipAddress2,
      shipCity: getValue('shipCity'),
      shipState: getValue('shipState'),
      shipPostal: getValue('shipPostal')?.replace(/\s/g, ''),
      shipCountry: getValue('shipCountry'),
      itemNumber: getValue('itemNumber'),
      itemTitle: getValue('itemTitle') || getValue('productName'),
      sku: getValue('sku') || getValue('skuId'),
      quantity: quantity,
      soldFor: soldFor,
      shippingCost: shippingCost,
      grandTotal: grandTotal,
      soldDate: soldDate,
      paymentDate: paymentDate,
      transactionId: getValue('transactionId'),
      variantDetails: getValue('variantDetails') || getValue('variation'),
      shippingService: marketplace === 'amazon' ? getValue('shipServiceLevel') : getValue('shippingService'),
      trackingNumber: getValue('trackingNumber'),
    })
  }

  console.log(`Parsed ${rawRows.length} raw rows`)

  // Group rows by order number to handle multi-item orders.
  // eBay multi-item orders: first row has buyer/shipping info but may have no SKU,
  // subsequent rows with same order number have SKU but empty buyer info.
  const orderGroups = {}
  for (const row of rawRows) {
    if (!row.orderNumber) continue
    if (!orderGroups[row.orderNumber]) {
      orderGroups[row.orderNumber] = []
    }
    orderGroups[row.orderNumber].push(row)
  }

  console.log(`Grouped into ${Object.keys(orderGroups).length} unique orders`)

  const orders = []
  for (const [orderNumber, rows] of Object.entries(orderGroups)) {
    // Find the row with buyer info (the one that has buyerEmail or recipientName)
    const headerRow = rows.find(r => r.buyerEmail || r.recipientName || r.buyerName) || rows[0]

    // Find all rows that have a SKU (the item lines)
    const itemRows = rows.filter(r => r.sku)

    // Build order lines from item rows
    const orderLines = itemRows.map(item => ({
      sku: item.sku,
      quantity: item.quantity || 1,
      soldFor: item.soldFor || 0,
      itemNumber: item.itemNumber || '',
      itemTitle: item.itemTitle || '',
      variantDetails: item.variantDetails || '',
      trackingNumber: item.trackingNumber || headerRow.trackingNumber || '',
      transactionId: item.transactionId || headerRow.transactionId || '',
      productFound: null,
      productId: null,
      productName: null
    }))

    // If no item rows with SKU, create a placeholder line
    if (orderLines.length === 0) {
      orderLines.push({
        sku: '',
        quantity: headerRow.quantity || 1,
        soldFor: headerRow.soldFor || 0,
        itemNumber: headerRow.itemNumber || '',
        itemTitle: headerRow.itemTitle || '',
        variantDetails: headerRow.variantDetails || '',
        trackingNumber: headerRow.trackingNumber || '',
        transactionId: headerRow.transactionId || '',
        productFound: null,
        productId: null,
        productName: null
      })
    }

    // Calculate grand total from all lines
    const calculatedTotal = orderLines.reduce((sum, l) => sum + (l.soldFor * l.quantity), 0)

    orders.push({
      orderNumber: headerRow.orderNumber,
      salesProtocolNumber: headerRow.salesProtocolNumber,
      buyerUsername: headerRow.buyerUsername,
      buyerName: headerRow.buyerName,
      buyerEmail: headerRow.buyerEmail,
      buyerNote: headerRow.buyerNote,
      buyerAddress1: headerRow.buyerAddress1,
      buyerAddress2: headerRow.buyerAddress2,
      buyerCity: headerRow.buyerCity,
      buyerState: headerRow.buyerState,
      buyerPostal: headerRow.buyerPostal,
      buyerCountry: headerRow.buyerCountry,
      recipientName: headerRow.recipientName,
      recipientPhone: headerRow.recipientPhone,
      shipAddress1: headerRow.shipAddress1,
      shipAddress2: headerRow.shipAddress2,
      shipCity: headerRow.shipCity,
      shipState: headerRow.shipState,
      shipPostal: headerRow.shipPostal,
      shipCountry: headerRow.shipCountry,
      soldDate: headerRow.soldDate,
      paymentDate: headerRow.paymentDate,
      shippingService: headerRow.shippingService,
      shippingCost: headerRow.shippingCost || 0,
      grandTotal: headerRow.grandTotal || calculatedTotal,
      orderLines: orderLines,
      selected: true
    })
  }

  console.log(`Final orders count: ${orders.length}`)
  return orders
}

// Read and parse the uploaded CSV file
const processCSV = async () => {
  console.log('=== processCSV CALLED ===')
  console.log('csvFile:', form.value.csvFile)
  console.log('organizationId:', form.value.organizationId)

  if (!form.value.csvFile) {
    toast({
      message: 'Please select a CSV file',
      type: 'is-warning',
      duration: 3000
    })
    return
  }

  if (!form.value.organizationId) {
    toast({
      message: 'Please select an organization',
      type: 'is-warning',
      duration: 3000
    })
    return
  }

  if (!form.value.orderSourceId) {
    toast({
      message: 'Tip: Select an Order Source to use its pricelist for product matching',
      type: 'is-info',
      duration: 4000
    })
  }

  const marketplace = effectiveMarketplace.value
  if (!marketplace) {
    toast({
      message: 'Please select an order source with a marketplace or select a marketplace manually',
      type: 'is-warning',
      duration: 3000
    })
    return
  }

  loading.value = true

  try {
    console.log('Reading file content...')
    const content = await form.value.csvFile.text()
    console.log('File content length:', content.length)
    console.log('Calling parseCSV with marketplace:', marketplace)
    const orders = parseCSV(content, marketplace)
    console.log('parseCSV returned:', orders.length, 'orders')

    if (orders.length === 0) {
      toast({
        message: 'No valid orders found in the CSV file. Make sure the file format matches the selected marketplace.',
        type: 'is-warning',
        duration: 5000
      })
      loading.value = false
      return
    }

    parsedOrders.value = orders
    currentStep.value = 'preview'

    // Look up products by SKU in the background (non-blocking)
    console.log('[processCSV] Preview shown, starting product lookups in background...')
    lookupProducts(orders).then(() => {
      console.log('[processCSV] Background product lookups finished')
    }).catch(err => {
      console.error('[processCSV] Background product lookups error:', err)
    })

    toast({
      message: `Found ${orders.length} order(s) in the CSV file`,
      type: 'is-success',
      duration: 3000
    })
  } catch (error) {
    console.error('Error parsing CSV:', error)
    toast({
      message: `Error parsing CSV: ${error.message}`,
      type: 'is-danger',
      duration: 5000
    })
  } finally {
    loading.value = false
  }
}

// Look up products by SKU using a single bulk filter query
const lookupProducts = async (orders) => {
  const uniqueSkus = [...new Set(
    orders.flatMap(o => o.orderLines.map(l => l.sku).filter(s => s))
  )]

  if (uniqueSkus.length === 0) return

  console.log(`[lookupProducts] Looking up ${uniqueSkus.length} unique SKUs in one call:`, uniqueSkus)

  try {
    const productMap = {}

    // Build a single OData filter: Value eq 'X' or Value eq 'Y' or SKU eq 'X' or SKU eq 'Y'
    // The /api/filters/[model]/[query] endpoint prepends $filter= automatically
    const valueFilters = uniqueSkus.map(s => `Value eq '${s}'`).join(' or ')
    const skuFilters = uniqueSkus.map(s => `SKU eq '${s}'`).join(' or ')
    const filter = `(${valueFilters} or ${skuFilters}) and isActive eq true`

    const res = await $fetch(`/api/filters/m_product/${encodeURIComponent(filter)}`, {
      headers: useRequestHeaders(['cookie'])
    })

    console.log(`[lookupProducts] Bulk query returned ${res?.records?.length || 0} products`)

    if (res?.records) {
      for (const product of res.records) {
        const pid = product.m_product_id || product.M_Product_ID || product.id
        const value = product.Value || ''
        const sku = product.SKU || ''
        // Match by Value first, then by SKU
        for (const s of uniqueSkus) {
          if (!productMap[s] && (value === s || sku === s)) {
            productMap[s] = { id: pid, Name: product.Name, Value: value }
          }
        }
      }
    }

    console.log(`[lookupProducts] Matched ${Object.keys(productMap).length}/${uniqueSkus.length} SKUs`)

    // Update order lines and trigger Vue reactivity
    for (const order of parsedOrders.value) {
      for (const line of order.orderLines) {
        if (line.sku && productMap[line.sku]) {
          line.productFound = true
          line.productId = productMap[line.sku].id
          line.productName = productMap[line.sku].Name
        } else if (line.sku) {
          line.productFound = false
        }
      }
    }
    parsedOrders.value = [...parsedOrders.value]
  } catch (error) {
    console.error('[lookupProducts] Error:', error)
  }
}

// Toggle order selection
const toggleOrderSelection = (index) => {
  parsedOrders.value[index].selected = !parsedOrders.value[index].selected
}

// Toggle all selections
const toggleSelectAll = () => {
  const allSelected = parsedOrders.value.every(o => o.selected)
  parsedOrders.value.forEach(o => o.selected = !allSelected)
}

// Edit a row
const startEditing = (index) => {
  editingRowIndex.value = index
  // Clear product options when starting edit
  productOptions.value = []
}

const stopEditing = () => {
  editingRowIndex.value = null
  productOptions.value = []
}

// Search products for the dropdown
const searchProducts = async (searchTerm) => {
  console.log('[searchProducts] Called with:', searchTerm)
  if (!searchTerm || searchTerm.length < 2) {
    productOptions.value = []
    return
  }

  loadingProducts.value = true
  try {
    const res = await $fetch(`/api/materials/products/search?search=${encodeURIComponent(searchTerm)}&limit=20`, {
      headers: useRequestHeaders(['cookie'])
    })
    console.log('[searchProducts] Response:', res?.records?.length, 'products')
    if (res?.records) {
      productOptions.value = res.records.map(p => ({
        id: p.id,
        Name: `${p.Value || ''} - ${p.Name || ''}`.trim(),
        sku: p.Value || '',
        value: p.Value || '',
        name: p.Name || ''
      }))
      console.log('[searchProducts] Options:', productOptions.value)
    }
  } catch (error) {
    console.error('Error searching products:', error)
    productOptions.value = []
  } finally {
    loadingProducts.value = false
  }
}

// Handle product selection for an order line
const selectProductForOrder = (orderIndex, lineIndex, productId) => {
  console.log('[selectProductForOrder] Called with orderIndex:', orderIndex, 'lineIndex:', lineIndex, 'productId:', productId)
  const product = productOptions.value.find(p => p.id === productId)
  console.log('[selectProductForOrder] Found product:', product)
  if (product) {
    const line = parsedOrders.value[orderIndex].orderLines[lineIndex]
    line.productId = product.id
    line.productName = product.name
    line.sku = product.sku
    line.productFound = true
    console.log('[selectProductForOrder] Updated line:', line)
  }
}

// Import the selected orders
const importOrders = async () => {
  const selectedOrders = parsedOrders.value.filter(o => o.selected)

  if (selectedOrders.length === 0) {
    toast({
      message: 'Please select at least one order to import',
      type: 'is-warning',
      duration: 3000
    })
    return
  }

  // Inform user about orders with lines missing products (they will be created as drafts)
  const ordersWithoutProducts = selectedOrders.filter(o => o.orderLines.some(l => !l.productId && l.sku))
  if (ordersWithoutProducts.length > 0) {
    toast({
      message: `${ordersWithoutProducts.length} order(s) have line(s) without matching product (SKU not found). These will be imported as Draft.`,
      type: 'is-info',
      duration: 5000
    })
  }

  // Send all selected orders to import (backend handles missing products)
  const ordersToImport = selectedOrders

  currentStep.value = 'importing'
  loading.value = true

  try {
    const res = await $fetch('/api/orders/import-ebay', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId,
        orderSourceId: form.value.orderSourceId || null,
        marketplace: effectiveMarketplace.value,
        docStatus: form.value.docStatus || 'CO',
        orders: ordersToImport
      }
    })

    importResult.value = res
    currentStep.value = 'done'

    if (res.success && res.success.length > 0) {
      toast({
        message: `Successfully imported ${res.success.length} order(s)`,
        type: 'is-success',
        duration: 5000
      })
      emit('ordersImported', res)
    }

    if (res.errors && res.errors.length > 0) {
      toast({
        message: `${res.errors.length} order(s) failed to import`,
        type: 'is-danger',
        duration: 5000
      })
    }
  } catch (error) {
    console.error('Error importing orders:', error)
    toast({
      message: `Error importing orders: ${error.message || 'Unknown error'}`,
      type: 'is-danger',
      duration: 5000
    })
    currentStep.value = 'preview'
  } finally {
    loading.value = false
  }
}

// Reset and close modal
const handleClose = () => {
  isOpen.value = false
  currentStep.value = 'upload'
  form.value = {
    organizationId: organizationIdCookie.value || '',
    orderSourceId: '',
    marketplace: 'ebay',
    docStatus: 'CO',
    csvFile: null,
    csvFileName: ''
  }
  parsedOrders.value = []
  importResult.value = null
  editingRowIndex.value = null
  selectedOrderSource.value = null
  productOptions.value = []
  loadingProducts.value = false
}

// Go back to upload step
const goBackToUpload = () => {
  currentStep.value = 'upload'
  parsedOrders.value = []
}

// Computed properties
const selectedCount = computed(() => parsedOrders.value.filter(o => o.selected).length)
const allSelected = computed(() => parsedOrders.value.length > 0 && parsedOrders.value.every(o => o.selected))
const someSelected = computed(() => selectedCount.value > 0 && selectedCount.value < parsedOrders.value.length)
</script>

<template>
  <div class="modal-overlay" v-if="isOpen">
    <div class="modal-wrapper" @click.self="handleClose">
      <div class="modalContent">
        <div class="modalHeader">
          <h3 class="modalTitle">
            <span class="ti ti-file-import me-2"></span>
            Import Orders
          </h3>
          <div class="cursor-pointer" @click="handleClose">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>

        <div class="modalBody">
          <!-- Step 1: Upload -->
          <div v-if="currentStep === 'upload'" class="my-4 mx-4">
            <p class="mb-4" style="color: #6b7280; font-size: 0.875rem;">
              Import orders from marketplace CSV exports. Select your organization and order source, then upload the CSV file.
            </p>

            <!-- Organization Selection -->
            <div class="field mb-4">
              <label class="label">Organization</label>
              <div class="control">
                <div class="select is-fullwidth">
                  <select v-model="form.organizationId">
                    <option value="">Select Organization</option>
                    <option v-for="org in sortedOrganizations" :key="org.id" :value="org.id">
                      {{ org.Name || org.identifier || org.name }}
                    </option>
                  </select>
                </div>
              </div>
            </div>

            <!-- Order Source Selection -->
            <div class="field mb-4">
              <label class="label">Order Source</label>
              <div class="control">
                <div class="select is-fullwidth">
                  <select v-model="form.orderSourceId">
                    <option value="">Select Order Source (optional)</option>
                    <option v-for="os in sortedOrderSources" :key="os.id" :value="os.id">
                      {{ os.Name || os.identifier || os.name }}
                    </option>
                  </select>
                </div>
              </div>
              <p class="help" v-if="!detectedMarketplace">Select the order source to apply to all imported orders (e.g., eBay, Amazon)</p>
              <div v-if="marketplaceColor" class="mt-2">
                <span class="marketplace-badge" :style="{ backgroundColor: marketplaceColor.bg, color: marketplaceColor.color, borderColor: marketplaceColor.border }">
                  <span class="ti ti-check me-1"></span>
                  {{ marketplaceColor.label }} CSV format will be used
                </span>
              </div>
              <div v-else-if="form.orderSourceId && !detectedMarketplace && selectedOrderSource" class="mt-2">
                <span class="marketplace-badge" style="background-color: #fef2f2; color: #dc2626; border-color: #dc2626;">
                  <span class="ti ti-alert-circle me-1"></span>
                  No marketplace set on this order source — select one below
                </span>
              </div>
            </div>

            <!-- Marketplace Selection (only when no order source or order source has no marketplace) -->
            <div class="field mb-4" v-if="!detectedMarketplace">
              <label class="label">Marketplace</label>
              <div class="control">
                <div class="select is-fullwidth">
                  <select v-model="form.marketplace">
                    <option v-for="mp in marketplaceOptions" :key="mp.value" :value="mp.value">
                      {{ mp.label }}
                    </option>
                  </select>
                </div>
              </div>
              <p class="help">Select a marketplace or choose an order source above to auto-detect</p>
            </div>

            <!-- Document Status Selection -->
            <div class="field mb-4">
              <label class="label">Document Status</label>
              <div class="control">
                <div class="select is-fullwidth">
                  <select v-model="form.docStatus">
                    <option v-for="ds in docStatusOptions" :key="ds.value" :value="ds.value">
                      {{ ds.label }}
                    </option>
                  </select>
                </div>
              </div>
              <p class="help">Status to set on imported orders (Completed will process/complete the order)</p>
            </div>

            <!-- File Upload -->
            <div class="field mb-4">
              <label class="label">CSV File</label>
              <div class="file has-name is-fullwidth">
                <label class="file-label">
                  <input class="file-input" type="file" accept=".csv,.txt,.tsv" @change="handleFileUpload">
                  <span class="file-cta">
                    <span class="file-icon">
                      <i class="ti ti-upload"></i>
                    </span>
                    <span class="file-label">Choose file...</span>
                  </span>
                  <span class="file-name">
                    {{ form.csvFileName || 'No file selected' }}
                  </span>
                </label>
              </div>
              <p class="help">Upload a {{ effectiveMarketplace === 'amazon' ? 'Amazon order report (tab-separated)' : effectiveMarketplace === 'temu' ? 'Temu order export (comma-separated)' : 'eBay sales report (semicolon-separated, German format)' }} CSV file</p>
            </div>
          </div>

          <!-- Step 2: Preview -->
          <div v-else-if="currentStep === 'preview'" class="my-4 mx-2">
            <div class="d-flex justify-between items-center mb-3">
              <div class="d-flex items-center gap-10px">
                <button class="button is-small" @click="goBackToUpload">
                  <span class="ti ti-arrow-left me-1"></span> Back
                </button>
                <span class="tag is-info">{{ parsedOrders.length }} orders found</span>
              </div>
              <div class="d-flex items-center gap-10px">
                <label class="checkbox-label-inline">
                  <input
                    type="checkbox"
                    :checked="allSelected"
                    :indeterminate.prop="someSelected"
                    @change="toggleSelectAll"
                    class="checkbox-input-inline"
                  />
                  <span class="checkbox-text-inline">
                    Select All ({{ selectedCount }} selected)
                  </span>
                </label>
              </div>
            </div>

            <div class="orders-preview-table">
              <table class="table is-fullwidth is-hoverable is-size-7">
                <thead>
                  <tr>
                    <th style="width: 40px;"></th>
                    <th>Order #</th>
                    <th>Customer</th>
                    <th>Ship To</th>
                    <th>Product (SKU)</th>
                    <th class="has-text-right">Qty</th>
                    <th class="has-text-right">Price</th>
                    <th class="has-text-right">Total</th>
                    <th style="width: 60px;">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(order, index) in parsedOrders" :key="index"
                      :class="{
                        'has-background-warning-light': order.orderLines.some(l => !l.productFound && l.sku),
                        'multi-line-order': order.orderLines.length > 1
                      }">
                    <td>
                      <input
                        type="checkbox"
                        :checked="order.selected"
                        @change="toggleOrderSelection(index)"
                      />
                    </td>
                    <td>
                      <span class="tag is-light">{{ order.orderNumber }}</span>
                      <div v-if="order.orderLines.length > 1" class="multi-line-badge mt-1">
                        <span class="ti ti-package me-1"></span>{{ order.orderLines.length }} items &rarr; 1 order
                      </div>
                    </td>
                    <td>
                      <template v-if="editingRowIndex === index">
                        <input v-model="order.buyerName" class="input is-small" placeholder="Name" />
                        <input v-model="order.buyerEmail" class="input is-small mt-1" placeholder="Email" />
                      </template>
                      <template v-else>
                        <strong>{{ order.recipientName || order.buyerName }}</strong>
                        <br>
                        <small class="has-text-grey">{{ order.buyerEmail }}</small>
                      </template>
                    </td>
                    <td>
                      <template v-if="editingRowIndex === index">
                        <input v-model="order.shipAddress1" class="input is-small" placeholder="Address" />
                        <input v-model="order.shipPostal" class="input is-small mt-1" placeholder="Postal" style="width: 80px; display: inline-block;" />
                        <input v-model="order.shipCity" class="input is-small mt-1" placeholder="City" style="width: calc(100% - 90px); display: inline-block; margin-left: 5px;" />
                      </template>
                      <template v-else>
                        {{ order.shipAddress1 }}
                        <br>
                        <small>{{ order.shipPostal }} {{ order.shipCity }}, {{ order.shipCountry }}</small>
                      </template>
                    </td>
                    <td style="min-width: 250px;">
                      <template v-if="editingRowIndex === index">
                        <div v-for="(line, lineIdx) in order.orderLines" :key="lineIdx" class="mb-2" :class="{ 'pt-2': lineIdx > 0, 'border-top': lineIdx > 0 }">
                          <label class="label is-small mb-1">{{ order.orderLines.length > 1 ? `Line ${lineIdx + 1}: ` : '' }}Search Article</label>
                          <ClientOnly>
                            <SelectBox
                              v-model="line.productId"
                              :options="productOptions"
                              prop="Name"
                              dataprop="id"
                              datatype="number"
                              :size="10"
                              :loading="loadingProducts"
                              @search="searchProducts"
                              @update:modelValue="selectProductForOrder(index, lineIdx, $event)"
                              placeholder="Type to search for a product..."
                            />
                          </ClientOnly>
                          <div v-if="line.productFound" class="tag is-success is-light is-small mt-1">
                            <span class="ti ti-check me-1"></span>
                            {{ line.sku }} - {{ line.productName }}
                          </div>
                        </div>
                      </template>
                      <template v-else>
                        <div v-for="(line, lineIdx) in order.orderLines" :key="lineIdx" :class="{ 'mt-1': lineIdx > 0 }">
                          <span v-if="line.productFound" class="tag is-success is-light">
                            <span class="ti ti-check me-1"></span>
                            {{ line.sku }}
                          </span>
                          <span v-else-if="line.sku" class="tag is-danger is-light" title="Product not found - click edit to select">
                            <span class="ti ti-alert-circle me-1"></span>
                            {{ line.sku }}
                          </span>
                          <span v-else class="tag is-warning is-light">No SKU</span>
                          <small class="has-text-grey ms-1" :title="line.itemTitle">
                            {{ line.productName || line.itemTitle?.substring(0, 25) }}{{ !line.productName && line.itemTitle?.length > 25 ? '...' : '' }}
                          </small>
                        </div>
                      </template>
                    </td>
                    <td class="has-text-right">
                      <template v-if="editingRowIndex === index">
                        <div v-for="(line, lineIdx) in order.orderLines" :key="lineIdx" :class="{ 'mt-1': lineIdx > 0 }">
                          <input v-model.number="line.quantity" type="number" min="1" class="input is-small" style="width: 70px;" />
                        </div>
                      </template>
                      <template v-else>
                        <div v-for="(line, lineIdx) in order.orderLines" :key="lineIdx" :class="{ 'mt-1': lineIdx > 0 }">
                          {{ line.quantity }}
                        </div>
                      </template>
                    </td>
                    <td class="has-text-right">
                      <template v-if="editingRowIndex === index">
                        <div v-for="(line, lineIdx) in order.orderLines" :key="lineIdx" :class="{ 'mt-1': lineIdx > 0 }">
                          <input v-model.number="line.soldFor" type="number" step="0.01" min="0" class="input is-small" style="width: 90px;" />
                        </div>
                      </template>
                      <template v-else>
                        <div v-for="(line, lineIdx) in order.orderLines" :key="lineIdx" :class="{ 'mt-1': lineIdx > 0 }">
                          {{ new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(line.soldFor) }}
                        </div>
                      </template>
                    </td>
                    <td class="has-text-right has-text-weight-bold">
                      {{ new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(
                        order.orderLines.reduce((sum, l) => sum + (l.soldFor || 0) * (l.quantity || 1), 0)
                      ) }}
                    </td>
                    <td>
                      <button v-if="editingRowIndex === index" class="button is-small is-success" @click="stopEditing" title="Save">
                        <span class="ti ti-check"></span>
                      </button>
                      <button v-else class="button is-small" @click="startEditing(index)" title="Edit">
                        <span class="ti ti-pencil"></span>
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- Warnings -->
            <div v-if="parsedOrders.some(o => o.orderLines.some(l => !l.productFound && l.sku))" class="notification is-warning is-light mt-3">
              <strong><span class="ti ti-alert-triangle me-1"></span> Some products not found</strong>
              <p class="is-size-7 mt-1">
                Orders without a matched product will be imported as <strong>Draft</strong> with the missing SKU noted in the order description.
                You can add the product manually after import. Or click the <span class="ti ti-pencil"></span> edit button to search and select a product now.
              </p>
            </div>
          </div>

          <!-- Step 3: Importing -->
          <div v-else-if="currentStep === 'importing'" class="my-5 mx-5 has-text-centered">
            <div class="is-size-1 mb-3">
              <span class="ti ti-loader-2 spin"></span>
            </div>
            <p class="is-size-5">Importing orders...</p>
            <p class="has-text-grey">Please wait while the orders are being created.</p>
          </div>

          <!-- Step 4: Done -->
          <div v-else-if="currentStep === 'done'" class="my-4 mx-4">
            <!-- Successfully completed orders -->
            <div v-if="importResult?.success?.filter(o => !o.hasMissingProduct).length > 0" class="notification is-success is-light mb-4">
              <strong><span class="ti ti-check me-1"></span> Successfully imported {{ importResult.success.filter(o => !o.hasMissingProduct).length }} order(s)</strong>
              <div class="order-links mt-2">
                <a
                  v-for="order in importResult.success.filter(o => !o.hasMissingProduct)"
                  :key="order.orderId"
                  :href="`/sales/orders/${order.orderId}/edit`"
                  target="_blank"
                  class="tag is-link is-medium order-link-tag me-1 mb-1"
                >
                  {{ order.documentNo || order.orderId }}
                  <span class="ti ti-external-link ms-1"></span>
                </a>
              </div>
            </div>

            <!-- Orders with missing products (imported as Draft) -->
            <div v-if="importResult?.success?.filter(o => o.hasMissingProduct).length > 0" class="notification is-warning is-light mb-4">
              <strong><span class="ti ti-alert-triangle me-1"></span> {{ importResult.success.filter(o => o.hasMissingProduct).length }} order(s) imported as Draft (missing product)</strong>
              <p class="is-size-7 mt-1 mb-2">These orders need manual product assignment before completing.</p>
              <div class="order-links">
                <a
                  v-for="order in importResult.success.filter(o => o.hasMissingProduct)"
                  :key="order.orderId"
                  :href="`/sales/orders/${order.orderId}/edit`"
                  target="_blank"
                  class="tag is-warning is-medium order-link-tag me-1 mb-1"
                >
                  {{ order.documentNo || order.orderId }}
                  <small class="ms-1">(SKU: {{ order.missingSku }})</small>
                  <span class="ti ti-external-link ms-1"></span>
                </a>
              </div>
            </div>

            <div v-if="importResult?.errors?.length > 0" class="notification is-danger is-light">
              <strong><span class="ti ti-x me-1"></span> {{ importResult.errors.length }} order(s) failed to import</strong>
              <ul class="mt-2 is-size-7">
                <li v-for="(error, idx) in importResult.errors" :key="idx">
                  <strong>{{ error.orderNumber }}:</strong> {{ error.error }}
                </li>
              </ul>
            </div>
          </div>
        </div>

        <div class="modalFooter">
          <div class="buttons" style="margin-left: auto;">
            <button class="button" @click="handleClose">
              {{ currentStep === 'done' ? 'Close' : 'Cancel' }}
            </button>

            <button
              v-if="currentStep === 'upload'"
              class="button is-primary"
              :class="{ 'is-loading': loading }"
              :disabled="!form.csvFile || !form.organizationId"
              @click="processCSV"
            >
              <span class="ti ti-eye me-1"></span>
              Preview Orders
            </button>

            <button
              v-if="currentStep === 'preview'"
              class="button is-success"
              :class="{ 'is-loading': loading }"
              :disabled="selectedCount === 0"
              @click="importOrders"
            >
              <span class="ti ti-file-import me-1"></span>
              Import {{ selectedCount }} Order(s)
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.modalContent {
  max-width: 95vw;
  width: 100%;
  max-height: 95vh;
  overflow-y: auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modalHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
  border-radius: 8px 8px 0 0;
}

.modalTitle {
  font-size: 1.25rem;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
}

.modalBody {
  padding: 0;
  max-height: calc(95vh - 140px);
  overflow-y: auto;
}

.modalFooter {
  display: flex;
  justify-content: flex-end;
  padding: 1rem 1.5rem;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
  border-radius: 0 0 8px 8px;
}

.marketplace-badge {
  display: inline-flex;
  align-items: center;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 600;
  border: 1px solid;
}

.orders-preview-table {
  max-height: calc(95vh - 300px);
  overflow-y: auto;
  overflow-x: visible;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
}

/* Allow SelectBox dropdown to overflow the table */
.orders-preview-table .table {
  margin-bottom: 0;
  overflow: visible;
}

.orders-preview-table .table thead {
  position: sticky;
  top: 0;
  background: #f9fafb;
  z-index: 1;
}

.orders-preview-table .table th {
  border-bottom: 2px solid #e5e7eb;
  white-space: nowrap;
}

.orders-preview-table .table td {
  vertical-align: middle;
  position: relative;
}

/* Fix SelectBox dropdown overflow */
.orders-preview-table .table td :deep(.selectbox),
.orders-preview-table .table td :deep(.tedir-select) {
  position: relative;
}

.orders-preview-table .table td :deep(.selectbox-dropdown),
.orders-preview-table .table td :deep(.tedir-select-dropdown),
.orders-preview-table .table td :deep([class*="dropdown"]) {
  position: absolute;
  z-index: 9999;
  max-height: 200px;
  overflow-y: auto;
}

.border-top {
  border-top: 1px solid #e5e7eb;
}

.multi-line-order > td:first-child {
  border-left: 3px solid #3e8ed0;
}

.multi-line-badge {
  display: inline-flex;
  align-items: center;
  font-size: 0.7rem;
  color: #3e8ed0;
  font-weight: 600;
}

.checkbox-label-inline {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  font-size: 0.875rem;
}

.checkbox-input-inline {
  width: 1rem;
  height: 1rem;
  cursor: pointer;
}

.checkbox-text-inline {
  user-select: none;
}

.order-link-tag {
  cursor: pointer;
  text-decoration: none;
  transition: all 0.2s;
}

.order-link-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .modal-wrapper {
    padding: 0;
  }

  .modalContent {
    max-height: 100vh;
    height: 100vh;
    border-radius: 0;
  }

  .orders-preview-table {
    max-height: calc(100vh - 300px);
  }

  .orders-preview-table .table {
    font-size: 0.7rem;
  }
}
</style>
