<template>
  <!-- Mobile: self-styled collapsible card (matches SolduriCompactCard) -->
  <div
    v-if="mobile"
    class="financial-indicators-card"
    :class="{ 'financial-indicators-card--expanded': isExpanded }"
    @click="toggleExpanded"
  >
    <div class="financial-indicators-card__header">
      <div class="financial-indicators-card__content">
        <span class="financial-indicators-card__label">Indicatori</span>
        <span v-if="loading" class="financial-indicators-card__value financial-indicators-card__value--muted">
          <i class="pi pi-spin pi-spinner"></i>
        </span>
        <span v-else-if="error" class="financial-indicators-card__value financial-indicators-card__value--danger">
          Eroare
        </span>
        <span v-else-if="summaryValue !== null" class="financial-indicators-card__value">
          {{ summaryFormatted }}
        </span>
        <span v-else class="financial-indicators-card__value financial-indicators-card__value--muted">-</span>
      </div>
      <i
        class="pi pi-chevron-down financial-indicators-card__chevron"
        :class="{ 'financial-indicators-card__chevron--expanded': isExpanded }"
      ></i>
    </div>
    <div v-if="isExpanded && data" class="financial-indicators-card__breakdown">
      <div v-for="kpi in kpiList" :key="kpi.key" class="financial-indicators-card__breakdown-item">
        <span class="financial-indicators-card__breakdown-label">{{ kpi.label }}</span>
        <span class="financial-indicators-card__breakdown-value">{{ kpi.formatted }}</span>
        <span class="financial-indicators-card__breakdown-delta" :class="kpi.deltaClass">{{ kpi.deltaText }}</span>
      </div>
      <router-link to="/reports/financial-indicators" class="financial-indicators-card__see-all" @click.stop>
        Vezi toți indicatorii →
      </router-link>
    </div>
  </div>

  <!-- Desktop: plain content (rendered inside CollapsibleCard wrapper) -->
  <div v-else class="financial-indicators-content">
    <div v-if="loading" class="financial-indicators-content__state">
      <i class="pi pi-spin pi-spinner"></i> Se încarcă...
    </div>
    <div v-else-if="error" class="financial-indicators-content__state financial-indicators-content__state--error">
      <i class="pi pi-exclamation-triangle"></i> {{ error }}
    </div>
    <div v-else-if="data" class="financial-indicators-content__list">
      <div v-for="kpi in kpiList" :key="kpi.key" class="financial-indicators-content__row">
        <span class="financial-indicators-content__label">{{ kpi.label }}</span>
        <span class="financial-indicators-content__value">{{ kpi.formatted }}</span>
        <span class="financial-indicators-content__delta" :class="kpi.deltaClass">{{ kpi.deltaText }}</span>
      </div>
      <router-link to="/reports/financial-indicators" class="financial-indicators-card__see-all">
        Vezi toți indicatorii →
      </router-link>
    </div>
    <div v-else class="financial-indicators-content__state">Nu există date</div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'

const props = defineProps({
  loading: Boolean,
  error: String,
  data: Object,
  mobile: Boolean,
  // { luna: number, an: number } — ultima lună închisă, transmisă de DashboardView
  period: Object
})

const isExpanded = ref(false)

const toggleExpanded = () => {
  isExpanded.value = !isExpanded.value
}

// Summary value for collapsed header: Marjă Profit Brut (%)
const summaryValue = computed(() => {
  return props.data?.profitabilitate?.marja_profit_brut?.value ?? null
})

const summaryFormatted = computed(() => {
  if (summaryValue.value === null) return '-'
  return `${Number(summaryValue.value).toLocaleString('ro-RO', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  })}% Marjă`
})

const getDelta = (indicator) => {
  const sparkline = indicator?.sparkline_data
  if (!sparkline || sparkline.length < 2) return null
  const current = sparkline[sparkline.length - 1]
  const previous = sparkline[sparkline.length - 2]
  if (previous === 0 || previous === null || previous === undefined) return null
  return {
    change: current - previous,
    pct: ((current - previous) / Math.abs(previous)) * 100
  }
}

const formatDelta = (delta) => {
  if (!delta) return ''
  const sign = delta.change > 0 ? '▲' : '▼'
  const pct = Math.abs(delta.pct).toFixed(1)
  return `${sign} ${pct}%`
}

const getDeltaClass = (delta) => {
  if (!delta) return ''
  return delta.change > 0 ? 'delta-up' : 'delta-down'
}

const formatNumber = (val, decimals = 2) => {
  if (val === null || val === undefined) return '-'
  return Number(val).toLocaleString('ro-RO', {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals
  })
}

const formatCurrency = (val) => {
  if (val === null || val === undefined) return '-'
  return Number(val).toLocaleString('ro-RO', { maximumFractionDigits: 0 })
}

const kpiList = computed(() => {
  if (!props.data) return []
  const d = props.data
  const items = [
    {
      key: 'lichiditate_imediata',
      label: 'Lichiditate',
      indicator: d?.lichiditate?.lichiditate_imediata,
      format: (v) => formatNumber(v, 0)
    },
    {
      key: 'profit_brut',
      label: 'Profit Brut',
      indicator: d?.profitabilitate?.profit_brut,
      format: (v) => formatCurrency(v)
    },
    {
      key: 'marja_profit',
      label: 'Marjă Profit',
      indicator: d?.profitabilitate?.marja_profit_brut,
      format: (v) => `${formatNumber(v, 0)}%`
    },
    {
      key: 'dso',
      label: 'DSO',
      indicator: d?.eficienta?.dso,
      format: (v) => `${formatNumber(v, 0)} zile`
    },
    {
      key: 'zscore',
      label: 'Z-Score',
      indicator: d?.altman_zscore?.zscore,
      format: (v) => formatNumber(v, 1)
    }
  ]
  return items.map(item => {
    const delta = getDelta(item.indicator)
    return {
      key: item.key,
      label: item.label,
      formatted: item.format(item.indicator?.value),
      deltaText: formatDelta(delta),
      deltaClass: getDeltaClass(delta)
    }
  })
})
</script>

<style scoped>
/* Card container - matches SolduriCompactCard pattern */
.financial-indicators-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);
}

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

.financial-indicators-card:active {
  transform: scale(0.98);
}

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

.financial-indicators-card__content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--space-xs);
  min-width: 0;
}

.financial-indicators-card__label {
  font-size: var(--text-xs);
  font-weight: var(--font-semibold);
  color: var(--color-text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.financial-indicators-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);
}

.financial-indicators-card__value--muted {
  color: var(--text-color-secondary);
}

.financial-indicators-card__value--danger {
  color: var(--red-600);
}

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

.financial-indicators-card__chevron--expanded {
  transform: rotate(180deg);
}

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

.financial-indicators-card__breakdown-item {
  display: flex;
  align-items: center;
  padding: var(--space-xs) 0;
  gap: var(--space-sm);
}

.financial-indicators-card__breakdown-label {
  flex: 1;
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
}

.financial-indicators-card__breakdown-value {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  font-variant-numeric: tabular-nums;
  color: var(--text-color);
  white-space: nowrap;
}

.financial-indicators-card__breakdown-delta {
  font-size: var(--text-xs);
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
  min-width: 50px;
  text-align: right;
}

.delta-up {
  color: var(--green-600);
}

.delta-down {
  color: var(--red-600);
}

/* "Vezi toți" link */
.financial-indicators-card__see-all {
  display: block;
  text-align: center;
  padding-top: var(--space-sm);
  font-size: var(--text-sm);
  color: var(--color-primary);
  text-decoration: none;
  font-weight: var(--font-medium);
}

.financial-indicators-card__see-all:hover {
  text-decoration: underline;
}

/* ===== Desktop: plain content inside CollapsibleCard ===== */
.financial-indicators-content {
  padding: var(--space-sm) var(--space-lg);
}

.financial-indicators-content__state {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  padding: var(--space-sm) 0;
  color: var(--text-color-secondary);
  font-size: var(--text-sm);
}

.financial-indicators-content__state--error {
  color: var(--red-600);
}

.financial-indicators-content__list {
  display: flex;
  flex-direction: column;
}

.financial-indicators-content__row {
  display: flex;
  align-items: center;
  padding: var(--space-xs) 0;
  border-bottom: 1px solid var(--surface-border);
  gap: var(--space-sm);
  min-height: 36px;
}

.financial-indicators-content__row:last-of-type {
  border-bottom: none;
}

.financial-indicators-content__label {
  flex: 1;
  font-size: var(--text-sm);
  color: var(--text-color);
}

.financial-indicators-content__value {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  font-variant-numeric: tabular-nums;
  color: var(--text-color);
  white-space: nowrap;
}

.financial-indicators-content__delta {
  font-size: var(--text-xs);
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
  min-width: 50px;
  text-align: right;
}

/* Dark mode */
[data-theme="dark"] .delta-up {
  color: var(--green-400);
}

[data-theme="dark"] .delta-down {
  color: var(--red-400);
}

[data-theme="dark"] .financial-indicators-card__value--danger,
[data-theme="dark"] .financial-indicators-content__state--error {
  color: var(--red-400);
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) .delta-up {
    color: var(--green-400);
  }
  :root:not([data-theme]) .delta-down {
    color: var(--red-400);
  }
}
</style>
