<template>
  <div class="ocr-metrics-view">
    <div class="page-header">
      <h1>Metrici OCR</h1>
    </div>

    <!-- Loading State -->
    <div v-if="loading && !hasData" class="loading-container">
      <ProgressSpinner style="width: 50px; height: 50px" strokeWidth="4" />
      <p>Se incarca metricile...</p>
    </div>

    <!-- Empty State -->
    <div v-else-if="!hasData" class="empty-state">
      <i class="pi pi-chart-bar empty-state-icon"></i>
      <h3>Nu exista date</h3>
      <p>Procesati imagini cu OCR pentru a vedea statisticile.</p>
    </div>

    <!-- Metrics Content -->
    <div v-else class="metrics-content">

      <!-- Engine Summary Section with period selector -->
      <div class="section-card">
        <div class="section-header">
          <h3 class="section-title">Performanta per Motor OCR</h3>
          <div class="section-actions">
            <Dropdown
              v-model="selectedDays"
              :options="daysOptions"
              optionLabel="label"
              optionValue="value"
              placeholder="Perioada"
              class="days-selector dropdown-borderless"
            />
            <Button
              icon="pi pi-refresh"
              :label="isMobile ? '' : 'Actualizeaza'"
              @click="loadAllMetrics"
              :loading="loading"
              severity="secondary"
              size="small"
            />
          </div>
        </div>

        <!-- Desktop: DataTable -->
        <DataTable
          v-if="!isMobile"
          :value="engineSummary"
          stripedRows
          responsiveLayout="scroll"
          class="engine-summary-table"
          sortField="total_jobs"
          :sortOrder="-1"
        >
          <Column field="engine" header="Motor OCR" :sortable="true">
            <template #body="{ data }">
              <div class="engine-cell">
                <span class="engine-badge" :class="getBaseEngine(data.engine)">
                  {{ formatEngineName(data.engine) }}
                </span>
                <span
                  v-if="getEngineBadge(data.engine)"
                  class="dynamic-badge"
                  :class="getEngineBadge(data.engine).class"
                >
                  {{ getEngineBadge(data.engine).text }}
                </span>
              </div>
            </template>
          </Column>
          <Column field="total_jobs" header="Total Joburi" :sortable="true" style="text-align: right;">
            <template #body="{ data }">
              {{ data.total_jobs }}
            </template>
          </Column>
          <Column field="success_rate" header="Rata Succes" :sortable="true" style="text-align: right;">
            <template #body="{ data }">
              <span class="success-value">{{ formatPercent(data.success_rate) }}</span>
            </template>
          </Column>
          <Column field="avg_processing_time_ms" header="Timp Mediu" :sortable="true" style="text-align: right;">
            <template #body="{ data }">
              {{ formatTime(data.avg_processing_time_ms) }}
            </template>
          </Column>
          <Column field="avg_confidence" header="Incredere Medie" :sortable="true" style="text-align: right;">
            <template #body="{ data }">
              {{ formatConfidence(data.avg_confidence) }}
            </template>
          </Column>
          <Column field="avg_fields_extracted" header="Campuri Medii" :sortable="true" style="text-align: right;">
            <template #body="{ data }">
              {{ data.avg_fields_extracted?.toFixed(1) || '-' }}
            </template>
          </Column>
        </DataTable>

        <!-- Mobile: Compact cards -->
        <div v-else class="mobile-card-list">
          <div
            v-for="engine in engineSummary"
            :key="engine.engine"
            class="mobile-data-card engine-mobile-card"
            :class="{ highlighted: getEngineBadge(engine.engine) }"
          >
            <div class="card-header">
              <span class="engine-badge" :class="getBaseEngine(engine.engine)">
                {{ formatEngineName(engine.engine) }}
              </span>
              <span
                v-if="getEngineBadge(engine.engine)"
                class="dynamic-badge"
                :class="getEngineBadge(engine.engine).class"
              >
                {{ getEngineBadge(engine.engine).text }}
              </span>
            </div>
            <div class="card-stats-grid">
              <div class="stat-item">
                <span class="stat-label">Joburi</span>
                <span class="stat-value">{{ engine.total_jobs }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">Succes</span>
                <span class="stat-value success">{{ formatPercent(engine.success_rate) }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">Timp</span>
                <span class="stat-value">{{ formatTime(engine.avg_processing_time_ms) }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">Incredere</span>
                <span class="stat-value">{{ formatConfidence(engine.avg_confidence) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Charts Section (hidden on mobile) -->
      <div v-if="!isMobile" class="charts-section">
        <!-- Processing Time Chart -->
        <div class="chart-card">
          <h3>Timp Procesare per Motor</h3>
          <div class="chart-container">
            <canvas ref="timeChartCanvas"></canvas>
          </div>
        </div>

        <!-- Success Rate Chart -->
        <div class="chart-card">
          <h3>Rata Succes per Motor</h3>
          <div class="chart-container">
            <canvas ref="successChartCanvas"></canvas>
          </div>
        </div>
      </div>

      <!-- Stats Summary -->
      <div v-if="stats" class="stats-overview">
        <h3>Statistici Generale</h3>
        <div class="stats-grid">
          <div class="stat-box">
            <i class="pi pi-file stat-icon stat-icon--primary"></i>
            <div class="stat-info">
              <span class="stat-number">{{ stats.total_jobs || 0 }}</span>
              <span class="stat-desc">Total joburi</span>
            </div>
          </div>
          <div class="stat-box">
            <i class="pi pi-check-circle stat-icon stat-icon--success"></i>
            <div class="stat-info">
              <span class="stat-number">{{ stats.successful_jobs || 0 }}</span>
              <span class="stat-desc">Procesate cu succes</span>
            </div>
          </div>
          <div class="stat-box">
            <i class="pi pi-times-circle stat-icon stat-icon--error"></i>
            <div class="stat-info">
              <span class="stat-number">{{ stats.failed_jobs || 0 }}</span>
              <span class="stat-desc">Esuate</span>
            </div>
          </div>
          <div class="stat-box">
            <i class="pi pi-clock stat-icon stat-icon--warning"></i>
            <div class="stat-info">
              <span class="stat-number">{{ formatTime(stats.avg_processing_time_ms) }}</span>
              <span class="stat-desc">Timp mediu total</span>
            </div>
          </div>
        </div>
      </div>

      <!-- History Section -->
      <div class="section-card">
        <div class="section-header">
          <h3 class="section-title">Istoric Joburi OCR</h3>
          <!-- Mobile: Filter toggle button -->
          <Button
            v-if="isMobile"
            icon="pi pi-filter"
            :class="{ 'filter-active': hasActiveFilters }"
            class="p-button-text"
            @click="showFilters = !showFilters"
            v-tooltip.bottom="'Filtre'"
          />
        </div>

        <!-- History Filters Toolbar -->
        <div v-if="!isMobile || showFilters" class="history-filters-toolbar">
          <div class="filters-row">
            <div class="filter-item">
              <label class="filter-label">Motor OCR</label>
              <Dropdown
                v-model="historyFilters.engine"
                :options="engineFilterOptions"
                optionLabel="label"
                optionValue="value"
                placeholder="Toate motoarele"
                class="filter-dropdown dropdown-borderless"
              />
            </div>
            <div class="filter-item">
              <label class="filter-label">Status</label>
              <Dropdown
                v-model="historyFilters.status"
                :options="statusFilterOptions"
                optionLabel="label"
                optionValue="value"
                placeholder="Toate"
                class="filter-dropdown dropdown-borderless"
              />
            </div>
            <div class="filter-actions">
              <Button
                icon="pi pi-filter-slash"
                :label="isMobile ? '' : 'Reseteaza'"
                class="p-button-outlined p-button-secondary"
                @click="clearFilters"
                :disabled="!hasActiveFilters"
                size="small"
              />
              <Button
                icon="pi pi-file-excel"
                :label="isMobile ? '' : 'Excel'"
                class="p-button-outlined p-button-success"
                @click="exportExcel"
                :disabled="filteredHistory.length === 0"
                size="small"
              />
              <Button
                icon="pi pi-file-pdf"
                :label="isMobile ? '' : 'PDF'"
                class="p-button-outlined p-button-danger"
                @click="exportPDF"
                :disabled="filteredHistory.length === 0"
                size="small"
              />
            </div>
          </div>
          <div v-if="hasActiveFilters" class="filter-info">
            <i class="pi pi-info-circle"></i>
            <span>{{ filteredHistory.length }} din {{ history.length }} inregistrari</span>
          </div>
        </div>

        <!-- Desktop: Enhanced DataTable -->
        <DataTable
          v-if="!isMobile"
          :value="filteredHistory"
          :paginator="true"
          :rows="20"
          :rowsPerPageOptions="[10, 20, 50]"
          responsiveLayout="scroll"
          stripedRows
          class="history-table"
          sortField="created_at"
          :sortOrder="-1"
        >
          <Column field="created_at" header="Data" :sortable="true">
            <template #body="{ data }">
              {{ formatDate(data.created_at) }}
            </template>
          </Column>
          <Column field="original_filename" header="Fisier" :sortable="true">
            <template #body="{ data }">
              <span class="filename-text" :title="data.original_filename">
                {{ data.original_filename || '-' }}
              </span>
            </template>
          </Column>
          <Column field="engine_requested" header="Motor Solicitat" :sortable="true">
            <template #body="{ data }">
              <span class="engine-badge" :class="getBaseEngine(data.engine_requested)">
                {{ formatEngineName(data.engine_requested) }}
              </span>
            </template>
          </Column>
          <Column field="engine_used" header="Motor Utilizat" :sortable="true">
            <template #body="{ data }">
              <span class="engine-badge" :class="getBaseEngine(data.engine_used)">
                {{ formatEngineName(data.engine_used) }}
              </span>
            </template>
          </Column>
          <Column field="processing_time_ms" header="Timp" :sortable="true" style="text-align: right;">
            <template #body="{ data }">
              {{ formatTime(data.processing_time_ms) }}
            </template>
          </Column>
          <Column field="success" header="Status" :sortable="true">
            <template #body="{ data }">
              <Tag :severity="data.success ? 'success' : 'danger'">
                {{ data.success ? 'Succes' : 'Eroare' }}
              </Tag>
            </template>
          </Column>
          <Column field="overall_confidence" header="Incredere" :sortable="true" style="text-align: right;">
            <template #body="{ data }">
              <span v-if="data.success">{{ formatConfidence(data.overall_confidence) }}</span>
              <span v-else class="error-text">-</span>
            </template>
          </Column>
          <Column field="fields_extracted" header="Campuri" :sortable="true" style="text-align: right;">
            <template #body="{ data }">
              <span v-if="data.success">{{ data.fields_extracted || 0 }}</span>
              <span v-else class="error-text">-</span>
            </template>
          </Column>
        </DataTable>

        <!-- Mobile: Compact cards -->
        <div v-else class="mobile-card-list">
          <div
            v-for="job in filteredHistory"
            :key="job.job_id"
            class="mobile-data-card history-mobile-card"
          >
            <div class="card-header">
              <span class="engine-badge" :class="getBaseEngine(job.engine_used)">
                {{ formatEngineName(job.engine_used) }}
              </span>
              <Tag :severity="job.success ? 'success' : 'danger'" class="status-tag">
                {{ job.success ? 'Succes' : 'Eroare' }}
              </Tag>
            </div>
            <div v-if="job.original_filename" class="card-row filename-row">
              <span class="filename-text">{{ job.original_filename }}</span>
            </div>
            <div class="card-row">
              <span class="card-meta">{{ formatDate(job.created_at) }}</span>
              <span class="card-value">{{ formatTime(job.processing_time_ms) }}</span>
            </div>
            <div v-if="job.success" class="card-row">
              <span class="card-meta">Incredere: {{ formatConfidence(job.overall_confidence) }}</span>
              <span class="card-value">{{ job.fields_extracted || 0 }} campuri</span>
            </div>
          </div>
          <div v-if="filteredHistory.length === 0" class="mobile-empty">
            <i class="pi pi-info-circle"></i>
            <p>Nu exista inregistrari</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, onUnmounted, watch, nextTick } from 'vue'
import Dropdown from 'primevue/dropdown'
import Button from 'primevue/button'
import ProgressSpinner from 'primevue/progressspinner'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Tag from 'primevue/tag'
import Card from 'primevue/card'
import { useToast } from 'primevue/usetoast'
import {
  Chart,
  CategoryScale,
  LinearScale,
  BarElement,
  BarController,
  Title,
  Tooltip,
  Legend,
} from 'chart.js'
import { useOCRSettingsStore } from '@data-entry/stores/ocrSettingsStore'
import { exportToExcel, exportToPDF } from '@reports/utils/exportUtils'

// Register Chart.js components
Chart.register(
  CategoryScale,
  LinearScale,
  BarElement,
  BarController,
  Title,
  Tooltip,
  Legend,
)

const ocrStore = useOCRSettingsStore()
const toast = useToast()

// State
const selectedDays = ref(30)
const daysOptions = [
  { label: 'Ultimele 7 zile', value: 7 },
  { label: 'Ultimele 30 zile', value: 30 },
  { label: 'Ultimele 90 zile', value: 90 },
]

// Mobile detection
const isMobile = ref(window.innerWidth < 768)
const showFilters = ref(false)

// History filters
const historyFilters = ref({
  engine: null,
  status: null
})

// Chart refs
const timeChartCanvas = ref(null)
const successChartCanvas = ref(null)
let timeChartInstance = null
let successChartInstance = null

// Computed
const loading = computed(() => ocrStore.metricsLoading)
const engineSummary = computed(() => ocrStore.metrics.summary || [])
const stats = computed(() => ocrStore.metrics.stats)
const history = computed(() => ocrStore.metrics.history || [])
const hasData = computed(() => engineSummary.value.length > 0 || history.value.length > 0)

// Filter options
const engineFilterOptions = computed(() => {
  const engines = new Set(history.value.map(h => h.engine_used))
  return [
    { label: 'Toate motoarele', value: null },
    ...Array.from(engines).map(e => ({ label: formatEngineName(e), value: e }))
  ]
})

const statusFilterOptions = computed(() => [
  { label: 'Toate', value: null },
  { label: 'Succes', value: true },
  { label: 'Eroare', value: false }
])

// Filtered history
const filteredHistory = computed(() => {
  let result = [...history.value]

  if (historyFilters.value.engine) {
    result = result.filter(h => h.engine_used === historyFilters.value.engine)
  }
  if (historyFilters.value.status !== null) {
    result = result.filter(h => h.success === historyFilters.value.status)
  }

  return result
})

// Check if any filter is active
const hasActiveFilters = computed(() => {
  return historyFilters.value.engine !== null || historyFilters.value.status !== null
})

// Dynamic badge computation - find fastest and best quality engines
const fastestEngine = computed(() => {
  if (!engineSummary.value.length) return null
  const successful = engineSummary.value.filter(e => e.successful_jobs > 0)
  if (!successful.length) return null
  return successful.reduce((min, e) =>
    (e.avg_processing_time_ms || Infinity) < (min.avg_processing_time_ms || Infinity) ? e : min
  ).engine
})

const bestQualityEngine = computed(() => {
  if (!engineSummary.value.length) return null
  const successful = engineSummary.value.filter(e => e.successful_jobs > 0)
  if (!successful.length) return null
  return successful.reduce((max, e) =>
    (e.avg_confidence || 0) > (max.avg_confidence || 0) ? e : max
  ).engine
})

// Get badge info for an engine
const getEngineBadge = (engine) => {
  const baseEngine = getBaseEngine(engine)
  if (baseEngine === fastestEngine.value && baseEngine === bestQualityEngine.value) {
    return { text: 'Cel mai bun', class: 'best' }
  }
  if (baseEngine === fastestEngine.value) {
    return { text: 'Cel mai rapid', class: 'fastest' }
  }
  if (baseEngine === bestQualityEngine.value) {
    return { text: 'Cea mai buna calitate', class: 'quality' }
  }
  return null
}

// Format helpers
const engineNameMap = {
  auto: 'Auto',
  doctr: 'docTR',
  paddleocr: 'PaddleOCR',
  tesseract: 'Tesseract',
  // Hybrid methods
  'hybrid': 'Hybrid',
  'hybrid-quality': 'Hybrid Calitate',
}

const getBaseEngine = (engine) => {
  if (!engine) return 'auto'
  if (engineNameMap[engine]) return engine
  // Find base engine for sub-variants like "doctr-light", "doctr-adaptive"
  const baseKey = Object.keys(engineNameMap).find(k => engine.startsWith(k))
  return baseKey || engine
}

const formatEngineName = (engine) => {
  const base = getBaseEngine(engine)
  return engineNameMap[base] || engine
}

const formatPercent = (value) => {
  if (value === null || value === undefined) return '-'
  return `${(value * 100).toFixed(1)}%`
}

const formatTime = (ms) => {
  if (ms === null || ms === undefined) return '-'
  if (ms < 1000) return `${Math.round(ms)}ms`
  return `${(ms / 1000).toFixed(2)}s`
}

const formatConfidence = (value) => {
  if (value === null || value === undefined) return '-'
  return `${(value * 100).toFixed(0)}%`
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('ro-RO', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// Chart colors per engine
const engineColors = {
  doctr: '#667eea',
  paddleocr: '#22c55e',
  tesseract: '#f59e0b',
  auto: '#6b7280',
  'hybrid': '#06b6d4',
  'hybrid-quality': '#8b5cf6',
}

// Initialize charts
const initCharts = async () => {
  if (isMobile.value) return // Don't init charts on mobile

  await nextTick()

  // Destroy existing charts
  if (timeChartInstance) {
    timeChartInstance.destroy()
    timeChartInstance = null
  }
  if (successChartInstance) {
    successChartInstance.destroy()
    successChartInstance = null
  }

  if (!engineSummary.value.length) return

  // Prepare data
  const engines = engineSummary.value.map(e => formatEngineName(e.engine))
  const times = engineSummary.value.map(e => (e.avg_processing_time_ms || 0) / 1000)
  const successRates = engineSummary.value.map(e => (e.success_rate || 0) * 100)
  const getEngineColor = (engine) => {
    if (engineColors[engine]) return engineColors[engine]
    const baseKey = Object.keys(engineColors).find(k => engine.startsWith(k))
    return baseKey ? engineColors[baseKey] : '#6b7280'
  }
  const colors = engineSummary.value.map(e => getEngineColor(e.engine))

  // Processing Time Chart
  if (timeChartCanvas.value) {
    const timeCtx = timeChartCanvas.value.getContext('2d')
    timeChartInstance = new Chart(timeCtx, {
      type: 'bar',
      data: {
        labels: engines,
        datasets: [{
          label: 'Timp mediu (secunde)',
          data: times,
          backgroundColor: colors,
          borderRadius: 6,
          barThickness: 50,
        }],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false },
          tooltip: {
            callbacks: {
              label: (context) => `${context.parsed.y.toFixed(2)}s`,
            },
          },
        },
        scales: {
          x: {
            grid: { display: false },
            ticks: { color: '#6b7280' },
          },
          y: {
            beginAtZero: true,
            grid: { color: 'rgba(0,0,0,0.05)' },
            ticks: {
              color: '#6b7280',
              callback: (value) => `${value}s`,
            },
          },
        },
      },
    })
  }

  // Success Rate Chart
  if (successChartCanvas.value) {
    const successCtx = successChartCanvas.value.getContext('2d')
    successChartInstance = new Chart(successCtx, {
      type: 'bar',
      data: {
        labels: engines,
        datasets: [{
          label: 'Rata succes (%)',
          data: successRates,
          backgroundColor: colors,
          borderRadius: 6,
          barThickness: 50,
        }],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false },
          tooltip: {
            callbacks: {
              label: (context) => `${context.parsed.y.toFixed(1)}%`,
            },
          },
        },
        scales: {
          x: {
            grid: { display: false },
            ticks: { color: '#6b7280' },
          },
          y: {
            beginAtZero: true,
            max: 100,
            grid: { color: 'rgba(0,0,0,0.05)' },
            ticks: {
              color: '#6b7280',
              callback: (value) => `${value}%`,
            },
          },
        },
      },
    })
  }
}

// Load all metrics
const loadAllMetrics = async () => {
  await ocrStore.loadAllMetrics(selectedDays.value)
  await initCharts()
}

// Clear filters
const clearFilters = () => {
  historyFilters.value = {
    engine: null,
    status: null
  }
}

// Handle resize
const handleResize = () => {
  isMobile.value = window.innerWidth < 768
  if (!isMobile.value) {
    showFilters.value = false
    // Reinit charts when switching to desktop
    initCharts()
  }
}

// Export Excel
const exportExcel = () => {
  const exportData = filteredHistory.value.map(job => ({
    'Data': formatDate(job.created_at),
    'Fisier': job.original_filename || '-',
    'Motor Solicitat': formatEngineName(job.engine_requested),
    'Motor Utilizat': formatEngineName(job.engine_used),
    'Timp (ms)': job.processing_time_ms,
    'Status': job.success ? 'Succes' : 'Eroare',
    'Incredere': job.success ? formatConfidence(job.overall_confidence) : '-',
    'Campuri Extrase': job.success ? (job.fields_extracted || 0) : '-'
  }))

  const result = exportToExcel(
    exportData,
    'metrici_ocr',
    'Istoric OCR'
  )

  if (result?.success !== false) {
    toast?.add?.({
      severity: 'success',
      summary: 'Export reusit',
      detail: `${exportData.length} inregistrari exportate`,
      life: 3000
    })
  }
}

// Export PDF
const exportPDF = () => {
  const columns = [
    { field: 'data', header: 'Data', type: 'text' },
    { field: 'fisier', header: 'Fisier', type: 'text' },
    { field: 'motor_utilizat', header: 'Motor', type: 'text' },
    { field: 'timp', header: 'Timp', type: 'text' },
    { field: 'status', header: 'Status', type: 'text' },
    { field: 'incredere', header: 'Incredere', type: 'text' },
    { field: 'campuri', header: 'Campuri', type: 'number' }
  ]

  const exportData = filteredHistory.value.map(job => ({
    data: formatDate(job.created_at),
    fisier: job.original_filename || '-',
    motor_utilizat: formatEngineName(job.engine_used),
    timp: formatTime(job.processing_time_ms),
    status: job.success ? 'Succes' : 'Eroare',
    incredere: job.success ? formatConfidence(job.overall_confidence) : '-',
    campuri: job.success ? (job.fields_extracted || 0) : 0
  }))

  const result = exportToPDF(
    exportData,
    columns,
    'metrici-ocr',
    {
      title: 'Metrici OCR',
      period: `Ultimele ${selectedDays.value} zile`
    }
  )

  if (result?.success !== false) {
    toast?.add?.({
      severity: 'success',
      summary: 'Export reusit',
      detail: `${exportData.length} inregistrari exportate`,
      life: 3000
    })
  }
}

// Watch for days change
watch(selectedDays, async () => {
  await loadAllMetrics()
})

// Lifecycle
onMounted(async () => {
  window.addEventListener('resize', handleResize)
  await loadAllMetrics()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (timeChartInstance) {
    timeChartInstance.destroy()
    timeChartInstance = null
  }
  if (successChartInstance) {
    successChartInstance.destroy()
    successChartInstance = null
  }
})
</script>

<style scoped>
.ocr-metrics-view {
  padding: 1.5rem;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.page-header h1 {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-color);
  margin: 0;
}

.days-selector {
  min-width: 160px;
}

.filter-active {
  background: var(--primary-100, #e0e7ff) !important;
  color: var(--primary-700, #4338ca) !important;
}

/* Section Header with actions */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  flex-wrap: wrap;
  gap: 0.75rem;
}

.section-header .section-title {
  margin: 0;
}

.section-actions {
  display: flex;
  gap: 0.75rem;
  align-items: center;
}

.section-actions .days-selector {
  min-width: 150px;
}

/* History Filters Toolbar */
.history-filters-toolbar {
  background: var(--surface-ground, #f8fafc);
  border: 1px solid var(--surface-border, #e2e8f0);
  border-radius: 8px;
  padding: 0.75rem 1rem;
  margin-bottom: 1rem;
}

.filters-row {
  display: flex;
  align-items: flex-end;
  gap: 1rem;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 150px;
}

.filter-label {
  font-size: 0.75rem;
  font-weight: 500;
  color: var(--text-color-secondary, #64748b);
  text-transform: uppercase;
  letter-spacing: 0.025em;
}

.filter-dropdown {
  min-width: 160px;
}

.filter-actions {
  display: flex;
  gap: 0.5rem;
  margin-left: auto;
}

.filter-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.75rem;
  padding-top: 0.75rem;
  border-top: 1px solid var(--surface-border, #e2e8f0);
  font-size: 0.8125rem;
  color: var(--text-color-secondary, #64748b);
}

.filter-info i {
  color: var(--primary-500, #6366f1);
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: stretch;
  }

  .section-actions {
    justify-content: space-between;
  }

  .section-actions .days-selector {
    flex: 1;
    min-width: 0;
  }

  .filters-row {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item {
    min-width: 100%;
  }

  .filter-actions {
    margin-left: 0;
    justify-content: flex-end;
    margin-top: 0.5rem;
    padding-top: 0.5rem;
    border-top: 1px solid var(--surface-border, #e2e8f0);
  }
}

/* Loading and Empty States */
.loading-container,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 2rem;
  text-align: center;
  color: #64748b;
}

.empty-state h3 {
  margin: 1rem 0 0.5rem;
  color: #1e293b;
}

/* Section Card */
.section-card {
  background: var(--surface-card);
  border-radius: 12px;
  padding: 1.25rem;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--surface-border);
  margin-bottom: 1.5rem;
}

.section-title {
  font-size: 1rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 1rem 0;
}

/* Engine cell in table */
.engine-cell {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.success-value {
  color: #22c55e;
  font-weight: 500;
}

/* Mobile Card List */
.mobile-card-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.mobile-data-card {
  background: var(--surface-card, #ffffff);
  border: 1px solid var(--surface-border, #e2e8f0);
  border-radius: 8px;
  padding: 0.75rem 1rem;
}

.mobile-data-card.highlighted {
  border-color: var(--primary-400, #818cf8);
  background: linear-gradient(to bottom right, #f8fafc, #eef2ff);
}

.mobile-data-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.mobile-data-card .card-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.875rem;
  color: var(--text-color-secondary, #64748b);
  margin-top: 0.25rem;
}

.mobile-data-card .card-meta {
  color: var(--text-color-secondary, #64748b);
}

.mobile-data-card .card-value {
  font-weight: 500;
  color: var(--text-color, #1e293b);
}

.card-stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.card-stats-grid .stat-item {
  display: flex;
  flex-direction: column;
  gap: 0.125rem;
}

.card-stats-grid .stat-label {
  font-size: 0.75rem;
  color: var(--text-color-secondary, #64748b);
}

.card-stats-grid .stat-value {
  font-size: 0.9375rem;
  font-weight: 600;
  color: var(--text-color, #1e293b);
}

.card-stats-grid .stat-value.success {
  color: var(--green-600, #16a34a);
}

.history-mobile-card .status-tag {
  font-size: 0.75rem;
}

/* Filename styles */
.filename-text {
  max-width: 250px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  color: var(--text-color, #1e293b);
}

.filename-row {
  justify-content: flex-start !important;
}

.filename-row .filename-text {
  font-size: 0.8125rem;
  font-weight: 500;
  color: var(--primary-700, #4338ca);
  max-width: 100%;
}

.mobile-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem;
  color: var(--text-color-secondary, #64748b);
  text-align: center;
}

.mobile-empty i {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

/* Charts Section */
.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.chart-card {
  background: var(--surface-card);
  border-radius: 12px;
  padding: 1.25rem;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--surface-border);
}

.chart-card h3 {
  font-size: 1rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 1rem 0;
}

.chart-container {
  height: 250px;
  position: relative;
}

/* Stats Overview */
.stats-overview {
  background: var(--surface-card);
  border-radius: 12px;
  padding: 1.25rem;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--surface-border);
  margin-bottom: 1.5rem;
}

.stats-overview h3 {
  font-size: 1rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 1rem 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.stat-box {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  background: var(--surface-ground);
  border-radius: 8px;
}

.stat-box i {
  font-size: 1.5rem;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-number {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--text-color);
}

.stat-desc {
  font-size: 0.8rem;
  color: var(--text-color-secondary);
}

/* Engine Badges */
.engine-badge {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
}

.engine-badge.doctr {
  background: #eef2ff;
  color: #667eea;
}

.engine-badge.paddleocr {
  background: #dcfce7;
  color: #16a34a;
}

.engine-badge.tesseract {
  background: #fef3c7;
  color: #d97706;
}

.engine-badge.auto {
  background: #f1f5f9;
  color: #475569;
}

.engine-badge.hybrid {
  background: #ecfeff;
  color: #0891b2;
}

.engine-badge.hybrid-quality {
  background: #f5f3ff;
  color: #7c3aed;
}

/* Dynamic badges for fastest/best quality */
.dynamic-badge {
  font-size: 0.65rem;
  padding: 0.2rem 0.4rem;
  border-radius: 4px;
  font-weight: 500;
  white-space: nowrap;
}

.dynamic-badge.fastest {
  background: #fef3c7;
  color: #d97706;
}

.dynamic-badge.quality {
  background: #dcfce7;
  color: #16a34a;
}

.dynamic-badge.best {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.error-text {
  color: #94a3b8;
}

/* Responsive */
@media (max-width: 768px) {
  .ocr-metrics-view {
    padding: 1rem;
  }

  .page-header h1 {
    font-size: 1.25rem;
  }

  .charts-section {
    display: none;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 0.5rem;
  }

  .stat-box {
    padding: 0.5rem;
  }

  .stat-box i {
    font-size: 1.25rem;
  }

  .stat-number {
    font-size: 1rem;
  }

  .filters-actions {
    flex-direction: column;
  }

  .form-col {
    min-width: 100%;
  }
}

/* Dark mode compatible icon styles */
.empty-state-icon {
  font-size: 3rem;
  color: var(--text-color-secondary);
}

.stat-icon {
  font-size: 1.5rem;
}

.stat-icon--primary {
  color: var(--primary-500, #667eea);
}

.stat-icon--success {
  color: var(--green-500, #22c55e);
}

.stat-icon--error {
  color: var(--red-500, #ef4444);
}

.stat-icon--warning {
  color: var(--yellow-500, #f59e0b);
}
</style>

<!-- Non-scoped styles for PrimeVue overrides -->
<style>
/* Borderless dropdown - matches receipt form styling */
.dropdown-borderless.p-dropdown {
  border: none !important;
  background: transparent !important;
  box-shadow: none !important;
  min-height: 38px;
}

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

.dropdown-borderless .p-dropdown-label {
  padding: 0.5rem 0.75rem !important;
  line-height: 1.4 !important;
}

.dropdown-borderless .p-dropdown-trigger {
  background: transparent !important;
  width: 2rem !important;
}
</style>
