<template>
  <div
    class="solduri-compact-card"
    :class="[`solduri-compact-card--${type}`, { 'solduri-compact-card--expanded': isExpanded }]"
    @click="toggleExpanded"
  >
    <!-- Header: Label + Value -->
    <div class="solduri-compact-card__header">
      <div class="solduri-compact-card__content">
        <span class="solduri-compact-card__label">{{ label }}</span>
        <!-- type !== 'tva': simple value -->
        <span v-if="type !== 'tva'" class="solduri-compact-card__value" :class="valueColorClass">
          {{ formatAmount(total) }}
        </span>
        <!-- type === 'tva': datorat · sold on same line, same font -->
        <div v-else class="solduri-compact-card__debt-line">
          <span class="solduri-compact-card__value" :class="valueColorClass">{{ formatAmount(total) }}</span>
          <span class="solduri-compact-card__debt-sep">·</span>
          <span class="solduri-compact-card__value solduri-compact-card__value--sold">
            {{ soldTotal !== undefined && soldTotal > 0 ? formatAmount(soldTotal) : '0 ✓' }}
          </span>
        </div>
      </div>
      <i
        class="pi pi-chevron-down solduri-compact-card__chevron"
        :class="{ 'solduri-compact-card__chevron--expanded': isExpanded }"
      ></i>
    </div>

    <!-- Expandable Breakdown Section -->
    <div v-if="isExpanded && hasBreakdown" class="solduri-compact-card__breakdown">
      <!-- CashFlow: Încasări + Plăți -->
      <template v-if="type === 'cashflow'">
        <div class="solduri-compact-card__breakdown-item">
          <span class="solduri-compact-card__breakdown-label">Încasări</span>
          <span class="solduri-compact-card__breakdown-value solduri-compact-card__breakdown-value--success">
            {{ formatAmount((breakdown as CashFlowBreakdown)?.incasari || 0) }}
          </span>
        </div>
        <div class="solduri-compact-card__breakdown-item">
          <span class="solduri-compact-card__breakdown-label">Plăți</span>
          <span class="solduri-compact-card__breakdown-value solduri-compact-card__breakdown-value--danger">
            {{ formatAmount((breakdown as CashFlowBreakdown)?.plati || 0) }}
          </span>
        </div>
      </template>

      <!-- Trezorerie: Casa + Bancă -->
      <template v-else-if="type === 'trezorerie'">
        <!-- Casa Total -->
        <div class="solduri-compact-card__breakdown-item">
          <span class="solduri-compact-card__breakdown-label">Casa</span>
          <span class="solduri-compact-card__breakdown-value">{{ formatAmount(casaTotal) }}</span>
        </div>
        <!-- Sub-conturi Casa (level 2 only) -->
        <template v-if="showSubDetails && breakdown?.casa?.items?.length">
          <div
            v-for="(item, idx) in breakdown.casa.items"
            :key="`casa-${idx}`"
            class="solduri-compact-card__breakdown-subitem"
          >
            <span class="solduri-compact-card__breakdown-sublabel">
              {{ item.nume || `Cont ${item.cont}` }}
            </span>
            <span class="solduri-compact-card__breakdown-subvalue">{{ formatAmount(item.sold) }}</span>
          </div>
        </template>
        <!-- Bancă Total -->
        <div class="solduri-compact-card__breakdown-item">
          <span class="solduri-compact-card__breakdown-label">Bancă</span>
          <span class="solduri-compact-card__breakdown-value">{{ formatAmount(bancaTotal) }}</span>
        </div>
        <!-- Sub-conturi Bancă (level 2 only) -->
        <template v-if="showSubDetails && breakdown?.banca?.items?.length">
          <div
            v-for="(item, idx) in breakdown.banca.items"
            :key="`banca-${idx}`"
            class="solduri-compact-card__breakdown-subitem"
          >
            <span class="solduri-compact-card__breakdown-sublabel">
              {{ item.nume || `Cont ${item.cont}` }}
            </span>
            <span class="solduri-compact-card__breakdown-subvalue">{{ formatAmount(item.sold) }}</span>
          </div>
        </template>
      </template>

      <!-- Clienți/Furnizori: Buckets (În termen, Restant) -->
      <template v-else-if="type === 'clienti' || type === 'furnizori'">
        <div class="solduri-compact-card__breakdown-item">
          <span class="solduri-compact-card__breakdown-label">În termen</span>
          <span class="solduri-compact-card__breakdown-value">
            {{ formatAmount(breakdown?.in_termen?.total || 0) }}
          </span>
        </div>
        <div class="solduri-compact-card__breakdown-item">
          <span class="solduri-compact-card__breakdown-label">Restant</span>
          <span class="solduri-compact-card__breakdown-value solduri-compact-card__breakdown-value--warning">
            {{ formatAmount(breakdown?.restant?.total || 0) }}
          </span>
        </div>
        <!-- Perioade restante (level 2 only) -->
        <template v-if="showSubDetails && breakdown?.restant?.perioade">
          <div
            v-for="(value, key) in breakdown.restant.perioade"
            :key="key"
            class="solduri-compact-card__breakdown-subitem"
          >
            <span class="solduri-compact-card__breakdown-sublabel">{{ formatPeriodLabel(key) }}</span>
            <span class="solduri-compact-card__breakdown-subvalue">{{ formatAmount(value) }}</span>
          </div>
        </template>
      </template>

      <!-- TVA / Datorii Buget: Breakdown pe grupe (TVA/BASS/CAM) cu sub-conturi -->
      <template v-else-if="type === 'tva'">
        <template v-if="Array.isArray(breakdown) && (breakdown as any[]).length">
          <!-- Header coloane -->
          <div class="solduri-compact-card__debt-header">
            <span></span>
            <span class="solduri-compact-card__col-head">Datorat</span>
            <span class="solduri-compact-card__col-head">Sold</span>
          </div>

          <div v-for="group in (breakdown as any[])" :key="group.key">
            <!-- Rând grup -->
            <div
              class="solduri-compact-card__breakdown-group"
              @click.stop="toggleGroup(group.key)"
            >
              <span class="solduri-compact-card__breakdown-label solduri-compact-card__group-label">
                <i class="pi pi-chevron-right solduri-compact-card__group-toggle"
                   :class="{ 'solduri-compact-card__group-toggle--expanded': expandedGroups.has(group.key) }"></i>
                {{ group.label }}
              </span>
              <span class="solduri-compact-card__breakdown-value">
                {{ group.datorat > 0 ? formatAmount(group.datorat) : '-' }}
              </span>
              <span class="solduri-compact-card__breakdown-value"
                    :class="group.sold <= 0 && group.datorat > 0 ? 'solduri-compact-card__cleared' : ''">
                {{ group.sold > 0 ? formatAmount(group.sold) : (group.datorat > 0 ? '✓' : '-') }}
              </span>
            </div>
            <!-- Sub-conturi expandabile -->
            <div v-show="expandedGroups.has(group.key)">
              <div
                v-for="acc in group.sub_accounts"
                :key="acc.cont"
                class="solduri-compact-card__breakdown-subitem"
              >
                <span class="solduri-compact-card__breakdown-sublabel">{{ acc.label }}</span>
                <span class="solduri-compact-card__breakdown-subvalue">
                  {{ acc.datorat > 0 ? formatAmount(acc.datorat) : '-' }}
                </span>
                <span class="solduri-compact-card__breakdown-subvalue">
                  {{ acc.sold > 0 ? formatAmount(acc.sold) : (acc.datorat > 0 ? '✓' : '-') }}
                </span>
              </div>
            </div>
          </div>

          <!-- Obligații luna curentă -->
          <template v-if="(breakdown as any[]).some((g: any) => g.curent > 0)">
            <div class="solduri-compact-card__divider"></div>
            <div class="solduri-compact-card__curent-summary">
              <span class="solduri-compact-card__curent-title">Obligații curente:</span>
              <span
                v-for="g in (breakdown as any[]).filter((g: any) => g.curent > 0)"
                :key="'c-' + g.key"
                class="solduri-compact-card__curent-chip"
              >
                {{ g.label }} {{ formatAmount(g.curent) }}
              </span>
              <span class="solduri-compact-card__curent-total">
                = {{ formatAmount(curentTotal) }}
              </span>
            </div>
          </template>
        </template>
        <template v-else>
          <div class="solduri-compact-card__breakdown-item">
            <span class="solduri-compact-card__breakdown-label">Fără date</span>
            <span class="solduri-compact-card__breakdown-value">-</span>
          </div>
        </template>
      </template>
    </div>

    <!-- Chart toggle - only shown when card is expanded and chartConfig is provided -->
    <div
      v-if="isExpanded && chartConfig"
      class="solduri-compact-card__charts-toggle"
      @click.stop="toggleChartExpanded"
    >
      <span class="solduri-compact-card__charts-toggle-label">Grafice evoluție</span>
      <i
        class="pi pi-chevron-right solduri-compact-card__charts-chevron"
        :class="{ 'solduri-compact-card__charts-chevron--expanded': isChartExpanded }"
      ></i>
    </div>

    <!-- Chart content - lazy rendered with v-if to avoid zero-dimension canvas -->
    <div v-if="isExpanded && isChartExpanded && chartConfig" class="solduri-compact-card__charts-content">
      <!-- Dual charts (Trezorerie: Casa + Banca) -->
      <template v-if="chartConfig.dual">
        <div class="solduri-compact-card__chart-wrapper">
          <div class="solduri-compact-card__chart-label" :style="{ color: chartConfig.dual.primaryColor }">
            {{ chartConfig.dual.primaryLabel }}
          </div>
          <div class="solduri-compact-card__chart-container">
            <canvas ref="chartCanvas1"></canvas>
          </div>
        </div>
        <div class="solduri-compact-card__chart-wrapper">
          <div class="solduri-compact-card__chart-label" :style="{ color: chartConfig.dual.secondaryColor }">
            {{ chartConfig.dual.secondaryLabel }}
          </div>
          <div class="solduri-compact-card__chart-container">
            <canvas ref="chartCanvas2"></canvas>
          </div>
        </div>
      </template>
      <!-- Single chart (Clienti/Furnizori) -->
      <template v-else-if="chartConfig.single">
        <div class="solduri-compact-card__chart-wrapper">
          <div class="solduri-compact-card__chart-container">
            <canvas ref="chartCanvas1"></canvas>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onBeforeUnmount, nextTick } from 'vue'
import { Chart, registerables } from 'chart.js'

Chart.register(...registerables)

// Type definitions
type CardType = 'trezorerie' | 'clienti' | 'furnizori' | 'tva' | 'cashflow'

interface TrezorerieBreakdown {
  casa?: {
    total?: number
    items?: Array<{ nume?: string; cont?: string; sold: number }>
  }
  banca?: {
    total?: number
    items?: Array<{ nume?: string; cont?: string; sold: number }>
  }
}

interface ClientiFurnizoriBreakdown {
  total?: number
  in_termen?: { total?: number }
  restant?: {
    total?: number
    perioade?: Record<string, number>
  }
}

interface CashFlowBreakdown {
  incasari: number
  plati: number
}

type BreakdownType = TrezorerieBreakdown | ClientiFurnizoriBreakdown | CashFlowBreakdown | null

interface ChartConfig {
  dual?: {
    primaryData: number[]
    primaryPreviousData?: number[]
    primaryLabel: string
    primaryColor: string
    secondaryData: number[]
    secondaryPreviousData?: number[]
    secondaryLabel: string
    secondaryColor: string
  }
  single?: {
    data: number[]
    previousData?: number[]
    label: string
    color: string
  }
  labels: string[]
  previousLabels?: string[]
}

// Props
const props = defineProps<{
  type: CardType
  total: number
  soldTotal?: number
  breakdown?: BreakdownType
  casaTotal?: number
  bancaTotal?: number
  chartConfig?: ChartConfig
}>()

// State - 3-level expansion cycle: 0 (collapsed) → 1 (totals) → 2 (sub-details) → 0
const expansionLevel = ref(0)
const isExpanded = computed(() => expansionLevel.value > 0)
const showSubDetails = computed(() => expansionLevel.value >= 2)
const expandedGroups = ref(new Set<string>())
const toggleGroup = (key: string) => {
  if (expandedGroups.value.has(key)) {
    expandedGroups.value.delete(key)
  } else {
    expandedGroups.value.add(key)
  }
  expandedGroups.value = new Set(expandedGroups.value)
}

// Chart state
const isChartExpanded = ref(false)
const chartCanvas1 = ref<HTMLCanvasElement | null>(null)
const chartCanvas2 = ref<HTMLCanvasElement | null>(null)
let chartInstance1: Chart | null = null
let chartInstance2: Chart | null = null

const toggleChartExpanded = () => {
  isChartExpanded.value = !isChartExpanded.value
}

// Helper: hex to rgba
const hexToRgba = (hex: string, alpha: number): string => {
  const r = parseInt(hex.slice(1, 3), 16)
  const g = parseInt(hex.slice(3, 5), 16)
  const b = parseInt(hex.slice(5, 7), 16)
  return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

// Create a sparkline chart on a canvas element
const createSparklineChart = (
  canvas: HTMLCanvasElement,
  data: number[],
  previousData: number[] | undefined,
  color: string,
  label: string
): Chart | null => {
  if (!canvas || !data || data.length === 0) return null
  const ctx = canvas.getContext('2d')
  if (!ctx) return null

  const labels = props.chartConfig?.labels || data.map((_, i) => `L${i + 1}`)

  const datasets: any[] = [{
    label: `${label} (curent)`,
    data: data,
    borderColor: color,
    backgroundColor: hexToRgba(color, 0.1),
    borderWidth: 2,
    fill: true,
    tension: 0.4,
    pointRadius: 0,
    pointHoverRadius: 4,
    pointHoverBackgroundColor: color,
    pointHoverBorderColor: '#ffffff',
    pointHoverBorderWidth: 2,
  }]

  if (previousData && previousData.length > 0) {
    datasets.push({
      label: `${label} (an precedent)`,
      data: previousData,
      borderColor: hexToRgba(color, 0.4),
      backgroundColor: hexToRgba(color, 0.05),
      borderWidth: 2,
      borderDash: [5, 5],
      fill: false,
      tension: 0.4,
      pointRadius: 0,
      pointHoverRadius: 4,
      pointHoverBackgroundColor: hexToRgba(color, 0.6),
      pointHoverBorderColor: '#ffffff',
      pointHoverBorderWidth: 2,
    })
  }

  // Y-axis: symmetric range with padding (from ClientiBalanceCard pattern)
  const allDataPoints = [...data]
  if (previousData && previousData.length > 0) allDataPoints.push(...previousData)
  const dataMin = Math.min(...allDataPoints)
  const dataMax = Math.max(...allDataPoints)
  const dataRange = dataMax - dataMin
  const dataMean = allDataPoints.reduce((sum, val) => sum + val, 0) / allDataPoints.length
  const minVisibleRange = dataMean * 0.25
  const center = (dataMin + dataMax) / 2
  const targetRange = Math.max(dataRange, minVisibleRange)
  const calculatedMin = center - targetRange / 2
  const calculatedMax = center + targetRange / 2
  const paddingAmount = targetRange * 0.1
  const allPositive = dataMin >= 0
  const yMin = allPositive ? Math.max(0, calculatedMin - paddingAmount) : calculatedMin - paddingAmount
  const yMax = calculatedMax + paddingAmount

  return new Chart(ctx, {
    type: 'line',
    data: { labels, datasets },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: { intersect: false, mode: 'index' },
      plugins: {
        legend: {
          display: datasets.length > 1,
          position: 'top',
          align: 'end',
          labels: {
            boxWidth: 12, boxHeight: 12, padding: 8,
            font: { size: 10, family: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif' },
            color: 'rgba(107, 114, 128, 0.9)',
            usePointStyle: true, pointStyle: 'line',
          },
        },
        tooltip: {
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          titleColor: '#ffffff',
          bodyColor: '#ffffff',
          borderColor: 'rgba(255, 255, 255, 0.2)',
          borderWidth: 1,
          cornerRadius: 6,
          displayColors: true,
          callbacks: {
            title: (context: any) => context[0].label || '',
            label: (context: any) => {
              const value = context.parsed.y
              const lbl = context.dataset.label || ''
              const formatted = new Intl.NumberFormat('ro-RO', {
                style: 'decimal',
                minimumFractionDigits: 0,
                maximumFractionDigits: 0,
              }).format(value)
              return `${lbl}: ${formatted}`
            },
          },
        },
      },
      scales: {
        x: {
          display: true,
          grid: { display: false, drawBorder: false },
          ticks: {
            color: 'rgba(107, 114, 128, 0.7)',
            font: { size: 10, family: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif' },
            maxRotation: 45,
            minRotation: 45,
            maxTicksLimit: 6,
          },
          border: { display: false },
        },
        y: {
          display: true,
          min: yMin,
          max: yMax,
          grid: { color: 'rgba(107, 114, 128, 0.1)', drawBorder: false },
          ticks: {
            color: color,
            font: { size: 11, family: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif' },
            maxTicksLimit: 3,
            callback: function(value: number | string) {
              const num = typeof value === 'string' ? parseFloat(value) : value
              if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M'
              if (num >= 1000) return (num / 1000).toFixed(0) + 'k'
              return num.toFixed(0)
            },
          },
          border: { display: false },
        },
      },
    },
  })
}

// Create all charts based on chartConfig
const createCharts = () => {
  destroyCharts()
  const config = props.chartConfig
  if (!config) return

  if (config.dual) {
    if (chartCanvas1.value) {
      chartInstance1 = createSparklineChart(
        chartCanvas1.value,
        config.dual.primaryData,
        config.dual.primaryPreviousData,
        config.dual.primaryColor,
        config.dual.primaryLabel
      )
    }
    if (chartCanvas2.value) {
      chartInstance2 = createSparklineChart(
        chartCanvas2.value,
        config.dual.secondaryData,
        config.dual.secondaryPreviousData,
        config.dual.secondaryColor,
        config.dual.secondaryLabel
      )
    }
  } else if (config.single) {
    if (chartCanvas1.value) {
      chartInstance1 = createSparklineChart(
        chartCanvas1.value,
        config.single.data,
        config.single.previousData,
        config.single.color,
        config.single.label
      )
    }
  }
}

// Destroy chart instances
const destroyCharts = () => {
  if (chartInstance1) { chartInstance1.destroy(); chartInstance1 = null }
  if (chartInstance2) { chartInstance2.destroy(); chartInstance2 = null }
}

// Reset chart state when card is collapsed
watch(expansionLevel, (level) => {
  if (level === 0) {
    isChartExpanded.value = false
    destroyCharts()
  }
})

// Watch chart expansion - lazy initialize charts
watch(isChartExpanded, async (expanded) => {
  if (expanded && props.chartConfig) {
    await nextTick()
    createCharts()
  } else {
    destroyCharts()
  }
})

// Cleanup on unmount
onBeforeUnmount(() => {
  destroyCharts()
})

// Computed: Label based on type
const label = computed(() => {
  const labels: Record<CardType, string> = {
    trezorerie: 'TREZORERIE',
    clienti: 'CLIENȚI',
    furnizori: 'FURNIZORI',
    tva: 'DATORII LA BUGET',
    cashflow: 'CASH FLOW'
  }
  return labels[props.type] || props.type.toUpperCase()
})

// Computed: Value color class based on type and value
const valueColorClass = computed(() => {
  if (props.type === 'tva') {
    // total = tvaPreviousMonthNet = plata - recuperat
    // pozitiv = datorie la buget (roșu), zero/negativ = fără datorie (verde)
    return props.total > 0
      ? 'solduri-compact-card__value--danger'
      : 'solduri-compact-card__value--success'
  }
  if (props.type === 'cashflow') {
    return props.total >= 0
      ? 'solduri-compact-card__value--success'
      : 'solduri-compact-card__value--danger'
  }
  return ''
})

// Computed: Total obligații curente (doar pentru type === 'tva')
const curentTotal = computed(() => {
  if (!Array.isArray(props.breakdown)) return 0
  return (props.breakdown as any[])
    .filter((g: any) => Number(g.curent || 0) > 0)
    .reduce((sum: number, g: any) => sum + Number(g.curent || 0), 0)
})

// Computed: Check if breakdown data exists
const hasBreakdown = computed(() => {
  if (props.type === 'trezorerie') {
    return props.casaTotal !== undefined || props.bancaTotal !== undefined || props.breakdown
  }
  if (props.type === 'clienti' || props.type === 'furnizori') {
    return props.breakdown !== null && props.breakdown !== undefined
  }
  if (props.type === 'tva') {
    return props.breakdown !== null && props.breakdown !== undefined
  }
  if (props.type === 'cashflow') {
    return props.breakdown !== null && props.breakdown !== undefined
  }
  return false
})

// Max expansion levels per card type
const maxExpansionLevel = computed(() => {
  // TVA and cashflow: only 1 level (0 → 1 → 0)
  if (props.type === 'tva' || props.type === 'cashflow') return 1
  // Trezorerie, clienti, furnizori: 2 levels (0 → 1 → 2 → 0)
  return 2
})

// Methods
const toggleExpanded = () => {
  if (!hasBreakdown.value) return
  const next = expansionLevel.value + 1
  expansionLevel.value = next > maxExpansionLevel.value ? 0 : next
}

const formatAmount = (amount: number | undefined | null): string => {
  if (amount === undefined || amount === null) return '0'
  return new Intl.NumberFormat('ro-RO', {
    style: 'decimal',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  }).format(amount)
}

const formatPeriodLabel = (key: string): string => {
  const labelMap: Record<string, string> = {
    '7_zile': '7 zile',
    '14_zile': '14 zile',
    '30_zile': '30 zile',
    '60_zile': '60 zile',
    '90_zile': '90 zile',
    'peste_90_zile': 'Peste 90 zile'
  }
  return labelMap[key] || key
}
</script>

<style scoped>
/* SolduriCompactCard - Compact card for 2x2 grid layout */

.solduri-compact-card {
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-md);
  padding: var(--space-md);
  cursor: pointer;
  transition: all var(--transition-fast);
  min-height: 80px;
  display: flex;
  flex-direction: column;
  gap: var(--space-sm);
}

.solduri-compact-card:hover {
  box-shadow: var(--shadow-md);
  border-color: var(--color-primary);
}

.solduri-compact-card:active {
  transform: scale(0.98);
}

/* Header Layout */
.solduri-compact-card__header {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
}

/* Content */
.solduri-compact-card__content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--space-xs);
  min-width: 0;
}

.solduri-compact-card__label {
  font-size: var(--text-xs);
  font-weight: var(--font-semibold);
  color: var(--color-text-secondary);
}

.solduri-compact-card__value {
  font-size: var(--text-lg);
  font-weight: var(--font-bold);
  color: var(--color-text);
  font-family: var(--font-mono, monospace);
  line-height: var(--leading-tight);
}

/* Debt line: datorat · sold inline, same font */
.solduri-compact-card__debt-line {
  display: flex;
  align-items: baseline;
  gap: var(--space-xs);
  flex-wrap: wrap;
}

.solduri-compact-card__debt-sep {
  color: var(--text-color-secondary);
  font-size: var(--text-lg);
  font-weight: var(--font-bold);
}

.solduri-compact-card__value--sold {
  color: var(--text-color-secondary);
}

/* Value color modifiers */
.solduri-compact-card__value--success {
  color: var(--green-600);
}

.solduri-compact-card__value--danger {
  color: var(--red-600);
}

/* Chevron */
.solduri-compact-card__chevron {
  color: var(--color-text-secondary);
  font-size: var(--text-sm);
  transition: transform var(--transition-fast);
}

.solduri-compact-card__chevron--expanded {
  transform: rotate(180deg);
}

/* Breakdown Section */
.solduri-compact-card__breakdown {
  padding-top: var(--space-sm);
  border-top: 1px solid var(--surface-border);
  display: flex;
  flex-direction: column;
  gap: var(--space-xs);
}

.solduri-compact-card__breakdown-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-xs) 0;
}

.solduri-compact-card__breakdown-label {
  font-size: var(--text-sm);
  color: var(--color-text-secondary);
  font-weight: var(--font-medium);
}

.solduri-compact-card__breakdown-value {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  color: var(--color-text);
  font-family: var(--font-mono, monospace);
}

.solduri-compact-card__breakdown-value--success {
  color: var(--green-600);
}

.solduri-compact-card__breakdown-value--danger {
  color: var(--red-600);
}

.solduri-compact-card__breakdown-value--warning {
  color: var(--orange-600);
}

/* Sub-items (indented) */
.solduri-compact-card__breakdown-subitem {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-xs) 0;
  padding-left: var(--space-md);
}

.solduri-compact-card__breakdown-sublabel {
  font-size: var(--text-sm);
  color: var(--color-text-secondary);
}

.solduri-compact-card__breakdown-subvalue {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--color-text);
  font-family: var(--font-mono, monospace);
}

/* TVA: 3-column grid layout (label | datorat | sold) */
.solduri-compact-card__debt-header,
.solduri-compact-card__breakdown-group,
.solduri-compact-card__breakdown-subitem {
  display: grid;
  grid-template-columns: 1fr auto auto;
  gap: var(--space-sm);
  align-items: center;
}

.solduri-compact-card__col-head {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
  text-align: right;
  min-width: 54px;
}

/* Override: breakdown-value/subvalue right-aligned with min-width in grid */
.solduri-compact-card__breakdown-group .solduri-compact-card__breakdown-value,
.solduri-compact-card__breakdown-subitem .solduri-compact-card__breakdown-subvalue {
  text-align: right;
  min-width: 54px;
}

/* TVA grup toggle */
.solduri-compact-card__breakdown-group {
  cursor: pointer;
  font-weight: var(--font-semibold);
  padding: var(--space-xs) 0;
}
.solduri-compact-card__breakdown-group:hover { background: var(--surface-hover); }

.solduri-compact-card__group-label {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
}

.solduri-compact-card__group-toggle {
  font-size: var(--text-xs);
  color: var(--color-text-secondary);
  transition: transform var(--transition-fast);
}
.solduri-compact-card__group-toggle--expanded { transform: rotate(90deg); }

/* Cleared (paid) indicator */
.solduri-compact-card__cleared {
  color: var(--green-600);
  font-weight: var(--font-semibold);
}

/* Divider between breakdown and obligații curente */
.solduri-compact-card__divider {
  height: 1px;
  background: var(--surface-border);
  margin: var(--space-sm) 0;
}

/* Obligații curente section */
.solduri-compact-card__curent-summary {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-xs);
  align-items: center;
}

.solduri-compact-card__curent-title {
  font-size: var(--text-xs);
  color: var(--text-color-secondary);
}

.solduri-compact-card__curent-chip {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  background: var(--surface-hover);
  border-radius: var(--radius-sm);
  padding: 2px var(--space-xs);
  color: var(--text-color);
}

.solduri-compact-card__curent-total {
  font-size: var(--text-sm);
  font-weight: var(--font-bold);
  font-family: var(--font-mono, monospace);
  color: var(--text-color);
  margin-left: var(--space-xs);
}

/* Responsive - Mobile */
@media (max-width: 768px) {
  .solduri-compact-card {
    padding: var(--space-sm);
    min-height: 70px;
  }

  .solduri-compact-card__value {
    font-size: var(--text-base);
  }

  .solduri-compact-card__breakdown-subitem {
    padding-left: var(--space-sm);
  }
}

/* Touch target compliance - minimum 44x44px */
@media (pointer: coarse) {
  .solduri-compact-card {
    min-height: 80px;
  }
}

/* Chart toggle */
.solduri-compact-card__charts-toggle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-sm) var(--space-md);
  background: var(--surface-hover);
  border-radius: var(--radius-sm);
  cursor: pointer;
  min-height: 44px;
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--color-text-secondary);
  transition: background-color var(--transition-fast);
}

.solduri-compact-card__charts-toggle:hover {
  background: var(--surface-border);
}

.solduri-compact-card__charts-toggle-label {
  user-select: none;
}

.solduri-compact-card__charts-chevron {
  font-size: var(--text-xs);
  color: var(--color-text-secondary);
  transition: transform var(--transition-fast);
}

.solduri-compact-card__charts-chevron--expanded {
  transform: rotate(90deg);
}

/* Chart content */
.solduri-compact-card__charts-content {
  display: flex;
  flex-direction: column;
  gap: var(--space-sm);
}

.solduri-compact-card__chart-wrapper {
  background: var(--surface-ground);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  padding: var(--space-sm);
}

.solduri-compact-card__chart-label {
  font-size: var(--text-xs);
  font-weight: var(--font-semibold);
  margin-bottom: var(--space-xs);
}

.solduri-compact-card__chart-container {
  height: 150px;
  position: relative;
}

.solduri-compact-card__chart-container canvas {
  width: 100% !important;
  height: 100% !important;
  display: block;
}

/* Responsive - Chart adjustments */
@media (max-width: 480px) {
  .solduri-compact-card__chart-container {
    height: 130px;
  }
}
</style>
