<script setup>
import sharedLang from '~/assets/langs/shared.js'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  customers: {
    type: Array,
    default: () => []
  },
  selectedCustomer: {
    type: Object,
    default: null
  },
  selectedMonth: {
    type: Number,
    default: null
  },
  selectedYear: {
    type: Number,
    default: null
  }
})

// Get language preference
const language = useCookie('language')
const lang = computed(() => language.value || 'en-US')
const t = computed(() => sharedLang(lang.value))

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

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

// Get previous month
const now = new Date()
const prevMonth = now.getMonth() === 0 ? 12 : now.getMonth()
const prevMonthYear = now.getMonth() === 0 ? now.getFullYear() - 1 : now.getFullYear()

const form = ref({
  partnerId: props.selectedCustomer?.id || null,
  month: props.selectedMonth || prevMonth,
  year: props.selectedYear || prevMonthYear,
  // Optional month-range mode (overrides the single month/year when enabled)
  rangeMode: false,
  monthFrom: props.selectedMonth || prevMonth,
  yearFrom: props.selectedYear || prevMonthYear,
  monthTo: props.selectedMonth || prevMonth,
  yearTo: props.selectedYear || prevMonthYear,
  preview: true,
  fetchCountryData: false,
  createReport: true,
  validatePaketShipment: false,
  debugStorageUsage: false
})

// Watch for changes to props and update form when modal opens
watch(() => props.modelValue, (isOpen) => {
  if (isOpen && (props.selectedCustomer || props.selectedMonth || props.selectedYear)) {
    form.value.partnerId = props.selectedCustomer?.id || null
    form.value.month = props.selectedMonth || prevMonth
    form.value.year = props.selectedYear || prevMonthYear
    form.value.monthFrom = props.selectedMonth || prevMonth
    form.value.yearFrom = props.selectedYear || prevMonthYear
    form.value.monthTo = props.selectedMonth || prevMonth
    form.value.yearTo = props.selectedYear || prevMonthYear
  }
})

// Build the date filter params sent to the API. In range mode we normalize so
// "from" is never after "to"; the server then fetches every month in the span
// and still produces one order per customer per month.
const buildDateParams = () => {
  if (form.value.rangeMode) {
    const fromIdx = form.value.yearFrom * 12 + (form.value.monthFrom - 1)
    const toIdx = form.value.yearTo * 12 + (form.value.monthTo - 1)
    const startIdx = Math.min(fromIdx, toIdx)
    const endIdx = Math.max(fromIdx, toIdx)
    return {
      rangeMode: true,
      monthFrom: (startIdx % 12) + 1,
      yearFrom: Math.floor(startIdx / 12),
      monthTo: (endIdx % 12) + 1,
      yearTo: Math.floor(endIdx / 12)
    }
  }
  return { month: form.value.month, year: form.value.year }
}

const loading = ref(false)
const result = ref(null)
const expandedLines = ref({})
const selectedOrders = ref(new Set())
const shippingFeesModal = ref({
  isOpen: false,
  data: null
})

// Generate customer options
const customerOptions = computed(() => {
  return [
    { label: t.value.all_customers, value: null },
    ...props.customers.map(c => ({
      label: c.Name || c.identifier,
      value: c.id
    }))
  ]
})

// Generate month options
const monthOptions = computed(() => {
  return [
    { label: t.value.all_months, value: null },
    { label: t.value.january, value: 1 },
    { label: t.value.february, value: 2 },
    { label: t.value.march, value: 3 },
    { label: t.value.april, value: 4 },
    { label: t.value.may, value: 5 },
    { label: t.value.june, value: 6 },
    { label: t.value.july, value: 7 },
    { label: t.value.august, value: 8 },
    { label: t.value.september, value: 9 },
    { label: t.value.october, value: 10 },
    { label: t.value.november, value: 11 },
    { label: t.value.december, value: 12 }
  ]
})

// Month options for range mode — no "All Months" entry (a range needs concrete bounds)
const rangeMonthOptions = computed(() => monthOptions.value.filter(o => o.value !== null))

// Generate year options
const yearOptions = computed(() => {
  const currentYear = new Date().getFullYear()
  const years = []
  for (let i = 0; i <= 5; i++) {
    years.push({
      label: String(currentYear - i),
      value: currentYear - i
    })
  }
  return years
})

const handleGenerate = async () => {
  loading.value = true
  result.value = null

  try {
    const response = await $fetch('/api/fulfillment/generate-orders', {
      method: 'POST',
      body: {
        partnerId: form.value.partnerId,
        ...buildDateParams(),
        preview: form.value.preview,
        fetchCountryData: form.value.preview ? form.value.fetchCountryData : false,
        createReport: form.value.preview ? false : form.value.createReport,
        validatePaketShipment: form.value.preview ? form.value.validatePaketShipment : false,
        debugStorageUsage: form.value.preview ? form.value.debugStorageUsage : false
      }
    })

    result.value = response
    if (!form.value.preview) {
      emit('ordersGenerated', response)
    } else {
      // Initialize all orders as selected in preview mode
      selectedOrders.value = new Set(response.success.map((_, idx) => idx))
    }
  } catch (error) {
    console.error('Error generating orders:', error)
    result.value = {
      success: [],
      errors: [{ error: 'Failed to generate orders', details: error }]
    }
  } finally {
    loading.value = false
  }
}

const handleGenerateSelected = async () => {
  if (selectedOrders.value.size === 0) {
    return
  }

  loading.value = true

  try {
    // Filter to only selected orders
    const selectedOrdersList = result.value.success.filter((_, idx) => selectedOrders.value.has(idx))

    const response = await $fetch('/api/fulfillment/generate-orders', {
      method: 'POST',
      body: {
        partnerId: form.value.partnerId,
        ...buildDateParams(),
        preview: false,
        createReport: form.value.createReport,
        validatePaketShipment: false,
        selectedOrders: selectedOrdersList.map(order => ({
          bpartnerId: order.bpartnerId,
          monthYear: order.monthYear
        }))
      }
    })

    result.value = response
    emit('ordersGenerated', response)
  } catch (error) {
    console.error('Error generating selected orders:', error)
    result.value = {
      success: [],
      errors: [{ error: 'Failed to generate selected orders', details: error }]
    }
  } finally {
    loading.value = false
  }
}

const toggleOrderSelection = (index) => {
  if (selectedOrders.value.has(index)) {
    selectedOrders.value.delete(index)
  } else {
    selectedOrders.value.add(index)
  }
}

const toggleSelectAll = () => {
  if (selectedOrders.value.size === result.value.success.length) {
    selectedOrders.value.clear()
  } else {
    selectedOrders.value = new Set(result.value.success.map((_, idx) => idx))
  }
}

const allSelected = computed(() => {
  return result.value?.success?.length > 0 && selectedOrders.value.size === result.value.success.length
})

const someSelected = computed(() => {
  return selectedOrders.value.size > 0 && selectedOrders.value.size < result.value.success.length
})

const toggleLineDetails = (orderIndex, lineIndex) => {
  const key = `${orderIndex}-${lineIndex}`
  expandedLines.value[key] = !expandedLines.value[key]
}

const isLineExpanded = (orderIndex, lineIndex) => {
  const key = `${orderIndex}-${lineIndex}`
  return expandedLines.value[key] || false
}

const formatDate = (dateStr) => {
  if (!dateStr) return 'N/A'
  return new Date(dateStr).toLocaleDateString('de-DE')
}

const getFlagEmoji = (countryCode) => {
  if (!countryCode || countryCode.length !== 2) return '🏳️'
  const codePoints = countryCode
    .toUpperCase()
    .split('')
    .map(char => 127397 + char.charCodeAt(0))
  return String.fromCodePoint(...codePoints)
}

const showShippingFees = (detail) => {
  shippingFeesModal.value.data = detail
  shippingFeesModal.value.isOpen = true
}

const closeShippingFeesModal = () => {
  shippingFeesModal.value.isOpen = false
  shippingFeesModal.value.data = null
}

const handleClose = () => {
  isOpen.value = false
  result.value = null
  expandedLines.value = {}
  selectedOrders.value = new Set()
  const now = new Date()
  const prevMonth = now.getMonth() === 0 ? 12 : now.getMonth()
  const prevMonthYear = now.getMonth() === 0 ? now.getFullYear() - 1 : now.getFullYear()
  form.value = {
    partnerId: null,
    month: prevMonth,
    year: prevMonthYear,
    rangeMode: false,
    monthFrom: prevMonth,
    yearFrom: prevMonthYear,
    monthTo: prevMonth,
    yearTo: prevMonthYear,
    preview: true,
    fetchCountryData: false,
    createReport: true,
    validatePaketShipment: false,
    debugStorageUsage: false
  }
}
</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">{{ t.generate_fulfillment_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">
          <div v-if="!result" class="my-5 mx-5">
            <p class="mb-4" style="color: #6b7280; font-size: 0.875rem;">
              {{ t.generate_orders_description }}
            </p>

            <div class="field mb-4">
              <label class="label">{{ t.customer }}</label>
              <div class="control">
                <USelect
                  v-model="form.partnerId"
                  :items="customerOptions"
                  value-key="value"
                  :placeholder="t.select_customer"
                  size="lg"
                  color="primary"
                  variant="outline"
                />
              </div>
            </div>

            <div class="field mb-3">
              <label class="checkbox-label checkbox-label-secondary">
                <input type="checkbox" v-model="form.rangeMode" class="checkbox-input" />
                <span class="checkbox-text">
                  <strong>{{ t.use_date_range }}</strong>
                  <span class="checkbox-hint">{{ t.use_date_range_hint }}</span>
                </span>
              </label>
            </div>

            <!-- Single month -->
            <div v-if="!form.rangeMode" class="columns">
              <div class="column">
                <div class="field">
                  <label class="label">{{ t.month }}</label>
                  <div class="control">
                    <USelect
                      v-model="form.month"
                      :items="monthOptions"
                      value-key="value"
                      :placeholder="t.select_month"
                      size="lg"
                      color="primary"
                      variant="outline"
                    />
                  </div>
                </div>
              </div>

              <div class="column">
                <div class="field">
                  <label class="label">{{ t.year }}</label>
                  <div class="control">
                    <USelect
                      v-model="form.year"
                      :items="yearOptions"
                      value-key="value"
                      size="lg"
                      color="primary"
                      variant="outline"
                    />
                  </div>
                </div>
              </div>
            </div>

            <!-- Month range -->
            <div v-else class="columns">
              <div class="column">
                <div class="field">
                  <label class="label">{{ t.range_from }}</label>
                  <div class="control range-control">
                    <USelect
                      v-model="form.monthFrom"
                      :items="rangeMonthOptions"
                      value-key="value"
                      size="lg"
                      color="primary"
                      variant="outline"
                    />
                    <USelect
                      v-model="form.yearFrom"
                      :items="yearOptions"
                      value-key="value"
                      size="lg"
                      color="primary"
                      variant="outline"
                    />
                  </div>
                </div>
              </div>

              <div class="column">
                <div class="field">
                  <label class="label">{{ t.range_to }}</label>
                  <div class="control range-control">
                    <USelect
                      v-model="form.monthTo"
                      :items="rangeMonthOptions"
                      value-key="value"
                      size="lg"
                      color="primary"
                      variant="outline"
                    />
                    <USelect
                      v-model="form.yearTo"
                      :items="yearOptions"
                      value-key="value"
                      size="lg"
                      color="primary"
                      variant="outline"
                    />
                  </div>
                </div>
              </div>
            </div>

            <div class="field mt-4">
              <label class="checkbox-label">
                <input type="checkbox" v-model="form.preview" class="checkbox-input" />
                <span class="checkbox-text">
                  <strong>{{ t.preview_mode }}</strong>
                  <span class="checkbox-hint">{{ t.preview_mode_hint }}</span>
                </span>
              </label>
            </div>

            <div v-if="form.preview" class="field mt-3">
              <label class="checkbox-label checkbox-label-secondary">
                <input type="checkbox" v-model="form.fetchCountryData" class="checkbox-input" />
                <span class="checkbox-text">
                  <strong>{{ t.fetch_country_data }}</strong>
                  <span class="checkbox-hint">{{ t.fetch_country_data_hint }}</span>
                </span>
              </label>
            </div>

            <div v-if="form.preview" class="field mt-3">
              <label class="checkbox-label checkbox-label-warning">
                <input type="checkbox" v-model="form.validatePaketShipment" class="checkbox-input" />
                <span class="checkbox-text">
                  <strong>Validate Paket-Shipment Assignment (1:1)</strong>
                  <span class="checkbox-hint">Verify that each parcel (paket) has exactly one corresponding shipment and vice versa. Displays mismatches where parcels or shipments are missing their counterpart.</span>
                </span>
              </label>
            </div>

            <div v-if="form.preview" class="field mt-3">
              <label class="checkbox-label checkbox-label-secondary">
                <input type="checkbox" v-model="form.debugStorageUsage" class="checkbox-input" />
                <span class="checkbox-text">
                  <strong>Show Storage Usage Debug</strong>
                  <span class="checkbox-hint">Adds a debug section to each previewed order with details about the space‑rent‑QM³ detection and the `/models/cust_storage_usage` fetch (filters, URL, counts, and any errors).</span>
                </span>
              </label>
            </div>

          </div>

          <!-- Results Section -->
          <div v-else class="my-5 mx-5 results-section">
            <div v-if="result.preview" class="notification is-info is-light mb-5">
              <strong><UIcon name="i-heroicons-eye" /> Preview Mode - No Orders Created</strong>
              <p class="mt-2">This is a preview of what would be generated. No data has been modified.</p>
            </div>

            <div v-if="result.success && result.success.length > 0" class="mb-5">
              <div class="notification is-success is-light">
                <strong>{{ result.preview ? 'Preview:' : 'Successfully Generated Orders' }} ({{ result.success.length }})</strong>

                <!-- Selection controls for preview mode -->
                <div v-if="result.preview" class="mt-3">
                  <div class="selection-controls">
                    <label class="checkbox-label-inline">
                      <input
                        type="checkbox"
                        :checked="allSelected"
                        :indeterminate.prop="someSelected"
                        @change="toggleSelectAll"
                        class="checkbox-input-inline"
                      />
                      <span class="checkbox-text-inline">
                        {{ selectedOrders.size === result.success.length ? 'Deselect All' : 'Select All' }}
                        ({{ selectedOrders.size }} selected)
                      </span>
                    </label>
                  </div>
                </div>

                <div v-if="!result.preview && result.success.length > 0" class="mt-3">
                  <span class="has-text-weight-semibold">Open orders:</span>
                  <div class="order-links mt-2">
                    <a
                      v-for="order in result.success"
                      :key="order.orderId"
                      :href="`/sales/orders/${order.orderId}/edit`"
                      target="_blank"
                      class="tag is-link is-medium order-link-tag"
                    >
                      <UIcon name="i-heroicons-document-text" class="mr-1" />
                      {{ order.documentNo }}
                      <UIcon name="i-heroicons-arrow-top-right-on-square" class="ml-1" />
                    </a>
                  </div>
                </div>
              </div>

              <div class="orders-list">
                <div
                  v-for="(order, index) in result.success"
                  :key="result.preview ? index : order.orderId"
                  class="box mb-3"
                  :class="{ 'preview-box': result.preview, 'selected-order': result.preview && selectedOrders.has(index) }"
                >
                  <div class="order-header">
                    <!-- Checkbox for preview mode -->
                    <div v-if="result.preview" class="order-checkbox">
                      <input
                        type="checkbox"
                        :checked="selectedOrders.has(index)"
                        @change="toggleOrderSelection(index)"
                        class="order-checkbox-input"
                      />
                    </div>
                    <div class="order-info">
                      <div v-if="result.preview" class="preview-title">
                        <UIcon name="i-heroicons-document-text" />
                        <strong>{{ order.bpartnerName }}</strong>
                        <span class="preview-badge">PREVIEW</span>
                      </div>
                      <nuxt-link
                        v-else
                        :to="`/sales/orders/${order.orderId}/edit`"
                        class="has-text-link has-text-weight-bold"
                      >
                        {{ order.documentNo }}
                      </nuxt-link>
                      <p class="is-size-7 mt-1">{{ order.bpartnerName }} - {{ order.monthYear }}</p>
                      <p class="is-size-7 has-text-grey">{{ order.linesProcessed }} fee lines processed</p>
                    </div>
                    <div class="order-total">
                      <p class="has-text-success has-text-weight-bold is-size-5">
                        {{ new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(order.totalAmount) }}
                      </p>
                    </div>
                  </div>

                  <!-- Storage Usage Debug (Preview only) -->
                  <div v-if="result.preview && order.debug?.storageUsage?.enabled" class="mt-3">
                    <article class="message is-info is-light">
                      <div class="message-header">
                        <p><UIcon name="i-heroicons-wrench-screwdriver" class="mr-1" /> Storage Usage Debug</p>
                      </div>
                      <div class="message-body is-size-7">
                        <div class="tags">
                          <span class="tag is-light">hasSpaceRentQm3: {{ String(order.debug.storageUsage.hasSpaceRentQm3) }}</span>
                          <span class="tag is-light">isAccountingWarehouseVolume: {{ String(order.debug.storageUsage.isAccountingWarehouseVolume) }}</span>
                          <span class="tag is-light" v-if="order.debug.storageUsage.customerOrgId !== undefined">customerOrgId: {{ order.debug.storageUsage.customerOrgId ?? 'N/A' }}</span>
                          <span class="tag is-light" v-if="order.debug.storageUsage.startDate">start: {{ order.debug.storageUsage.startDate }}</span>
                          <span class="tag is-light" v-if="order.debug.storageUsage.endDate">end: {{ order.debug.storageUsage.endDate }}</span>
                          <span class="tag is-warning" v-if="order.debug.storageUsage.skippedReason">skipped: {{ order.debug.storageUsage.skippedReason }}</span>
                          <span class="tag is-danger" v-if="order.debug.storageUsage.error">error: {{ order.debug.storageUsage.error }}</span>
                          <span class="tag is-success" v-if="order.debug.storageUsage.fetchedCount !== undefined">fetched: {{ order.debug.storageUsage.fetchedCount }}</span>
                        </div>

                        <div v-if="order.debug.storageUsage.requestUrl" class="mt-2">
                          <span class="has-text-weight-semibold">Request URL:</span>
                          <code class="is-family-monospace">{{ order.debug.storageUsage.requestUrl }}</code>
                        </div>

                        <div v-if="order.debug.storageUsage.sample && order.debug.storageUsage.sample.length > 0" class="mt-2">
                          <span class="has-text-weight-semibold">Sample (first 3 rows):</span>
                          <pre class="mt-1" style="white-space: pre-wrap">{{ JSON.stringify(order.debug.storageUsage.sample, null, 2) }}</pre>
                        </div>
                      </div>
                    </article>
                  </div>

                  <!-- Validation Results -->
                  <div v-if="order.validationResults && (order.validationResults.unmatchedParcels?.length > 0 || order.validationResults.unmatchedShipments?.length > 0)" class="validation-results mt-3 mb-3">
                    <div class="notification is-warning">
                      <p class="has-text-weight-bold mb-2">
                        <UIcon name="i-heroicons-exclamation-triangle" class="mr-1" />
                        Paket-Shipment Validation Issues Found
                      </p>
                      <div class="validation-summary mb-3">
                        <span class="tag is-light mr-2">Total Parcels: {{ order.validationResults.totalParcels }}</span>
                        <span class="tag is-light mr-2">Total Shipments: {{ order.validationResults.totalShipments }}</span>
                        <span class="tag is-success mr-2">Matched: {{ order.validationResults.matchedParcels }}</span>
                        <span class="tag is-warning mr-2">Unmatched Parcels: {{ order.validationResults.unmatchedParcels?.length || 0 }}</span>
                        <span class="tag is-danger">Unmatched Shipments: {{ order.validationResults.unmatchedShipments?.length || 0 }}</span>
                      </div>

                      <!-- Unmatched Parcels -->
                      <div v-if="order.validationResults.unmatchedParcels?.length > 0" class="mb-3">
                        <p class="has-text-weight-semibold mb-2 is-size-7">
                          <UIcon name="i-heroicons-cube" class="mr-1" />
                          Parcels without matching Shipment ({{ order.validationResults.unmatchedParcels.length }})
                        </p>
                        <table class="table is-fullwidth is-size-7 is-narrow validation-table">
                          <thead>
                            <tr>
                              <th>Shipment ID</th>
                              <th>Parcel Fee Lines</th>
                              <th>Issue</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr v-for="(item, idx) in order.validationResults.unmatchedParcels" :key="`parcel-${idx}`">
                              <td class="is-family-monospace">
                                <nuxt-link
                                  :to="`/sales/shipments/${item.inoutId}/edit`"
                                  class="tag is-warning is-light"
                                  target="_blank"
                                >
                                  {{ item.inoutId }}
                                  <UIcon name="i-heroicons-arrow-top-right-on-square" class="ml-1" />
                                </nuxt-link>
                              </td>
                              <td>
                                <span v-for="(paket, pidx) in item.paketLines" :key="pidx" class="tag is-light mr-1">
                                  Fee #{{ paket.feeLineId }} (Qty: {{ paket.qty }})
                                </span>
                              </td>
                              <td class="has-text-danger is-size-7">{{ item.reason }}</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>

                      <!-- Unmatched Shipments -->
                      <div v-if="order.validationResults.unmatchedShipments?.length > 0">
                        <p class="has-text-weight-semibold mb-2 is-size-7">
                          <UIcon name="i-heroicons-truck" class="mr-1" />
                          Shipments without matching Parcel ({{ order.validationResults.unmatchedShipments.length }})
                        </p>
                        <table class="table is-fullwidth is-size-7 is-narrow validation-table">
                          <thead>
                            <tr>
                              <th>Shipment</th>
                              <th>Fee Line ID</th>
                              <th>Type</th>
                              <th>Issue</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr v-for="(item, idx) in order.validationResults.unmatchedShipments" :key="`shipment-${idx}`">
                              <td>
                                <nuxt-link
                                  :to="`/sales/shipments/${item.inoutId}/edit`"
                                  class="tag is-danger is-light"
                                  target="_blank"
                                >
                                  {{ item.documentNo }}
                                  <UIcon name="i-heroicons-arrow-top-right-on-square" class="ml-1" />
                                </nuxt-link>
                              </td>
                              <td class="is-family-monospace">#{{ item.feeLineId }}</td>
                              <td><span class="tag is-info is-light">{{ item.type }}</span></td>
                              <td class="has-text-danger is-size-7">{{ item.reason }}</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>

                  <!-- Order Lines Preview -->
                  <div v-if="order.orderLines && order.orderLines.length > 0" class="order-lines mt-3">
                    <p class="has-text-weight-bold mb-2">Order Positions ({{ order.orderLines.length }}):</p>
                    <table class="table is-fullwidth is-size-7">
                      <thead>
                        <tr>
                          <th style="width: 30px;"></th>
                          <th>Product</th>
                          <th>Description</th>
                          <th class="has-text-right">Qty</th>
                          <th class="has-text-right">Price</th>
                          <th class="has-text-right">Total</th>
                        </tr>
                      </thead>
                      <tbody>
                        <template v-for="(line, lineIndex) in order.orderLines" :key="lineIndex">
                          <tr
                            class="position-row"
                            :class="{ 'is-expanded': isLineExpanded(index, lineIndex), 'has-details': line.details && line.details.length > 0 }"
                            @click="line.details && line.details.length > 0 ? toggleLineDetails(index, lineIndex) : null"
                          >
                            <td class="expand-cell">
                              <UIcon
                                v-if="line.details && line.details.length > 0"
                                :name="isLineExpanded(index, lineIndex) ? 'i-heroicons-chevron-down' : 'i-heroicons-chevron-right'"
                                class="expand-icon"
                              />
                            </td>
                            <td>{{ line.productName || 'N/A' }}</td>
                            <td>{{ line.description || '-' }}</td>
                            <td class="has-text-right">{{ line.qtyOrdered }}</td>
                            <td class="has-text-right">{{ new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(line.priceActual) }}</td>
                            <td class="has-text-right has-text-weight-bold">{{ new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(line.lineNetAmt) }}</td>
                          </tr>

                          <!-- Detailed Records for this Position -->
                          <tr v-if="isLineExpanded(index, lineIndex) && line.details && line.details.length > 0" class="details-row">
                            <td colspan="6" class="details-cell">
                              <div class="details-container">
                                <p class="has-text-weight-semibold mb-2 is-size-7">
                                  <UIcon name="i-heroicons-document-text" class="mr-1" />
                                  Detailed Records ({{ line.details.length }})
                                </p>
                                <table class="table is-fullwidth is-size-7 details-table">
                                  <thead>
                                    <tr>
                                      <th>Fee Line ID</th>
                                      <th v-if="line.type === 'fulfillment' || line.type === 'return' || line.type === 'shippingfee'">Country</th>
                                      <th v-if="line.type === 'fulfillment' || line.type === 'return'">Sales Order</th>
                                      <th v-if="line.type === 'fulfillment' || line.type === 'return'">Ext</th>
                                      <th v-if="line.type === 'shippingfee'">Shipment</th>
                                      <th>Date</th>
                                      <th class="has-text-right">Qty</th>
                                      <th class="has-text-right">Unit Price</th>
                                      <th class="has-text-right">Amount</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    <tr v-for="(detail, detailIndex) in line.details" :key="detailIndex">
                                      <td class="is-family-monospace">#{{ detail.id }}</td>
                                      <td v-if="line.type === 'fulfillment' || line.type === 'return' || line.type === 'shippingfee'">
                                        <span v-if="detail.countryCode" class="country-flag" :title="detail.countryName">
                                          {{ getFlagEmoji(detail.countryCode) }}
                                        </span>
                                        <span v-else class="tag is-light is-small">N/A</span>
                                      </td>
                                      <td v-if="line.type === 'fulfillment' || line.type === 'return'">
                                        <nuxt-link
                                          v-if="detail.orderId"
                                          :to="`/sales/orders/${detail.orderId}/edit`"
                                          class="tag is-link is-light order-link"
                                        >
                                          {{ detail.orderDocumentNo || detail.orderId }}
                                        </nuxt-link>
                                        <span v-else class="tag is-light">N/A</span>
                                      </td>
                                      <td v-if="line.type === 'fulfillment' || line.type === 'return'">
                                        {{ detail.externalOrderId || '-' }}
                                      </td>
                                      <td v-if="line.type === 'shippingfee'">
                                        <nuxt-link
                                          v-if="detail.inoutId"
                                          :to="`/sales/shipments/${detail.inoutId}/edit`"
                                          class="tag is-info is-light order-link"
                                        >
                                          {{ detail.inoutDocumentNo || detail.inoutId }}
                                        </nuxt-link>
                                        <span v-else class="tag is-light">N/A</span>
                                      </td>
                                      <td>{{ formatDate(detail.shippingDate) }}</td>
                                      <td class="has-text-right">{{ detail.qty.toFixed(2) }}</td>
                                      <td class="has-text-right">{{ new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(detail.price) }}</td>
                                      <td class="has-text-right has-text-weight-semibold">
                                        {{ new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(detail.amount) }}
                                        <button
                                          v-if="line.type === 'shippingfee' && detail.shippingFees"
                                          @click.stop="showShippingFees(detail)"
                                          class="button is-small is-info is-light ml-2"
                                          title="Show shipping fee details"
                                        >
                                          <UIcon name="i-heroicons-information-circle" />
                                        </button>
                                      </td>
                                    </tr>
                                  </tbody>
                                  <tfoot>
                                    <tr class="has-background-light">
                                      <th :colspan="(line.type === 'fulfillment' || line.type === 'return') ? 6 : (line.type === 'shippingfee' ? 6 : 4)" class="has-text-right">
                                        Subtotal:
                                      </th>
                                      <th class="has-text-right">
                                        {{ new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(line.lineNetAmt) }}
                                      </th>
                                    </tr>
                                  </tfoot>
                                </table>
                              </div>
                            </td>
                          </tr>
                        </template>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="result.errors && result.errors.length > 0" class="mb-5">
              <div class="notification is-danger is-light">
                <strong>Errors ({{ result.errors.length }})</strong>
              </div>

              <div v-for="(error, index) in result.errors" :key="index" class="box mb-3 error-box">
                <div class="error-header">
                  <strong>{{ error.error }}</strong>
                  <span v-if="error.bpartnerId" class="tag is-light ml-2">Partner ID: {{ error.bpartnerId }}</span>
                </div>

                <div v-if="error.details && typeof error.details === 'object'" class="error-details mt-3">
                  <details>
                    <summary class="has-text-weight-semibold is-clickable">Show Details</summary>
                    <div class="mt-3">
                      <!-- Order Information -->
                      <div v-if="error.details.orderId" class="mb-2">
                        <strong>Order:</strong>
                        <nuxt-link
                          :to="`/sales/orders/${error.details.orderId}/edit`"
                          class="tag is-link is-light ml-2"
                        >
                          {{ error.details.orderDocumentNo || error.details.orderId }}
                        </nuxt-link>
                      </div>

                      <!-- Update Statistics -->
                      <div v-if="error.details.totalLines" class="mb-2">
                        <strong>Lines:</strong>
                        <span class="tag is-success is-light ml-2">{{ error.details.successfulUpdates || 0 }} successful</span>
                        <span class="tag is-danger is-light ml-2">{{ error.details.failedUpdates || 0 }} failed</span>
                        <span class="tag is-light ml-2">{{ error.details.totalLines }} total</span>
                      </div>

                      <!-- Failed Lines Table -->
                      <div v-if="error.details.failedLines && error.details.failedLines.length > 0" class="mt-3">
                        <strong>Failed Lines:</strong>
                        <table class="table is-fullwidth is-size-7 mt-2">
                          <thead>
                            <tr>
                              <th>Line ID</th>
                              <th>Type</th>
                              <th>Error</th>
                              <th>Status Code</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr v-for="(failedLine, idx) in error.details.failedLines" :key="idx">
                              <td class="is-family-monospace">#{{ failedLine.lineId }}</td>
                              <td><span class="tag is-warning is-light">{{ failedLine.type }}</span></td>
                              <td class="has-text-danger">{{ failedLine.error }}</td>
                              <td><span class="tag is-light">{{ failedLine.statusCode || 'N/A' }}</span></td>
                            </tr>
                          </tbody>
                        </table>
                      </div>

                      <!-- Raw Error Details -->
                      <div v-if="error.details.error" class="notification is-warning is-light mt-3">
                        <strong>Error Message:</strong> {{ error.details.error }}
                      </div>
                    </div>
                  </details>
                </div>
              </div>
            </div>

            <div v-if="result.message" class="notification is-info is-light">
              {{ result.message }}
            </div>
          </div>
        </div>

        <div class="modalFooter">
          <div class="buttons" style="margin-left: auto;">
            <button v-if="result" class="button" @click="handleClose">{{ t.close }}</button>
            <button v-else class="button" @click="handleClose">{{ t.close }}</button>
            <button
              v-if="!result"
              class="button is-primary"
              :class="{ 'is-loading': loading }"
              @click="handleGenerate"
            >
              {{ form.preview ? t.preview_mode : t.generate_orders }}
            </button>
            <!-- Fee report checkbox + Generate Selected button for preview mode -->
            <label v-if="result && result.preview" class="checkbox-label checkbox-label-success" style="margin-right: 12px; margin-bottom: 0; display: flex; align-items: center;">
              <input type="checkbox" v-model="form.createReport" class="checkbox-input" />
              <span class="checkbox-text">
                <strong>{{ t.create_fee_report }}</strong>
              </span>
            </label>
            <button
              v-if="result && result.preview"
              class="button is-success"
              :class="{ 'is-loading': loading }"
              :disabled="selectedOrders.size === 0"
              @click="handleGenerateSelected"
            >
              <UIcon name="i-heroicons-check-circle" class="mr-1" />
              {{ t.generate_orders }} ({{ selectedOrders.size }})
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Shipping Fees Details Modal -->
  <div v-if="shippingFeesModal.isOpen" class="modal-overlay" @click.self="closeShippingFeesModal">
    <div class="modal-wrapper" @click.self="closeShippingFeesModal">
      <div class="modalContent shipping-fees-modal">
        <div class="modalHeader">
          <h3 class="modalTitle">Shipping Fee Details</h3>
          <div class="cursor-pointer" @click="closeShippingFeesModal">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>

        <div class="modalBody" v-if="shippingFeesModal.data">
          <div class="box">
            <h4 class="subtitle is-5 mb-3">
              <UIcon name="i-heroicons-information-circle" class="mr-1" />
              Shipment Information
            </h4>
            <div class="columns is-multiline">
              <div class="column is-half">
                <strong>Fee Line ID:</strong> #{{ shippingFeesModal.data.id }}
              </div>
              <div class="column is-half">
                <strong>Shipment:</strong>
                <nuxt-link
                  v-if="shippingFeesModal.data.inoutId"
                  :to="`/sales/shipments/${shippingFeesModal.data.inoutId}/edit`"
                  class="tag is-info is-light"
                >
                  {{ shippingFeesModal.data.inoutDocumentNo || shippingFeesModal.data.inoutId }}
                </nuxt-link>
                <span v-else>N/A</span>
              </div>
              <div class="column is-half">
                <strong>Product:</strong> {{ shippingFeesModal.data.productName }}
              </div>
              <div class="column is-half">
                <strong>Date:</strong> {{ formatDate(shippingFeesModal.data.shippingDate) }}
              </div>
            </div>
          </div>

          <div v-if="shippingFeesModal.data.shippingFees" class="box">
            <h4 class="subtitle is-5 mb-3">
              <UIcon name="i-heroicons-truck" class="mr-1" />
              Shipping Details
            </h4>
            <div class="columns is-multiline is-size-7">
              <div class="column is-half">
                <strong>Service:</strong> {{ shippingFeesModal.data.shippingFees.serviceName || 'N/A' }}
              </div>
              <div class="column is-half">
                <strong>Paket Type:</strong> {{ shippingFeesModal.data.shippingFees.paketType || 'N/A' }}
              </div>
              <div class="column is-full">
                <strong>Description:</strong> {{ shippingFeesModal.data.shippingFees.productDescription || 'N/A' }}
              </div>
              <div class="column is-half">
                <strong>DHL Product ID:</strong> {{ shippingFeesModal.data.shippingFees.dhlProductId || 'N/A' }}
              </div>
              <div class="column is-half">
                <strong>Weight:</strong> {{ shippingFeesModal.data.shippingFees.extWeight != null ? `${shippingFeesModal.data.shippingFees.extWeight} kg` : 'N/A' }}
              </div>
            </div>
          </div>

          <div v-if="shippingFeesModal.data.shippingFees" class="box">
            <h4 class="subtitle is-5 mb-3">
              <UIcon name="i-heroicons-currency-euro" class="mr-1" />
              Cost Comparison
            </h4>

            <table class="table is-fullwidth is-striped comparison-table">
              <thead>
                <tr>
                  <th>Item</th>
                  <th class="has-text-right has-background-warning-light">External</th>
                  <th class="has-text-right has-background-info-light">Internal</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td><strong>Total</strong></td>
                  <td class="has-text-right has-text-weight-bold has-background-warning-light">
                    {{ shippingFeesModal.data.shippingFees.extTotal != null ? new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(shippingFeesModal.data.shippingFees.extTotal) : 'N/A' }}
                  </td>
                  <td class="has-text-right has-text-weight-bold has-background-info-light">
                    {{ shippingFeesModal.data.shippingFees.intTotal != null ? new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(shippingFeesModal.data.shippingFees.intTotal) : 'N/A' }}
                  </td>
                </tr>
                <tr>
                  <td>Cost</td>
                  <td class="has-text-right">
                    {{ shippingFeesModal.data.shippingFees.extCost != null ? new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(shippingFeesModal.data.shippingFees.extCost) : 'N/A' }}
                  </td>
                  <td class="has-text-right">
                    {{ shippingFeesModal.data.shippingFees.intCost != null ? new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(shippingFeesModal.data.shippingFees.intCost) : 'N/A' }}
                  </td>
                </tr>
                <tr>
                  <td>CO2</td>
                  <td class="has-text-right">
                    {{ shippingFeesModal.data.shippingFees.extCo2 != null ? new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(shippingFeesModal.data.shippingFees.extCo2) : 'N/A' }}
                  </td>
                  <td class="has-text-right">
                    {{ shippingFeesModal.data.shippingFees.intCo2 != null ? new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(shippingFeesModal.data.shippingFees.intCo2) : 'N/A' }}
                  </td>
                </tr>
                <tr>
                  <td>Energy</td>
                  <td class="has-text-right">
                    {{ shippingFeesModal.data.shippingFees.extEnergy != null ? new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(shippingFeesModal.data.shippingFees.extEnergy) : 'N/A' }}
                  </td>
                  <td class="has-text-right">
                    {{ shippingFeesModal.data.shippingFees.intEnergy != null ? new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(shippingFeesModal.data.shippingFees.intEnergy) : 'N/A' }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div v-if="shippingFeesModal.data.shippingFees" class="box">
            <h4 class="subtitle is-5 mb-3">
              <UIcon name="i-heroicons-check-badge" class="mr-1" />
              Status Flags
            </h4>
            <div class="flags-grid">
              <div class="flag-item">
                <span class="flag-label">Commissioned:</span>
                <span :class="['tag', shippingFeesModal.data.shippingFees.isCommissioned ? 'is-success' : 'is-light']">
                  {{ shippingFeesModal.data.shippingFees.isCommissioned ? 'Yes' : 'No' }}
                </span>
              </div>
              <div class="flag-item">
                <span class="flag-label">Commissioned Confirmed:</span>
                <span :class="['tag', shippingFeesModal.data.shippingFees.isCommissionedConfirmed ? 'is-success' : 'is-light']">
                  {{ shippingFeesModal.data.shippingFees.isCommissionedConfirmed ? 'Yes' : 'No' }}
                </span>
              </div>
              <div class="flag-item">
                <span class="flag-label">Laravel Acknowledged:</span>
                <span :class="['tag', shippingFeesModal.data.shippingFees.ackCommissionedLaravel ? 'is-success' : 'is-light']">
                  {{ shippingFeesModal.data.shippingFees.ackCommissionedLaravel ? 'Yes' : 'No' }}
                </span>
              </div>
              <div class="flag-item">
                <span class="flag-label">DHL Klein Paket:</span>
                <span :class="['tag', shippingFeesModal.data.shippingFees.isDHLKleinPaket ? 'is-info' : 'is-light']">
                  {{ shippingFeesModal.data.shippingFees.isDHLKleinPaket ? 'Yes' : 'No' }}
                </span>
              </div>
              <div class="flag-item">
                <span class="flag-label">Plenty In Progress:</span>
                <span :class="['tag', shippingFeesModal.data.shippingFees.isPlentyInProgress ? 'is-warning' : 'is-light']">
                  {{ shippingFeesModal.data.shippingFees.isPlentyInProgress ? 'Yes' : 'No' }}
                </span>
              </div>
              <div class="flag-item">
                <span class="flag-label">Accounting Exported:</span>
                <span :class="['tag', shippingFeesModal.data.shippingFees.isAccountingExported ? 'is-success' : 'is-light']">
                  {{ shippingFeesModal.data.shippingFees.isAccountingExported ? 'Yes' : 'No' }}
                </span>
              </div>
              <div class="flag-item">
                <span class="flag-label">Paket Accounting Exported:</span>
                <span :class="['tag', shippingFeesModal.data.shippingFees.isExportedPaketAccounting ? 'is-success' : 'is-light']">
                  {{ shippingFeesModal.data.shippingFees.isExportedPaketAccounting ? 'Yes' : 'No' }}
                </span>
              </div>
              <div class="flag-item">
                <span class="flag-label">External Fee Accounted:</span>
                <span :class="['tag', shippingFeesModal.data.shippingFees.isExternalFeeAccounted ? 'is-success' : 'is-light']">
                  {{ shippingFeesModal.data.shippingFees.isExternalFeeAccounted ? 'Yes' : 'No' }}
                </span>
              </div>
              <div class="flag-item">
                <span class="flag-label">Shipping Fee Accounted:</span>
                <span :class="['tag', shippingFeesModal.data.shippingFees.isShippingFeeAccounted ? 'is-success' : 'is-light']">
                  {{ shippingFeesModal.data.shippingFees.isShippingFeeAccounted ? 'Yes' : 'No' }}
                </span>
              </div>
            </div>
          </div>

          <div v-else class="notification is-warning">
            <UIcon name="i-heroicons-exclamation-triangle" class="mr-2" />
            No shipping fee details available for this record. Enable "Fetch Country Data" to load details.
          </div>
        </div>

        <div class="modalFooter">
          <button class="button" @click="closeShippingFeesModal">Close</button>
        </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;
}

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

.modalContent {
  max-width: 900px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .modalContent {
    max-height: 100vh;
    height: 100vh;
    max-width: 100%;
    border-radius: 0;
  }
}

.field .control {
  width: 100%;
}

.field .control :deep(select),
.field .control :deep(button) {
  width: 100%;
  min-width: 300px;
}

/* Range mode: two selects share a row, so they must shrink below the 300px min */
.range-control {
  display: flex;
  gap: 0.5rem;
}

.range-control :deep(select),
.range-control :deep(button) {
  min-width: 0 !important;
  flex: 1;
}

.orders-list {
  max-height: 400px;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .orders-list {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
}

.results-section {
  max-height: 60vh;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .results-section {
    max-height: calc(100vh - 120px);
  }

  .results-section .my-5 {
    margin-top: 0.5rem !important;
    margin-bottom: 0.5rem !important;
  }

  .results-section .mx-5 {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
}

.checkbox-label {
  display: flex;
  align-items: flex-start;
  gap: 0.75rem;
  padding: 1rem;
  background: #f0f9ff;
  border: 2px solid #3b82f6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.checkbox-label:hover {
  background: #dbeafe;
  border-color: #2563eb;
}

.checkbox-label-secondary {
  background: #fef3c7;
  border: 2px solid #f59e0b;
}

.checkbox-label-secondary:hover {
  background: #fde68a;
  border-color: #d97706;
}

.checkbox-label-secondary .checkbox-text strong {
  color: #92400e;
}

.checkbox-label-warning {
  background: #fef3e2;
  border: 2px solid #fb923c;
}

.checkbox-label-warning:hover {
  background: #fed7aa;
  border-color: #f97316;
}

.checkbox-label-warning .checkbox-text strong {
  color: #9a3412;
}

.checkbox-label-success {
  background: #d1fae5;
  border: 2px solid #10b981;
}

.checkbox-label-success:hover {
  background: #a7f3d0;
  border-color: #059669;
}

.checkbox-label-success .checkbox-text strong {
  color: #065f46;
}

.checkbox-input {
  margin-top: 0.25rem;
  width: 1.25rem;
  height: 1.25rem;
  cursor: pointer;
}

.checkbox-text {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.checkbox-text strong {
  color: #1e40af;
  font-size: 0.95rem;
}

.checkbox-hint {
  font-size: 0.8rem;
  color: #6b7280;
  line-height: 1.4;
}

.preview-box {
  border: 2px solid #3b82f6;
  background: #f0f9ff;
  transition: all 0.2s ease;
}

.selected-order {
  border-color: #10b981;
  background: #d1fae5;
}

.order-checkbox {
  display: flex;
  align-items: center;
  padding-right: 1rem;
}

.order-checkbox-input {
  width: 1.5rem;
  height: 1.5rem;
  cursor: pointer;
  accent-color: #10b981;
}

.selection-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  background: #f0f9ff;
  border-radius: 0.5rem;
  border: 1px solid #bfdbfe;
}

.checkbox-label-inline {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  font-size: 0.95rem;
  font-weight: 600;
  color: #1e40af;
}

.checkbox-input-inline {
  width: 1.25rem;
  height: 1.25rem;
  cursor: pointer;
  accent-color: #3b82f6;
}

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

@media (max-width: 768px) {
  .selection-controls {
    padding: 0.5rem;
    font-size: 0.85rem;
  }

  .checkbox-label-inline {
    font-size: 0.85rem;
  }

  .checkbox-input-inline {
    width: 1.1rem;
    height: 1.1rem;
  }

  .order-checkbox {
    padding-right: 0.5rem;
  }

  .order-checkbox-input {
    width: 1.25rem;
    height: 1.25rem;
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 1rem;
}

@media (max-width: 768px) {
  .order-header {
    flex-direction: row;
    flex-wrap: wrap;
    gap: 0.5rem;
  }

  .order-header .order-checkbox {
    order: -1;
    flex-shrink: 0;
  }

  .order-header .order-info {
    flex: 1 1 calc(100% - 3rem);
  }

  .order-header .order-total {
    flex: 1 1 100%;
    order: 2;
  }
}

.order-info {
  flex: 1;
}

.order-total {
  text-align: right;
}

@media (max-width: 768px) {
  .order-total {
    width: 100%;
    text-align: left;
  }
}

.preview-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1rem;
  margin-bottom: 0.5rem;
}

@media (max-width: 768px) {
  .preview-title {
    flex-wrap: wrap;
    font-size: 0.9rem;
  }
}

.preview-badge {
  font-size: 0.625rem;
  font-weight: 700;
  padding: 0.125rem 0.5rem;
  background: #3b82f6;
  color: white;
  border-radius: 4px;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

@media (max-width: 768px) {
  .preview-badge {
    font-size: 0.55rem;
    padding: 0.1rem 0.4rem;
  }
}

.order-lines {
  border-top: 1px solid #e5e7eb;
  padding-top: 1rem;
}

.order-lines .table {
  background: white;
  border-radius: 6px;
  overflow: hidden;
}

@media (max-width: 768px) {
  .order-lines {
    padding-top: 0.5rem;
    margin-left: 0 !important;
    margin-right: 0 !important;
  }

  .order-lines .table {
    display: block;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    border-radius: 0;
  }

  .order-lines .table thead,
  .order-lines .table tbody,
  .order-lines .table tr {
    display: table;
    width: 100%;
    table-layout: fixed;
  }

  .order-lines .table thead {
    width: 100%;
  }
}

.order-lines .table th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
}

@media (max-width: 768px) {
  .order-lines .table th {
    font-size: 0.65rem;
    padding: 0.5rem 0.25rem;
    white-space: nowrap;
  }
}

.order-lines .table td {
  vertical-align: middle;
}

@media (max-width: 768px) {
  .order-lines .table td {
    font-size: 0.7rem;
    padding: 0.5rem 0.25rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.position-row.has-details {
  cursor: pointer;
  transition: background-color 0.2s;
}

.position-row.has-details:hover {
  background-color: #f9fafb;
}

.position-row.is-expanded {
  background-color: #f0f9ff;
}

.expand-cell {
  width: 30px;
  padding: 0.5rem 0.25rem !important;
  text-align: center;
}

@media (max-width: 768px) {
  .expand-cell {
    width: 24px;
    padding: 0.25rem 0.15rem !important;
  }
}

.expand-icon {
  transition: transform 0.2s;
  color: #6b7280;
}

@media (max-width: 768px) {
  .expand-icon {
    font-size: 0.9rem;
  }
}

.details-row {
  background-color: #f9fafb;
}

.details-cell {
  padding: 1rem !important;
}

@media (max-width: 768px) {
  .details-cell {
    padding: 0 !important;
  }
}

.details-container {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 0.75rem;
}

@media (max-width: 768px) {
  .details-container {
    padding: 0.5rem;
    border-radius: 0;
    border-left: 0;
    border-right: 0;
  }
}

.details-table {
  margin-top: 0.5rem;
  font-size: 0.75rem !important;
  background: transparent;
}

@media (max-width: 768px) {
  .details-table {
    display: block;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    font-size: 0.65rem !important;
  }

  .details-table thead,
  .details-table tbody,
  .details-table tfoot,
  .details-table tr {
    display: table;
    width: 100%;
    table-layout: fixed;
  }

  .details-table th,
  .details-table td {
    padding: 0.35rem 0.2rem !important;
    font-size: 0.65rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.details-table thead {
  background: #f3f4f6;
}

.details-table tbody tr:hover {
  background-color: #fafafa;
}

.details-table tfoot {
  border-top: 2px solid #d1d5db;
}

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

@media (max-width: 768px) {
  .order-link {
    font-size: 0.7rem;
    padding: 0.25rem 0.4rem;
  }
}

.order-link:hover {
  background-color: #3b82f6 !important;
  color: white !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.country-flag {
  font-size: 1.5rem;
  cursor: help;
}

@media (max-width: 768px) {
  .country-flag {
    font-size: 1.2rem;
  }
}

.shipping-fees-modal {
  max-width: 800px;
}

@media (max-width: 768px) {
  .shipping-fees-modal {
    max-width: 100%;
    max-height: 100vh;
    height: 100vh;
    border-radius: 0;
  }
}

.shipping-fees-modal .box {
  margin-bottom: 1rem;
}

@media (max-width: 768px) {
  .shipping-fees-modal .box {
    margin-bottom: 0.5rem;
    margin-left: 0 !important;
    margin-right: 0 !important;
    border-radius: 0;
  }

  .shipping-fees-modal .columns {
    margin: 0 !important;
  }

  .shipping-fees-modal .column {
    padding: 0.5rem !important;
    font-size: 0.85rem;
  }

  .shipping-fees-modal .modalBody {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
}

.shipping-fees-modal .table {
  background: transparent;
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .shipping-fees-modal .table {
    display: block;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    font-size: 0.75rem;
  }
}

.shipping-fees-modal .table td {
  border: none;
  padding: 0.5rem;
}

@media (max-width: 768px) {
  .shipping-fees-modal .table td {
    padding: 0.35rem 0.25rem;
    font-size: 0.75rem;
  }
}

.comparison-table thead th {
  font-weight: 700;
  text-transform: uppercase;
  font-size: 0.75rem;
  letter-spacing: 0.05em;
}

@media (max-width: 768px) {
  .comparison-table thead th {
    font-size: 0.65rem;
    padding: 0.5rem 0.25rem;
  }

  .comparison-table tbody td {
    font-size: 0.7rem;
    padding: 0.5rem 0.25rem;
  }
}

.comparison-table tbody tr:hover {
  background-color: #f9fafb;
}

.flags-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 0.75rem;
}

@media (max-width: 768px) {
  .flags-grid {
    grid-template-columns: 1fr;
    gap: 0.5rem;
  }
}

.flag-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  background: #f9fafb;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

@media (max-width: 768px) {
  .flag-item {
    padding: 0.5rem;
  }
}

.flag-label {
  font-size: 0.875rem;
  font-weight: 500;
  color: #374151;
}

@media (max-width: 768px) {
  .flag-label {
    font-size: 0.75rem;
  }
}

.flag-item .tag {
  font-weight: 600;
  min-width: 50px;
  justify-content: center;
}

@media (max-width: 768px) {
  .flag-item .tag {
    font-size: 0.7rem;
    min-width: 40px;
  }
}

.error-box {
  border-left: 4px solid #f14668;
  background: #feecf0;
}

@media (max-width: 768px) {
  .error-box {
    border-radius: 0;
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
}

.error-header {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.error-details summary {
  cursor: pointer;
  user-select: none;
  color: #3273dc;
  padding: 0.5rem;
  background: #f5f5f5;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.error-details summary:hover {
  background: #e8e8e8;
}

.error-details table {
  background: white;
  border: 1px solid #dbdbdb;
}

@media (max-width: 768px) {
  .error-details table {
    display: block;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    font-size: 0.7rem;
  }

  .error-details table th,
  .error-details table td {
    padding: 0.5rem 0.35rem;
    font-size: 0.7rem;
  }
}

.error-details table thead {
  background: #f5f5f5;
}

/* Modal Header */
@media (max-width: 768px) {
  .modalHeader {
    padding: 1rem;
    border-radius: 0;
  }
}

/* Modal Footer Buttons */
.modalFooter .buttons {
  display: flex;
  gap: 0.5rem;
}

@media (max-width: 768px) {
  .modalFooter {
    padding: 0.75rem 1rem;
    border-radius: 0;
  }

  .modalFooter .buttons {
    flex-wrap: wrap;
    width: 100%;
  }

  .modalFooter .button {
    flex: 1;
    min-width: 100px;
    font-size: 0.85rem;
    padding: 0.5rem 0.75rem;
  }

  .modalFooter .button.is-success {
    flex: 1 1 100%;
    max-width: 100%;
  }
}

/* Shipping Fee Info Button */
.details-table .button.is-small {
  padding: 0.25rem 0.5rem;
}

@media (max-width: 768px) {
  .details-table .button.is-small {
    padding: 0.15rem 0.35rem;
    font-size: 0.65rem;
    margin-left: 0.25rem !important;
  }

  .details-table .button.is-small :deep(svg) {
    width: 0.85rem;
    height: 0.85rem;
  }
}

/* Modal Body */
@media (max-width: 768px) {
  .modalBody {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }

  .modalBody .my-5 {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }

  .modalBody .mx-5 {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
}

/* Notification boxes */
@media (max-width: 768px) {
  .notification {
    padding: 0.75rem 0.75rem;
    font-size: 0.85rem;
    border-radius: 0;
    margin-left: 0 !important;
    margin-right: 0 !important;
  }

  .notification strong {
    font-size: 0.9rem;
  }

  .notification p {
    font-size: 0.8rem;
  }
}

/* Box elements */
@media (max-width: 768px) {
  .box {
    padding: 0.75rem;
    border-radius: 0;
    margin-left: 0 !important;
    margin-right: 0 !important;
  }

  .box .is-size-7 {
    font-size: 0.7rem !important;
  }

  .box .is-size-5 {
    font-size: 1rem !important;
  }
}

/* Tags */
@media (max-width: 768px) {
  .tag:not(.flag-item .tag) {
    font-size: 0.65rem;
    padding: 0.25rem 0.5rem;
  }
}

/* Order Links in Success Notification */
.validation-results {
  border-top: 1px solid #e5e7eb;
  padding-top: 1rem;
}

.validation-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  align-items: center;
}

.validation-table {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  overflow: hidden;
}

.validation-table thead {
  background: #f9fafb;
}

.validation-table tbody tr:hover {
  background-color: #fafafa;
}

.validation-table td {
  vertical-align: middle;
}

@media (max-width: 768px) {
  .validation-results {
    padding-top: 0.5rem;
  }

  .validation-summary {
    gap: 0.25rem;
  }

  .validation-summary .tag {
    font-size: 0.65rem;
    padding: 0.25rem 0.5rem;
  }

  .validation-table {
    display: block;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    font-size: 0.65rem !important;
  }

  .validation-table th,
  .validation-table td {
    padding: 0.35rem 0.25rem !important;
    font-size: 0.65rem;
    white-space: nowrap;
  }
}

.order-links {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.order-link-tag {
  cursor: pointer;
  text-decoration: none;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
}

.order-link-tag:hover {
  background-color: #2366d1 !important;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

@media (max-width: 768px) {
  .order-links {
    gap: 0.35rem;
  }

  .order-link-tag {
    font-size: 0.7rem;
    padding: 0.4rem 0.6rem;
  }
}
</style>
