<template>
  <div class="unified-receipt-form">
    <!-- Compact Upload Zone -->
    <CompactUploadZone
      v-if="!readonly"
      ref="uploadZone"
      @ocr-result="onOCRResult"
      @file-selected="onFileSelected"
      @error="onOCRError"
    />

    <!-- Main Form - Ultra Compact Flat Layout -->
    <div class="form-body">
      <!-- Row 1: Supplier DB + CUI inline -->
      <div class="form-row">
        <span class="inline-label">Furnizor</span>
        <AutoComplete
          v-model="form.partner_name"
          :suggestions="filteredPartners"
          optionLabel="name"
          field="name"
          @complete="searchPartners"
          @item-select="onPartnerSelect"
          placeholder="Cauta..."
          dropdown
          :forceSelection="false"
          :disabled="readonly"
          class="supplier-input"
        />
        <InputText
          v-model="form.cui"
          placeholder="CUI"
          :disabled="readonly"
          class="cui-input"
        />
        <OCRConfidenceIndicator
          v-if="ocrData?.confidence_vendor"
          :confidence="ocrData.confidence_vendor"
          size="small"
        />
        <span v-if="supplierSource" class="source-tag ok" v-tooltip.top="'Gasit in ' + supplierSource">
          <i class="pi pi-check"></i>
        </span>
        <span v-else-if="supplierWarning" class="source-tag warn" @click="$emit('create-supplier')" v-tooltip.top="'Click pentru a crea'">
          <i class="pi pi-plus"></i>
        </span>
        <Button
          v-if="!readonly"
          icon="pi pi-sync"
          text
          rounded
          size="small"
          :loading="syncingSuppliers"
          @click="$emit('sync-suppliers')"
          class="sync-btn"
          v-tooltip.top="'Sincronizeaza'"
        />
      </div>

      <!-- Row 2: OCR Supplier (if different) - subtle -->
      <div class="form-row ocr-hint" v-if="ocrData?.partner_name && ocrData.partner_name !== getPartnerNameString()">
        <span class="hint-label">OCR:</span>
        <span class="hint-value">{{ ocrData.partner_name }}</span>
        <span class="hint-value" v-if="ocrData.cui">({{ ocrData.cui }})</span>
      </div>

      <!-- Row 2b: Client OCR (B2B receipts with buyer info) -->
      <div class="form-row client-hint" v-if="ocrData?.client_name || ocrData?.client_cui">
        <span class="hint-label">Client:</span>
        <span class="hint-value">{{ ocrData.client_name || '—' }}</span>
        <span class="hint-value" v-if="ocrData.client_cui">({{ ocrData.client_cui }})</span>
        <OCRConfidenceIndicator
          v-if="ocrData?.confidence_client"
          :confidence="ocrData.confidence_client"
          size="small"
        />
      </div>

      <!-- Row 3: Type + Nr + Date inline -->
      <div class="form-row">
        <Dropdown
          v-model="form.receipt_type"
          :options="receiptTypeOptions"
          optionLabel="label"
          optionValue="value"
          :disabled="readonly"
          class="type-select dropdown-borderless"
        />
        <span class="inline-label nr-label">Nr.</span>
        <InputText
          v-model="form.receipt_number"
          placeholder="–"
          :disabled="readonly"
          class="nr-input"
        />
        <span class="inline-label">Data</span>
        <Calendar
          v-model="form.receipt_date"
          dateFormat="dd.mm.yy"
          showIcon
          :disabled="readonly"
          class="date-input"
        />
        <OCRConfidenceIndicator
          v-if="ocrData?.confidence_date"
          :confidence="ocrData.confidence_date"
          size="small"
        />
      </div>

      <!-- Row 4: TOTAL + Payments (merged on same row) -->
      <div class="form-row total-row">
        <span class="total-label">TOTAL</span>
        <InputNumber
          v-model="form.amount"
          :minFractionDigits="2"
          :maxFractionDigits="2"
          :disabled="readonly"
          placeholder="0.00"
          class="total-input"
        />
        <OCRConfidenceIndicator
          v-if="ocrData?.confidence_amount"
          :confidence="ocrData.confidence_amount"
          size="small"
        />

        <!-- Separator vizual -->
        <span class="pay-separator">│</span>

        <!-- Payment methods inline -->
        <div class="pay-inline">
          <div class="pay-item">
            <span class="pay-label">Card</span>
            <InputNumber
              v-model="form.payments.CARD"
              :minFractionDigits="2"
              :maxFractionDigits="2"
              :disabled="readonly"
              placeholder="0.00"
              class="pay-input"
            />
          </div>
          <div class="pay-item">
            <span class="pay-label">Cash</span>
            <InputNumber
              v-model="form.payments.NUMERAR"
              :minFractionDigits="2"
              :maxFractionDigits="2"
              :disabled="readonly"
              placeholder="0.00"
              class="pay-input"
            />
          </div>
          <div class="pay-item">
            <span class="pay-label">Alte</span>
            <InputNumber
              v-model="form.payments.ALTE.amount"
              :minFractionDigits="2"
              :maxFractionDigits="2"
              :disabled="readonly"
              placeholder="0.00"
              class="pay-input"
            />
          </div>
          <!-- Payment confidence -->
          <OCRConfidenceIndicator
            v-if="ocrData?.confidence_payment && hasPaymentFromOCR"
            :confidence="ocrData.confidence_payment"
            size="small"
            v-tooltip.top="'Incredere extragere plati'"
          />
        </div>
      </div>

      <!-- Payment mismatch warning -->
      <div v-if="showPaymentMismatch" class="mismatch-msg">
        <i class="pi pi-exclamation-triangle"></i>
        Plati ({{ formatAmount(paymentTotal) }}) ≠ Total ({{ formatAmount(form.amount) }})
      </div>

      <!-- Row 5: TVA inline -->
      <div class="tva-row-wrapper">
        <TvaCompactFields
          v-model="form.tva"
          :disabled="readonly"
        />
        <!-- TVA confidence -->
        <OCRConfidenceIndicator
          v-if="ocrData?.confidence_tva && hasTvaFromOCR"
          :confidence="ocrData.confidence_tva"
          size="small"
          v-tooltip.top="'Incredere extragere TVA'"
          class="tva-confidence"
        />
      </div>

      <!-- Row 7: Expense Type + Description (desc below) -->
      <div class="form-row expense-row">
        <Dropdown
          v-model="form.expense_type_code"
          :options="expenseTypes"
          optionLabel="name"
          optionValue="code"
          placeholder="Cheltuiala..."
          :disabled="readonly"
          class="expense-select dropdown-borderless"
        />
        <InputText
          v-model="form.description"
          placeholder="Descriere..."
          :disabled="readonly"
          class="desc-input"
        />
      </div>

      <!-- Attachments (compact inline) -->
      <div class="form-row attachments-row" v-if="existingAttachments.length || selectedFiles.length || !readonly">
        <span class="inline-label">Atasamente</span>
        <div class="chips-wrap">
          <span
            v-for="att in existingAttachments"
            :key="att.id"
            class="file-chip"
            @click="$emit('download-attachment', att)"
          >
            <i :class="att.mime_type?.startsWith('image/') ? 'pi pi-image' : 'pi pi-file-pdf'"></i>
            {{ truncateFilename(att.filename) }}
            <i v-if="!readonly" class="pi pi-times chip-remove" @click.stop="$emit('remove-attachment', att.id)"></i>
          </span>
          <span
            v-for="(file, idx) in selectedFiles"
            :key="'new-' + idx"
            class="file-chip new"
          >
            <i :class="file.type?.startsWith('image/') ? 'pi pi-image' : 'pi pi-file-pdf'"></i>
            {{ truncateFilename(file.name) }}
            <i class="pi pi-times chip-remove" @click="$emit('remove-file', idx)"></i>
          </span>
          <button v-if="!readonly" class="add-chip" @click="triggerFileInput">
            <i class="pi pi-plus"></i>
          </button>
        </div>
        <input
          ref="fileInputRef"
          type="file"
          accept="image/*,application/pdf"
          multiple
          class="hidden-input"
          @change="onFilesSelected"
        />
      </div>

      <!-- OCR Raw Text Toggle (at bottom) -->
      <div class="form-row ocr-text-row" v-if="ocrData?.raw_text">
        <Button
          :label="showRawText ? 'Ascunde' : 'Text OCR'"
          :icon="showRawText ? 'pi pi-eye-slash' : 'pi pi-eye'"
          size="small"
          severity="secondary"
          text
          @click="showRawText = !showRawText"
        />
        <span v-if="ocrData.ocr_engine" class="ocr-meta">{{ ocrData.ocr_engine }}</span>
        <span v-if="ocrData.processing_time_ms" class="ocr-meta">{{ formatTime(ocrData.processing_time_ms) }}</span>
      </div>
      <pre v-if="showRawText && ocrData?.raw_text" class="ocr-raw-text">{{ ocrData.raw_text }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import AutoComplete from 'primevue/autocomplete'
import Dropdown from 'primevue/dropdown'
import InputText from 'primevue/inputtext'
import InputNumber from 'primevue/inputnumber'
import Calendar from 'primevue/calendar'
import Button from 'primevue/button'

import CompactUploadZone from './CompactUploadZone.vue'
import TvaCompactFields from './TvaCompactFields.vue'
import OCRConfidenceIndicator from '@data-entry/components/ocr/OCRConfidenceIndicator.vue'

const props = defineProps({
  modelValue: { type: Object, required: true },
  ocrData: { type: Object, default: null },
  partners: { type: Array, default: () => [] },
  expenseTypes: { type: Array, default: () => [] },
  supplierSource: { type: String, default: null },
  supplierWarning: { type: Boolean, default: false },
  syncingSuppliers: { type: Boolean, default: false },
  existingAttachments: { type: Array, default: () => [] },
  selectedFiles: { type: Array, default: () => [] },
  readonly: { type: Boolean, default: false },
})

const emit = defineEmits([
  'update:modelValue', 'ocr-result', 'file-selected', 'ocr-error',
  'partner-selected', 'sync-suppliers', 'create-supplier',
  'add-files', 'remove-file', 'remove-attachment', 'download-attachment',
])

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

const uploadZone = ref(null)
const fileInputRef = ref(null)
const showRawText = ref(false)
const filteredPartners = ref([])

const receiptTypeOptions = [
  { value: 'bon_fiscal', label: 'Bon fiscal' },
  { value: 'chitanta', label: 'Chitanta' },
]

const getPartnerNameString = () => {
  const pn = form.value.partner_name
  return typeof pn === 'string' ? pn : pn?.name || ''
}

const searchPartners = (event) => {
  const query = event.query.toLowerCase()
  filteredPartners.value = props.partners.filter(p =>
    p.name.toLowerCase().includes(query) ||
    (p.fiscal_code && p.fiscal_code.toLowerCase().includes(query))
  )
}

const onPartnerSelect = (event) => {
  const partner = event.value
  if (partner) {
    form.value.cui = partner.fiscal_code || ''
    if (partner.address) form.value.vendor_address = partner.address
    emit('partner-selected', partner)
  }
}

const onOCRResult = (result) => emit('ocr-result', result)
const onFileSelected = (file) => emit('file-selected', file)
const onOCRError = (error) => emit('ocr-error', error)

const triggerFileInput = () => fileInputRef.value?.click()

const onFilesSelected = async (event) => {
  const files = Array.from(event.target?.files || [])
  if (files.length === 0) return
  const clonedFiles = await Promise.all(files.map(async (file) => {
    try {
      const ab = await file.arrayBuffer()
      return new File([ab], file.name, { type: file.type, lastModified: file.lastModified })
    } catch { return file }
  }))
  emit('add-files', clonedFiles)
  if (fileInputRef.value) fileInputRef.value.value = ''
}

const truncateFilename = (name, max = 15) => {
  if (!name || name.length <= max) return name
  const ext = name.split('.').pop()
  return name.substring(0, max - ext.length - 3) + '...' + ext
}

const formatTime = (ms) => ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`

// Payment mismatch logic (moved from PaymentCompactFields)
const paymentTotal = computed(() => {
  return (form.value.payments?.CARD || 0) +
         (form.value.payments?.NUMERAR || 0) +
         (form.value.payments?.ALTE?.amount || 0)
})

const showPaymentMismatch = computed(() => {
  if (!form.value.amount || form.value.amount === 0) return false
  if (paymentTotal.value === 0) return false
  return Math.abs(paymentTotal.value - form.value.amount) > 0.02
})

const formatAmount = (amount) => {
  return parseFloat(amount || 0).toLocaleString('ro-RO', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// Check if OCR extracted payment data
const hasPaymentFromOCR = computed(() => {
  const pm = props.ocrData?.payment_methods
  return pm && pm.length > 0
})

// Check if OCR extracted TVA data
const hasTvaFromOCR = computed(() => {
  const tva = props.ocrData?.tva_entries
  return tva && tva.length > 0
})

defineExpose({
  resetUpload: () => uploadZone.value?.reset(),
  processOCR: () => uploadZone.value?.processOCR(),
})
</script>

<style scoped>
.unified-receipt-form {
  width: 100%;
  max-width: 100%;
}

@media (min-width: 640px) {
  .unified-receipt-form {
    max-width: 560px;
    margin: 0 auto;
  }
}

.form-body {
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: 6px;
  padding: 0.25rem;
  overflow: hidden;
}

/* === ULTRA COMPACT INLINE ROW === */
.form-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 0.35rem;
  padding: 0.3rem 0.4rem;
  flex-wrap: wrap;
  min-height: 32px;
}

.form-row + .form-row {
  border-top: 1px solid var(--surface-border);
}

/* Inline labels - compact */
.inline-label {
  font-size: var(--text-xs);  /* 12px - uniform */
  font-weight: var(--font-semibold);
  color: var(--text-color-secondary);
  white-space: nowrap;
  flex-shrink: 0;
}

/* === SUPPLIER ROW === */
.supplier-input {
  flex: 1;
  min-width: 100px;
}

.supplier-input :deep(.p-autocomplete-input) {
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform */
  height: 32px;
}

.supplier-input :deep(.p-autocomplete-dropdown) {
  width: 24px;
}

.cui-input {
  width: 140px;
  flex-shrink: 0;
}

.cui-input:deep(input) {
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform */
  height: 32px;
}

/* Source tag - tiny icon only */
.source-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  flex-shrink: 0;
}

.source-tag i {
  font-size: var(--text-xs);
}

.source-tag.ok {
  background: var(--green-100);
  color: var(--green-600);
}

.source-tag.warn {
  background: var(--yellow-100);
  color: var(--yellow-700);
  cursor: pointer;
}

.source-tag.warn:hover {
  background: var(--yellow-200);
}

.sync-btn {
  width: 22px !important;
  height: 22px !important;
  padding: 0 !important;
}

.sync-btn :deep(.pi) {
  font-size: var(--text-xs);
}

/* === OCR HINT ROW === */
.ocr-hint {
  background: var(--blue-50);
  padding: var(--space-xs) var(--space-sm) !important;
  min-height: 24px !important;
  font-size: var(--text-xs);  /* 12px - uniform for hints */
}

.hint-label {
  color: var(--blue-500);
  font-weight: 500;
}

.hint-value {
  color: var(--blue-700);
}

/* === CLIENT HINT ROW (cyan for B2B buyer info) === */
.client-hint {
  background: var(--cyan-50);
  padding: var(--space-xs) var(--space-sm) !important;
  min-height: 24px !important;
  font-size: var(--text-xs);
}

.client-hint .hint-label {
  color: var(--cyan-600);
}

.client-hint .hint-value {
  color: var(--cyan-700);
}

/* === DOCUMENT ROW (type/nr/date) === */
.type-select {
  width: auto;
  min-width: 100px;
}

/* Push nr and date to the right - margin on LABEL not input */
.nr-label {
  margin-left: auto;
}

.type-select :deep(.p-dropdown) {
  height: 32px;
}

.type-select :deep(.p-dropdown-label) {
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform */
}

.nr-input {
  width: 90px;
  flex-shrink: 0;
}

.nr-input:deep(input) {
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform */
  height: 32px;
  text-align: right;
}

.date-input {
  width: 150px;
  flex-shrink: 0;
}

.date-input :deep(.p-inputtext) {
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform */
  height: 32px;
}

.date-input :deep(.p-datepicker-trigger) {
  width: 28px;
}

/* === TOTAL ROW (with payments inline) === */
.total-row {
  display: flex;
  flex-wrap: nowrap;  /* FORCE single line */
  align-items: center;
  gap: var(--space-xs, 0.25rem);  /* smaller gap */
  background: var(--green-50);
  border-radius: var(--radius-sm, 4px);
  padding: var(--space-xs, 0.25rem) var(--space-sm, 0.5rem) !important;
  margin: var(--space-xs, 0.25rem) 0;
  overflow-x: auto;  /* scroll if needed on very small screens */
}

.total-label {
  font-weight: 700;
  font-size: var(--text-sm, 0.875rem);
  color: var(--text-color);
  flex-shrink: 0;
}

.total-input {
  width: 80px;  /* narrower to fit with payments */
  flex-shrink: 0;
}

.total-input :deep(.p-inputnumber-input) {
  width: 100%;
  font-size: var(--text-base);
  font-weight: var(--font-semibold);  /* 600, not 700 */
  text-align: right;
  padding: var(--space-xs) var(--space-sm);
  height: 32px;
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  color: var(--text-color);
}

/* Payment separator */
.pay-separator {
  color: var(--text-color-secondary);
  font-weight: 300;
  margin: 0 var(--space-xs, 0.25rem);
}

/* Payment methods inline container */
.pay-inline {
  display: flex;
  flex-wrap: nowrap;  /* stay on same line */
  gap: var(--space-sm, 0.5rem);  /* smaller gap */
  align-items: center;
}

.pay-item {
  display: flex;
  align-items: center;
  gap: var(--space-xs, 0.25rem);
}

.pay-label {
  font-size: var(--text-xs);  /* 12px - labels */
  font-weight: var(--font-medium);
  color: var(--text-color-secondary);
}

.pay-input {
  width: 70px;
}

.pay-input :deep(.p-inputnumber-input) {
  width: 100%;
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform for inputs */
  font-weight: var(--font-normal);
  text-align: right;
  height: 32px;  /* uniform height */
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  color: var(--text-color);
}

/* Payment mismatch warning */
.mismatch-msg {
  display: flex;
  align-items: center;
  gap: var(--space-xs, 0.25rem);
  padding: var(--space-xs, 0.25rem) var(--space-sm, 0.5rem);
  background: color-mix(in srgb, var(--yellow-500) 15%, var(--surface-card));
  border: 1px solid var(--yellow-500);
  border-radius: var(--radius-sm, 4px);
  font-size: var(--text-xs, 0.75rem);
  color: var(--yellow-700);
  margin: var(--space-xs, 0.25rem) 0;
}

.mismatch-msg i {
  font-size: var(--text-xs, 0.75rem);
}

/* === TVA ROW WRAPPER === */
.tva-row-wrapper {
  display: flex;
  align-items: flex-start;
  gap: var(--space-xs);
}

.tva-row-wrapper > :first-child {
  flex: 1;
}

.tva-confidence {
  margin-top: var(--space-sm);  /* align with TVA row content */
  flex-shrink: 0;
}

/* === EXPENSE/DESCRIPTION ROW === */
.expense-row {
  flex-wrap: wrap;
  background: var(--blue-50);
  border-radius: var(--radius-sm);
  padding: var(--space-sm) var(--space-md);
  margin: var(--space-xs) 0;
}

.expense-select {
  width: auto;
  min-width: 160px;  /* wider */
}

.expense-select :deep(.p-dropdown) {
  height: 32px;
}

.expense-select :deep(.p-dropdown-label) {
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform */
}

.desc-input {
  flex: 1;
  min-width: 80px;
  flex-basis: 100%;
  margin-top: var(--space-xs);
}

.desc-input:deep(input) {
  padding: var(--space-xs) var(--space-sm);
  font-size: var(--text-sm);  /* 14px - uniform */
  height: 32px;
}

/* === ATTACHMENTS ROW === */
.attachments-row {
  align-items: center;
}

.chips-wrap {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-xs);
  flex: 1;
  align-items: center;
}

.file-chip {
  display: inline-flex;
  align-items: center;
  gap: var(--space-xs);
  padding: var(--space-xs) var(--space-sm);
  background: var(--surface-hover);
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);  /* bigger - 0.875rem */
  cursor: pointer;
}

.file-chip:hover {
  background: var(--surface-200);
}

.file-chip.new {
  background: var(--blue-50);
  border: 1px dashed var(--blue-300);
}

.file-chip i {
  font-size: var(--text-sm);
}

.chip-remove {
  font-size: var(--text-xs) !important;
  color: var(--text-color-secondary);
  margin-left: var(--space-xs);
}

.chip-remove:hover {
  color: var(--red-500);
}

.add-chip {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: var(--surface-hover);
  border: 1px dashed var(--surface-border);
  border-radius: var(--radius-sm);
  cursor: pointer;
  color: var(--text-color-secondary);
}

.add-chip:hover {
  background: var(--primary-50);
  border-color: var(--primary-300);
  color: var(--primary-500);
}

.add-chip i {
  font-size: var(--text-xs);
}

.hidden-input {
  display: none;
}

/* === OCR TEXT ROW === */
.ocr-text-row {
  justify-content: flex-start;
}

.ocr-meta {
  font-size: var(--text-xs);  /* 12px - uniform */
  color: var(--text-color-secondary);
  background: var(--surface-hover);
  padding: 2px var(--space-xs);
  border-radius: var(--radius-sm);
}

.ocr-raw-text {
  margin: 0;
  padding: var(--space-sm);
  background: var(--surface-ground);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);  /* 12px - uniform for raw text */
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 120px;
  overflow: auto;
  color: var(--text-color-secondary);
}

/* === MOBILE STACKING === */
@media (max-width: 480px) {
  .form-row {
    flex-wrap: wrap;
    gap: var(--space-xs);
  }

  /* Supplier row */
  .supplier-input {
    width: 100%;
    flex: 1 1 100%;
  }

  .cui-input {
    width: 100%;
    flex: 1 1 100%;
  }

  /* Document row - stack vertically but keep label+input together */
  .type-select {
    width: 100%;
    flex: 1 1 100%;
  }

  .type-select :deep(.p-dropdown) {
    width: 100%;
  }

  /* Nr. label removed margin-left on mobile */
  .nr-label {
    margin-left: 0;
  }

  .nr-input {
    flex: 1;
    width: auto;
  }

  /* Data on same line as Nr on mobile */
  .date-input {
    flex: 1;
    width: auto;
  }

  /* Expense row */
  .expense-row {
    flex-direction: column;
    align-items: stretch;
  }

  .expense-select {
    width: 100%;
    min-width: unset;
  }

  .expense-select :deep(.p-dropdown) {
    width: 100%;
  }

  .desc-input {
    width: 100%;
    flex-basis: 100%;
    margin-top: 0;
  }

  /* Payment methods stack on mobile */
  .total-row {
    flex-wrap: wrap;
  }

  .pay-separator {
    display: none;
  }

  .pay-inline {
    width: 100%;
    flex-wrap: wrap;
    margin-top: var(--space-xs);
    justify-content: flex-start;
  }

  .pay-item {
    flex: 1 1 auto;
    min-width: 80px;
  }

  .pay-input {
    flex: 1;
    width: auto;
    min-width: 60px;
  }
}

/* === DARK MODE === */
[data-theme="dark"] .source-tag.ok {
  background: rgba(34, 197, 94, 0.2);
  color: var(--green-400);
}

[data-theme="dark"] .source-tag.warn {
  background: rgba(234, 179, 8, 0.2);
  color: var(--yellow-400);
}

[data-theme="dark"] .ocr-hint {
  background: rgba(59, 130, 246, 0.1);
}

[data-theme="dark"] .client-hint {
  background: rgba(6, 182, 212, 0.08);
}

[data-theme="dark"] .client-hint .hint-label {
  color: var(--cyan-400);
}

[data-theme="dark"] .client-hint .hint-value {
  color: var(--cyan-300);
}

[data-theme="dark"] .total-row {
  background: rgba(34, 197, 94, 0.1);
}

[data-theme="dark"] .mismatch-msg {
  background: rgba(234, 179, 8, 0.15);
  color: var(--yellow-400);
}

[data-theme="dark"] .expense-row {
  background: rgba(59, 130, 246, 0.08);
}

[data-theme="dark"] .file-chip {
  background: var(--surface-100);
}

[data-theme="dark"] .file-chip.new {
  background: rgba(59, 130, 246, 0.1);
  border-color: var(--blue-700);
}

[data-theme="dark"] .add-chip {
  background: var(--surface-100);
  border-color: var(--surface-300);
}
</style>

<!-- NON-SCOPED: Comprehensive dark mode overrides for TVA/Payment grids -->
<style>
/* ========================================
   DROPDOWN BORDERLESS - All dropdowns in form
   ======================================== */
.unified-receipt-form .p-dropdown {
  border: none !important;
  background: transparent !important;
  box-shadow: none !important;
}

.unified-receipt-form .p-dropdown:hover,
.unified-receipt-form .p-dropdown:focus,
.unified-receipt-form .p-dropdown.p-focus {
  border: none !important;
  box-shadow: none !important;
}

.unified-receipt-form .p-dropdown .p-dropdown-trigger {
  width: 1.25rem;
}

/* ========================================
   DARK MODE: TVA & PAYMENT GRID INPUTS
   ======================================== */

/* InputNumber inputs in TVA/Payment grids */
[data-theme="dark"] .tva-row .p-inputnumber-input,
[data-theme="dark"] .pay-row .p-inputnumber-input {
  background: #1e293b !important;
  color: #f1f5f9 !important;
  border: 1px solid #475569 !important;
}

[data-theme="dark"] .tva-row .p-inputnumber-input:focus,
[data-theme="dark"] .pay-row .p-inputnumber-input:focus {
  border-color: #3b82f6 !important;
  box-shadow: 0 0 0 1px #3b82f6 !important;
}

/* Dropdown labels in dark mode */
[data-theme="dark"] .tva-row .p-dropdown-label,
[data-theme="dark"] .pay-row .p-dropdown-label {
  color: #f1f5f9 !important;
}

/* Grid items background in dark mode */
[data-theme="dark"] .tva-row .grid-item,
[data-theme="dark"] .pay-row .grid-item {
  background: #1e293b !important;
  border-color: #475569 !important;
}

[data-theme="dark"] .tva-row .grid-item.active {
  background: rgba(34, 197, 94, 0.15) !important;
  border-color: #22c55e !important;
}

[data-theme="dark"] .pay-row .grid-item.active {
  background: rgba(59, 130, 246, 0.15) !important;
  border-color: #3b82f6 !important;
}

/* Item code badges in dark mode */
[data-theme="dark"] .tva-row .item-code {
  background: #334155 !important;
  color: #f1f5f9 !important;
}

/* Entry chips (collapsed state) in dark mode */
[data-theme="dark"] .tva-row .entry-chip,
[data-theme="dark"] .pay-row .entry-chip {
  background: #334155 !important;
  color: #f1f5f9 !important;
  border-color: #475569 !important;
}

/* ========================================
   AUTO DARK MODE (prefers-color-scheme)
   ======================================== */
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) .tva-row .p-inputnumber-input,
  :root:not([data-theme="light"]) .pay-row .p-inputnumber-input {
    background: #1e293b !important;
    color: #f1f5f9 !important;
    border: 1px solid #475569 !important;
  }

  :root:not([data-theme="light"]) .tva-row .grid-item,
  :root:not([data-theme="light"]) .pay-row .grid-item {
    background: #1e293b !important;
    border-color: #475569 !important;
  }

  :root:not([data-theme="light"]) .tva-row .entry-chip,
  :root:not([data-theme="light"]) .pay-row .entry-chip {
    background: #334155 !important;
    color: #f1f5f9 !important;
  }

  :root:not([data-theme="light"]) .expense-row {
    background: rgba(59, 130, 246, 0.08);
  }

  :root:not([data-theme="light"]) .client-hint {
    background: rgba(6, 182, 212, 0.08);
  }

  :root:not([data-theme="light"]) .client-hint .hint-label {
    color: var(--cyan-400);
  }

  :root:not([data-theme="light"]) .client-hint .hint-value {
    color: var(--cyan-300);
  }
}
</style>
