<template>
  <!-- Mobile Top Bar -->
  <MobileTopBar
    v-if="isMobile"
    :title="dashboardTitle"
    :show-menu="true"
    :actions="mobileTopBarActions"
    @menu-click="showDrawer = true"
    @action-click="handleMobileAction"
  />

  <!-- Mobile Drawer Menu (replaces old Sidebar) -->
  <MobileDrawerMenu
    v-model="showDrawer"
    :user="authStore.user"
    :companies-store="companyStore"
    :period-store="periodStore"
    :available-servers="authStore.availableServers"
    :current-server-id="authStore.selectedServerId"
    :auth-store="authStore"
    @logout="handleLogout"
    @server-switched="handleServerSwitched"
  />

  <main class="main-content" :class="{ 'mobile-layout': isMobile }">
    <div class="app-container">
      <!-- Dashboard Header - only on desktop -->
      <div v-if="!isMobile" class="page-header">
        <h1 class="page-title">Dashboard</h1>
        <Button
          icon="pi pi-refresh"
          text
          rounded
          class="refresh-btn"
          :class="{ 'is-loading': isLoading }"
          @click="handleRefresh"
          v-tooltip.bottom="'Actualizează datele'"
          aria-label="Actualizează datele"
        />
      </div>

      <!-- Company selection removed - now handled in header only -->

      <!-- Loading Bar - non-blocking, subtle indicator while data loads -->
      <div v-if="isLoading" class="loading-bar-container">
        <div class="loading-bar"></div>
      </div>

      <!-- Secțiune Carduri Noi - Adăugare -->
      <div class="metrics-cards-section">
        <!-- Mobile: Swipeable KPI Cards Carousel -->
        <!-- 2 pages: enriched compact cards with embedded charts + financial indicators -->
        <SwipeableCards v-if="isMobile" :totalCards="1" :fixed-dots="false" :fill-height="true" class="mobile-kpi-carousel">
          <!-- Page 1: Compact cards with embedded sparkline charts -->
          <template #card-0>
            <div class="solduri-grid-2x2">
              <SolduriCompactCard
                type="trezorerie"
                :total="totalTrezorerie"
                :casaTotal="treasuryData?.breakdown?.casa?.total || 0"
                :bancaTotal="treasuryData?.breakdown?.banca?.total || 0"
                :breakdown="treasuryData?.breakdown"
                :chartConfig="{
                  dual: {
                    primaryData: casaSparkline,
                    primaryPreviousData: casaPreviousSparkline,
                    primaryLabel: 'Casa',
                    primaryColor: '#10b981',
                    secondaryData: bancaSparkline,
                    secondaryPreviousData: bancaPreviousSparkline,
                    secondaryLabel: 'Bancă',
                    secondaryColor: '#3b82f6'
                  },
                  labels: sparklineLabels
                }"
              />
              <SolduriCompactCard
                type="cashflow"
                :total="netCashFlow"
                :breakdown="{ incasari: monthlyInflows, plati: monthlyOutflows }"
                :chartConfig="{
                  dual: {
                    primaryData: inflowsSparkline,
                    primaryPreviousData: inflowsPreviousSparkline,
                    primaryLabel: 'Încasări',
                    primaryColor: '#10b981',
                    secondaryData: outflowsSparkline,
                    secondaryPreviousData: outflowsPreviousSparkline,
                    secondaryLabel: 'Plăți',
                    secondaryColor: '#ef4444'
                  },
                  labels: sparklineLabels
                }"
              />
              <SolduriCompactCard
                type="clienti"
                :total="netBalanceData?.clienti_total || 0"
                :breakdown="netBalanceData?.breakdown?.clienti"
                :chartConfig="{
                  single: {
                    data: clientiSparkline,
                    previousData: clientiPreviousSparkline,
                    label: 'Clienți',
                    color: '#10b981'
                  },
                  labels: sparklineLabels
                }"
              />
              <SolduriCompactCard
                type="furnizori"
                :total="netBalanceData?.furnizori_total || 0"
                :breakdown="netBalanceData?.breakdown?.furnizori"
                :chartConfig="{
                  single: {
                    data: furnizoriSparkline,
                    previousData: furnizoriPreviousSparkline,
                    label: 'Furnizori',
                    color: '#f59e0b'
                  },
                  labels: sparklineLabels
                }"
              />
              <SolduriCompactCard
                type="tva"
                :total="budgetDebtTotalPrecedent"
                :sold-total="budgetDebtSold"
                :breakdown="tvaBreakdown"
              />
              <FinancialIndicatorsCard
                :loading="dashboardStore.financialIndicators.loading"
                :error="dashboardStore.financialIndicators.error"
                :data="dashboardStore.financialIndicators.data"
                :period="previousPeriodForIndicators"
                mobile
              />
            </div>
          </template>
        </SwipeableCards>

        <!-- Desktop: Grid layout (carduri grafice originale) - collapsible by default -->
        <div v-if="!isMobile" class="metrics-row">
          <CollapsibleCard
            label="Trezorerie"
            :value="totalTrezorerie"
            :value-class="totalTrezorerie >= 0 ? 'positive' : 'negative'"
          >
            <TreasuryDualCard
              :casaTotal="treasuryData?.breakdown?.casa?.total || 0"
              :bancaTotal="treasuryData?.breakdown?.banca?.total || 0"
              :casaItems="treasuryData?.breakdown?.casa?.items || []"
              :bancaItems="treasuryData?.breakdown?.banca?.items || []"
              :casaTrend="casaTrend"
              :bancaTrend="bancaTrend"
              :casaSparklineData="casaSparkline"
              :bancaSparklineData="bancaSparkline"
              :casaPreviousSparklineData="casaPreviousSparkline"
              :bancaPreviousSparklineData="bancaPreviousSparkline"
              :sparklineLabels="sparklineLabels"
              :previousSparklineLabels="previousSparklineLabels"
              :cacheInfo="treasuryCacheInfo"
            />
          </CollapsibleCard>
          <CollapsibleCard
            label="Cash Flow"
            :value="netCashFlow"
            :value-class="netCashFlow >= 0 ? 'positive' : 'negative'"
          >
            <CashFlowMetricCard
              :inflowsValue="monthlyInflows"
              :outflowsValue="monthlyOutflows"
              :inflowsTrend="inflowsTrend"
              :outflowsTrend="outflowsTrend"
              :inflowsSparkline="inflowsSparkline"
              :outflowsSparkline="outflowsSparkline"
              :inflowsPreviousSparkline="inflowsPreviousSparkline"
              :outflowsPreviousSparkline="outflowsPreviousSparkline"
              :sparklineLabels="sparklineLabels"
              :previousSparklineLabels="previousSparklineLabels"
              :cacheInfo="cashflowCacheInfo"
            />
          </CollapsibleCard>
          <CollapsibleCard
            label="Clienți"
            :value="netBalanceData?.clienti_total || 0"
            :value-class="(netBalanceData?.clienti_total || 0) >= 0 ? 'positive' : 'negative'"
          >
            <ClientiBalanceCard
              :total="netBalanceData?.clienti_total || 0"
              :trend="clientiTrend"
              :sparklineData="clientiSparkline"
              :previousSparklineData="clientiPreviousSparkline"
              :sparklineLabels="sparklineLabels"
              :previousSparklineLabels="previousSparklineLabels"
              :breakdown="netBalanceData?.breakdown?.clienti"
              :cacheInfo="netBalanceCacheInfo"
            />
          </CollapsibleCard>
          <CollapsibleCard
            label="Furnizori"
            :value="netBalanceData?.furnizori_total || 0"
            :value-class="(netBalanceData?.furnizori_total || 0) <= 0 ? 'positive' : 'negative'"
          >
            <FurnizoriBalanceCard
              :total="netBalanceData?.furnizori_total || 0"
              :trend="furnizoriTrend"
              :sparklineData="furnizoriSparkline"
              :previousSparklineData="furnizoriPreviousSparkline"
              :sparklineLabels="sparklineLabels"
              :previousSparklineLabels="previousSparklineLabels"
              :breakdown="netBalanceData?.breakdown?.furnizori"
              :cacheInfo="netBalanceCacheInfo"
            />
          </CollapsibleCard>
          <CollapsibleCard
            label="Datorii la buget"
            :value="budgetDebtHeaderValue"
            :value-class="budgetDebtSold > 0 ? 'negative' : (budgetDebtTotalPrecedent > 0 ? 'positive' : '')"
          >
            <div class="budget-debt-breakdown-desktop">
              <div class="budget-debt-breakdown-header">
                <span></span>
                <span class="budget-debt-col-header-value">Datorat</span>
                <span class="budget-debt-col-header-value budget-debt-col-achitat">Achitat</span>
                <span class="budget-debt-col-header-value">Sold</span>
              </div>

              <template v-for="group in budgetDebtBreakdown" :key="group.key">
                <!-- Rând grup (clickabil pentru expand sub-conturi) -->
                <div
                  class="budget-debt-breakdown-row budget-debt-group-row"
                  @click="toggleBudgetGroup(group.key)"
                >
                  <span class="budget-debt-col-label budget-debt-group-label">
                    <i class="pi pi-chevron-right budget-debt-toggle"
                       :class="{ expanded: expandedBudgetGroups.has(group.key) }"></i>
                    {{ group.label }}
                  </span>
                  <span class="budget-debt-col-value">
                    {{ group.datorat > 0 ? formatAmount(group.datorat) : '-' }}
                  </span>
                  <span class="budget-debt-col-value budget-debt-paid budget-debt-col-achitat">
                    {{ group.achitat > 0 ? formatAmount(group.achitat) : '-' }}
                  </span>
                  <span class="budget-debt-col-value" :class="{ 'budget-debt-cleared': group.sold <= 0 && group.datorat > 0 }">
                    {{ group.sold > 0 ? formatAmount(group.sold) : (group.datorat > 0 ? '✓' : '-') }}
                  </span>
                </div>

                <!-- Sub-conturi (expandabile) -->
                <div v-show="expandedBudgetGroups.has(group.key)" class="budget-debt-sub-accounts">
                  <div
                    v-for="acc in group.sub_accounts"
                    :key="acc.cont"
                    class="budget-debt-breakdown-row budget-debt-subrow"
                  >
                    <span class="budget-debt-col-label budget-debt-sub-label">{{ acc.label }}</span>
                    <span class="budget-debt-col-value budget-debt-sub-value">
                      {{ acc.datorat > 0 ? formatAmount(acc.datorat) : '-' }}
                    </span>
                    <span class="budget-debt-col-value budget-debt-sub-value budget-debt-paid budget-debt-col-achitat">
                      {{ acc.achitat > 0 ? formatAmount(acc.achitat) : '-' }}
                    </span>
                    <span class="budget-debt-col-value budget-debt-sub-value" :class="{ 'budget-debt-cleared': acc.sold <= 0 && acc.datorat > 0 }">
                      {{ acc.sold > 0 ? formatAmount(acc.sold) : (acc.datorat > 0 ? '✓' : '-') }}
                    </span>
                  </div>
                </div>
              </template>

              <div v-if="budgetDebtBreakdown.length === 0" class="budget-debt-breakdown-empty">
                Nu există datorii înregistrate
              </div>

              <!-- Obligații luna curentă - compact, fără sub-secțiune -->
              <template v-if="budgetDebtBreakdownCurent.length > 0">
                <div class="budget-debt-section-divider"></div>
                <div class="budget-debt-curent-summary">
                  <span class="budget-debt-curent-title">Obligații curente:</span>
                  <span
                    v-for="group in budgetDebtBreakdownCurent"
                    :key="'crt-' + group.key"
                    class="budget-debt-curent-chip"
                  >{{ group.label }} {{ formatAmount(group.curent) }}</span>
                  <span class="budget-debt-curent-total">= {{ formatAmount(budgetDebtTotalCurent) }}</span>
                </div>
              </template>
            </div>
          </CollapsibleCard>
          <CollapsibleCard
            label="Indicatori"
            :value="indicatorsSummaryLabel"
            value-class=""
          >
            <FinancialIndicatorsCard
              :loading="dashboardStore.financialIndicators.loading"
              :error="dashboardStore.financialIndicators.error"
              :data="dashboardStore.financialIndicators.data"
              :period="previousPeriodForIndicators"
            />
          </CollapsibleCard>
        </div>

      </div>

    </div>
  </main>

  <!-- Mobile Bottom Nav - US-307: Using default nav items -->
  <MobileBottomNav v-if="isMobile" />
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useRouter } from "vue-router";
import { useToast } from "primevue/usetoast";
import Button from "primevue/button";
// Import componente noi
import MetricCard from "@reports/components/dashboard/cards/MetricCard.vue";
import CashFlowMetricCard from "@reports/components/dashboard/cards/CashFlowMetricCard.vue";
import ClientiBalanceCard from "@reports/components/dashboard/cards/ClientiBalanceCard.vue";
import FurnizoriBalanceCard from "@reports/components/dashboard/cards/FurnizoriBalanceCard.vue";
import TreasuryDualCard from "@reports/components/dashboard/cards/TreasuryDualCard.vue";
import SolduriCompactCard from "@reports/components/solduri/SolduriCompactCard.vue";
import FinancialIndicatorsCard from "@reports/components/dashboard/cards/FinancialIndicatorsCard.vue";
import CollapsibleCard from "@shared/components/CollapsibleCard.vue";
// Mobile components
import SwipeableCards from "@shared/components/mobile/SwipeableCards.vue";
import MobileTopBar from "@shared/components/mobile/MobileTopBar.vue";
import MobileBottomNav from "@shared/components/mobile/MobileBottomNav.vue";
import MobileDrawerMenu from "@shared/components/mobile/MobileDrawerMenu.vue";
import { useCompanyStore, useAuthStore } from "@reports/stores/sharedStores";
import { useDashboardStore } from "@reports/stores/dashboard";
import { useAccountingPeriodStore } from "@reports/stores/sharedStores";
import api, { getWithCacheInfo } from "@reports/services/api";
import {
  exportToExcel,
  exportToPDF,
  exportTrendData as prepareTrendData,
} from "@reports/utils/exportUtils";

const toast = useToast();
const router = useRouter();
const companyStore = useCompanyStore();
const dashboardStore = useDashboardStore();
const periodStore = useAccountingPeriodStore();
const authStore = useAuthStore();

// State
const filteredCompanies = ref([]);
const isLoading = ref(false);
const showDrawer = ref(false);

// State pentru carduri
const monthlyInflows = ref(0);
const monthlyOutflows = ref(0);
const treasuryData = ref(null);
const netBalanceData = ref(null);

// Cache info state for each card
const treasuryCacheInfo = ref({ hit: false, time: 0, source: null });
const netBalanceCacheInfo = ref({ hit: false, time: 0, source: null });
const cashflowCacheInfo = ref({ hit: false, time: 0, source: null });

// New dashboard state
const selectedPeriod = ref("12m");
const selectedChartType = ref("line");

// Calculare trend bazată pe date reale din trends.raw
const calculateTrend = (metric) => {
  if (!dashboardStore.trends?.raw) return null;

  const raw = dashboardStore.trends.raw;
  let data = [];

  // Selectează datele corecte pentru fiecare metric
  switch (metric) {
    case "clienti":
      data = raw.clienti_sold || [];
      break;
    case "furnizori":
      data = raw.furnizori_sold || [];
      break;
    case "treasury":
      data = raw.trezorerie_sold || [];
      break;
    case "sold":
      // Sold net = clienti_sold - furnizori_sold
      if (raw.clienti_sold?.length && raw.furnizori_sold?.length) {
        data = raw.clienti_sold.map(
          (c, i) => Number(c || 0) - Number(raw.furnizori_sold[i] || 0),
        );
      }
      break;
    case "inflows":
      data = raw.clienti_incasat || [];
      break;
    case "outflows":
      data = raw.furnizori_achitat || [];
      break;
    default:
      return null;
  }

  // Trebuie să avem cel puțin 2 puncte de date pentru a calcula trend
  if (!data || data.length < 2) return null;

  const current = Number(data[data.length - 1]) || 0;
  const previous = Number(data[data.length - 2]) || 0;

  // Handle edge case: division by zero
  if (previous === 0) {
    return current > 0
      ? { value: 100, direction: "up" }
      : current < 0
        ? { value: 100, direction: "down" }
        : { value: 0, direction: "neutral" };
  }

  // Calculate percentage change
  const change = ((current - previous) / Math.abs(previous)) * 100;
  const direction = change > 0.1 ? "up" : change < -0.1 ? "down" : "neutral";

  return { value: Math.abs(change), direction };
};

// Obține date sparkline pentru mini grafice
const getSparklineData = (metric) => {
  if (!dashboardStore.trends?.raw) {
    return [];
  }

  const raw = dashboardStore.trends.raw;
  let data = [];

  switch (metric) {
    case "clienti":
      data = raw.clienti_sold || [];
      break;
    case "furnizori":
      data = raw.furnizori_sold || [];
      break;
    case "treasury":
      data = raw.trezorerie_sold || [];
      break;
    case "sold":
      // Sold net = clienti_sold - furnizori_sold
      if (raw.clienti_sold?.length && raw.furnizori_sold?.length) {
        data = raw.clienti_sold.map(
          (c, i) => Number(c || 0) - Number(raw.furnizori_sold[i] || 0),
        );
      }
      break;
    case "inflows":
      data = raw.clienti_incasat || [];
      break;
    case "outflows":
      data = raw.furnizori_achitat || [];
      break;
    default:
      return [];
  }

  // Returnează ultimele 12 valori pentru sparkline
  const sparklineData = data.slice(-12).map((v) => Number(v) || 0);
  return sparklineData;
};

// Obține labels pentru sparkline (ultimele 12 perioade)
const getSparklineLabels = () => {
  if (!dashboardStore.trends?.raw?.periods) {
    return [];
  }

  const periods = dashboardStore.trends.raw.periods;
  // Returnează ultimele 12 perioade, formatate scurt (MM/YY)
  return periods.slice(-12).map((period) => {
    const [year, month] = period.split("-");
    return `${month}/${year.slice(-2)}`; // Format: MM/YY
  });
};

// Obține date sparkline pentru perioada precedentă (year-over-year comparison)
const getPreviousSparklineData = (metric) => {
  if (!dashboardStore.trends?.raw) {
    return [];
  }

  const raw = dashboardStore.trends.raw;
  let data = [];

  switch (metric) {
    case "clienti":
      data = raw.clienti_sold_prev || [];
      break;
    case "furnizori":
      data = raw.furnizori_sold_prev || [];
      break;
    case "treasury":
      data = raw.trezorerie_sold_prev || [];
      break;
    case "inflows":
      data = raw.clienti_incasat_prev || [];
      break;
    case "outflows":
      data = raw.furnizori_achitat_prev || [];
      break;
    default:
      return [];
  }

  // Returnează ultimele 12 valori pentru sparkline (aceeași perioadă, anul anterior)
  const sparklineData = data.slice(-12).map((v) => Number(v) || 0);
  return sparklineData;
};

// Obține labels pentru sparkline perioada precedentă
const getPreviousSparklineLabels = () => {
  if (!dashboardStore.trends?.raw?.previous_periods) {
    return [];
  }

  const periods = dashboardStore.trends.raw.previous_periods;
  // Returnează ultimele 12 perioade precedente, formatate scurt (MM/YY)
  return periods.slice(-12).map((period) => {
    const [year, month] = period.split("-");
    return `${month}/${year.slice(-2)}`; // Format: MM/YY
  });
};

// Computed properties pentru carduri - REACTIVE!
const clientiTrend = computed(() => calculateTrend("clienti"));
const clientiSparkline = computed(() => getSparklineData("clienti"));
const clientiPreviousSparkline = computed(() =>
  getPreviousSparklineData("clienti"),
);

const furnizoriTrend = computed(() => calculateTrend("furnizori"));
const furnizoriSparkline = computed(() => getSparklineData("furnizori"));
const furnizoriPreviousSparkline = computed(() =>
  getPreviousSparklineData("furnizori"),
);

const soldTrend = computed(() => calculateTrend("sold"));
const soldSparkline = computed(() => getSparklineData("sold"));
const inflowsTrend = computed(() => calculateTrend("inflows"));
const inflowsSparkline = computed(() => getSparklineData("inflows"));
const inflowsPreviousSparkline = computed(() =>
  getPreviousSparklineData("inflows"),
);
const outflowsTrend = computed(() => calculateTrend("outflows"));
const outflowsSparkline = computed(() => getSparklineData("outflows"));
const outflowsPreviousSparkline = computed(() =>
  getPreviousSparklineData("outflows"),
);
const treasuryTrend = computed(() => calculateTrend("treasury"));
const treasurySparkline = computed(() => getSparklineData("treasury"));
const treasuryPreviousSparkline = computed(() =>
  getPreviousSparklineData("treasury"),
);
const sparklineLabels = computed(() => getSparklineLabels());
const previousSparklineLabels = computed(() => getPreviousSparklineLabels());

// US-2002: Computed properties for SolduriCompactCard grid
const totalTrezorerie = computed(() => {
  const casaTotal = treasuryData.value?.breakdown?.casa?.total || 0;
  const bancaTotal = treasuryData.value?.breakdown?.banca?.total || 0;
  return casaTotal + bancaTotal;
});

const tvaTotal = computed(() => {
  const s = dashboardStore.summary;
  if (!s) return 0;
  // Pozitiv = de recuperat, Negativ = de plată
  return Number(s.tva_recuperat_curent || 0) - Number(s.tva_plata_curent || 0);
});

const tvaPreviousMonth = computed(() => {
  const s = dashboardStore.summary;
  if (!s) return { plata: 0, recuperat: 0 };
  return {
    plata: Number(s.tva_plata_precedent || 0),
    recuperat: Number(s.tva_recuperat_precedent || 0),
  };
});

const tvaCurrentMonth = computed(() => {
  const s = dashboardStore.summary;
  if (!s) return { plata: 0, recuperat: 0 };
  return {
    plata: Number(s.tva_plata_curent || 0),
    recuperat: Number(s.tva_recuperat_curent || 0),
  };
});

// TVA net luna precedentă (valoare pozitivă = datorie la buget)
const tvaPreviousMonthNet = computed(() => {
  const prev = tvaPreviousMonth.value;
  return (prev.plata || 0) - (prev.recuperat || 0);
});

// Breakdown pe grupe datorii buget - DOAR grupe cu datorii din luna precedentă
const budgetDebtBreakdown = computed(() => {
  return (dashboardStore.summary?.budget_debt_breakdown || [])
    .filter(g => Number(g.datorat || 0) !== 0 || Number(g.precedent || 0) !== 0);
});

// Filtrare grupe cu obligații luna curentă (pentru secțiunea compactă)
const budgetDebtBreakdownCurent = computed(() =>
  (dashboardStore.summary?.budget_debt_breakdown || []).filter(g => Number(g.curent || 0) > 0)
);

// Total obligații curente (suma tuturor grupurilor din luna curentă)
const budgetDebtTotalCurent = computed(() =>
  budgetDebtBreakdownCurent.value.reduce((sum, g) => sum + Number(g.curent || 0), 0)
);

// Total precedent din toate grupurile (pentru header CollapsibleCard)
const budgetDebtTotalPrecedent = computed(() => {
  const groups = dashboardStore.summary?.budget_debt_breakdown || [];
  return groups.reduce((sum, g) => sum + Number(g.precedent || 0), 0);
});

// Sold final total (cât mai rămâne de plată după plățile din luna curentă)
const budgetDebtSold = computed(() => {
  const groups = dashboardStore.summary?.budget_debt_breakdown || [];
  return groups.reduce((sum, g) => sum + Number(g.sold || 0), 0);
});

// Header card: format "X.XXX (Y.YYY)" — total datorat și sold rămas
const budgetDebtHeaderValue = computed(() => {
  const datorat = budgetDebtTotalPrecedent.value;
  const sold = budgetDebtSold.value;
  if (datorat === 0 && sold === 0) return '-';
  const fmt = (n) => new Intl.NumberFormat('ro-RO').format(Math.round(Math.abs(n)));
  if (sold <= 0 && datorat > 0) return `${fmt(datorat)} (0 ✓)`;
  return `${fmt(datorat)} (${fmt(sold)})`;
});

const tvaBreakdown = computed(() => {
  return dashboardStore.summary?.budget_debt_breakdown || [];
});

// Reactive state pentru expand/collapse grupe buget
const expandedBudgetGroups = ref(new Set());
const toggleBudgetGroup = (key) => {
  if (expandedBudgetGroups.value.has(key)) {
    expandedBudgetGroups.value.delete(key);
  } else {
    expandedBudgetGroups.value.add(key);
  }
  // Force reactivity update on Set
  expandedBudgetGroups.value = new Set(expandedBudgetGroups.value);
};

// Net Cash Flow for CollapsibleCard header
const netCashFlow = computed(() => {
  return (monthlyInflows.value || 0) - (monthlyOutflows.value || 0);
});

// Casa and Bancă specific trends and sparklines
const casaTrend = computed(() => {
  // Calculate trend based on Casa proportion of treasury
  if (!treasuryData.value?.breakdown) return null;

  const casaTotal = treasuryData.value.breakdown.casa?.total || 0;
  const bancaTotal = treasuryData.value.breakdown.banca?.total || 0;
  const totalTreasury = casaTotal + bancaTotal;

  if (totalTreasury === 0) return null;

  // Use treasury trend as base, since we don't have separate casa trend data
  const tTrend = calculateTrend("treasury");
  return tTrend ? { ...tTrend } : null;
});

const casaSparkline = computed(() => {
  // Use treasury sparkline data scaled by casa proportion
  if (!treasuryData.value?.breakdown) return [];

  const sparklineData = getSparklineData("treasury");
  if (!sparklineData.length) return [];

  const casaTotal = treasuryData.value.breakdown.casa?.total || 0;
  const bancaTotal = treasuryData.value.breakdown.banca?.total || 0;
  const totalTreasury = casaTotal + bancaTotal;

  if (totalTreasury === 0) return sparklineData.map(() => 0);

  const casaProportion = casaTotal / totalTreasury;
  return sparklineData.map((v) => v * casaProportion);
});

const bancaTrend = computed(() => {
  // Calculate trend based on Bancă proportion of treasury
  if (!treasuryData.value?.breakdown) return null;

  const casaTotal = treasuryData.value.breakdown.casa?.total || 0;
  const bancaTotal = treasuryData.value.breakdown.banca?.total || 0;
  const totalTreasury = casaTotal + bancaTotal;

  if (totalTreasury === 0) return null;

  // Use treasury trend as base, since we don't have separate banca trend data
  const tTrend = calculateTrend("treasury");
  return tTrend ? { ...tTrend } : null;
});

const bancaSparkline = computed(() => {
  // Use treasury sparkline data scaled by banca proportion
  if (!treasuryData.value?.breakdown) return [];

  const sparklineData = getSparklineData("treasury");
  if (!sparklineData.length) return [];

  const casaTotal = treasuryData.value.breakdown.casa?.total || 0;
  const bancaTotal = treasuryData.value.breakdown.banca?.total || 0;
  const totalTreasury = casaTotal + bancaTotal;

  if (totalTreasury === 0) return sparklineData.map(() => 0);

  const bancaProportion = bancaTotal / totalTreasury;
  return sparklineData.map((v) => v * bancaProportion);
});

// Previous year sparklines for Casa and Bancă
const casaPreviousSparkline = computed(() => {
  if (!treasuryData.value?.breakdown) return [];

  const previousSparklineData = getPreviousSparklineData("treasury");
  if (!previousSparklineData.length) return [];

  const casaTotal = treasuryData.value.breakdown.casa?.total || 0;
  const bancaTotal = treasuryData.value.breakdown.banca?.total || 0;
  const totalTreasury = casaTotal + bancaTotal;

  if (totalTreasury === 0) return previousSparklineData.map(() => 0);

  const casaProportion = casaTotal / totalTreasury;
  return previousSparklineData.map((v) => v * casaProportion);
});

const bancaPreviousSparkline = computed(() => {
  if (!treasuryData.value?.breakdown) return [];

  const previousSparklineData = getPreviousSparklineData("treasury");
  if (!previousSparklineData.length) return [];

  const casaTotal = treasuryData.value.breakdown.casa?.total || 0;
  const bancaTotal = treasuryData.value.breakdown.banca?.total || 0;
  const totalTreasury = casaTotal + bancaTotal;

  if (totalTreasury === 0) return previousSparklineData.map(() => 0);

  const bancaProportion = bancaTotal / totalTreasury;
  return previousSparklineData.map((v) => v * bancaProportion);
});

// Detectare mobile - reactive with resize listener
const windowWidth = ref(window.innerWidth);
const isMobile = computed(() => windowWidth.value <= 768);

const dashboardTitle = computed(() => {
  const company = companyStore.selectedCompany?.name;
  const period = periodStore.selectedPeriod;
  if (!company) return 'Dashboard';
  if (period) {
    const lunaStr = String(period.luna).padStart(2, '0');
    return `${company} · ${lunaStr}/${period.an}`;
  }
  return company;
});

// Handle window resize for mobile detection
const handleResize = () => {
  windowWidth.value = window.innerWidth;
};

// US-307: Removed custom mobileNavItems - using MobileBottomNav defaults
// Dashboard is now at /dashboard with its own nav item

// Handle logout from drawer menu
const handleLogout = async () => {
  await authStore.logout();
  router.push('/login');
};

// Handle server switched from drawer menu (password already verified in modal)
const handleServerSwitched = async (newServerId) => {
  // Clear selected company and period FIRST to prevent stale data from old server
  companyStore.clearSelectedCompany();
  periodStore.reset();

  // Reload companies and periods for the new server
  await companyStore.loadCompanies();
  if (companyStore.selectedCompany?.id_firma) {
    await periodStore.loadPeriods(companyStore.selectedCompany.id_firma);
  }
  // Dashboard will reload automatically via watchers
};

// US-2008: Mobile top bar actions with refresh button
const mobileTopBarActions = computed(() => [
  {
    id: 'refresh',
    icon: isLoading.value ? 'pi pi-spin pi-refresh' : 'pi pi-refresh',
    label: 'Actualizează',
    tooltip: 'Actualizează datele'
  }
]);

// US-2008: Handle mobile action clicks
const handleMobileAction = async (action) => {
  if (action.id === 'refresh') {
    await handleRefresh();
  }
};

// US-2008: Handle refresh button click (shared between mobile and desktop)
const handleRefresh = async () => {
  if (isLoading.value) return; // Prevent multiple clicks during loading
  await loadDashboardData();
};

// Computed property pentru luna curentă - folosește perioada din period selector
const currentMonthLabel = computed(() => {
  // Prioritate: period selector > dashboard current period > loading
  if (periodStore.selectedPeriod) {
    const { an, luna } = periodStore.selectedPeriod;
    const date = new Date(an, luna - 1, 1);
    return date.toLocaleDateString("ro-RO", { month: "long", year: "numeric" });
  }

  if (dashboardStore.currentPeriod) {
    const { year, month } = dashboardStore.currentPeriod;
    const date = new Date(year, month - 1, 1);
    return date.toLocaleDateString("ro-RO", { month: "long", year: "numeric" });
  }

  return "Se încarcă...";
});

// Computed property pentru luna anterioară - pentru indicatorii financiari
// Luna curentă e în lucru, deci folosim luna anterioară pentru date finale
// Summary label for Indicators CollapsibleCard header (desktop)
const indicatorsSummaryLabel = computed(() => {
  const d = dashboardStore.financialIndicators.data;
  if (!d) return '';
  const marja = d?.profitabilitate?.marja_profit_brut?.value;
  if (marja === null || marja === undefined) return '';
  return `${Number(marja).toLocaleString('ro-RO', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}% Marjă`;
});

const previousPeriodForIndicators = computed(() => {
  if (!periodStore.selectedPeriod) return null;

  const { luna, an } = periodStore.selectedPeriod;

  // Calculează luna anterioară cu rollover la decembrie anul anterior
  if (luna === 1) {
    return { luna: 12, an: an - 1 };
  }
  return { luna: luna - 1, an };
});

// Methods
const handleCompanyChanged = async (company) => {
  if (company) {
    companyStore.setSelectedCompany(company);
    await loadDashboardData();
  }
};

const formatAmount = (amount) => {
  if (!amount && amount !== 0) return "0";
  const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
  if (isNaN(numAmount)) return "0";
  try {
    return new Intl.NumberFormat("ro-RO", {
      style: "decimal",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(numAmount);
  } catch {
    return numAmount.toLocaleString("ro-RO", { minimumFractionDigits: 0, maximumFractionDigits: 0 });
  }
};

const getBalanceClass = (amount) => {
  if (!amount && amount !== 0) return "neutral";
  const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
  return numAmount > 0 ? "positive" : numAmount < 0 ? "negative" : "neutral";
};

// Trend methods
const loadTrendData = async () => {
  if (!companyStore.selectedCompany) {
    console.warn("No company selected for trend data loading");
    return;
  }

  const luna = periodStore.selectedPeriod?.luna || null;
  const an = periodStore.selectedPeriod?.an || null;

  console.log(
    "Loading trend data for company:",
    companyStore.selectedCompany.id_firma,
    "luna:", luna, "an:", an,
  );

  const result = await dashboardStore.loadTrendData(
    companyStore.selectedCompany.id_firma,
    selectedPeriod.value,
    selectedChartType.value,
    luna,
    an,
  );

  if (result.success) {
    console.log("Trend data loaded successfully:", result.data);
    // Toast notification removed - it was showing on every dashboard refresh
  } else {
    console.error("Failed to load trend data:", result.error);
    toast.add({
      severity: "error",
      summary: "Eroare la încărcarea datelor",
      detail: result.error || "Nu s-au putut încărca datele de trend",
      life: 4000,
    });
  }
};

// Export Trend Data to Excel
const exportTrendExcel = () => {
  const data = prepareTrendData(
    dashboardStore.trends,
    selectedPeriod.value,
    selectedChartType.value,
  );
  const result = exportToExcel(data, "date_trend", "Date Trend");

  if (result.success) {
    toast.add({
      severity: "success",
      summary: "Export Reușit",
      detail: "Fișier Excel generat cu succes",
      life: 3000,
    });
  } else {
    toast.add({
      severity: "error",
      summary: "Eroare Export",
      detail: "Nu s-a putut genera fișierul Excel",
      life: 3000,
    });
  }
};

// Export Trend Data to PDF
const exportTrendPDF = () => {
  const data = prepareTrendData(
    dashboardStore.trends,
    selectedPeriod.value,
    selectedChartType.value,
  );

  if (!data || data.length === 0) {
    toast.add({
      severity: "warn",
      summary: "Nu există date",
      detail: "Nu există date de trend pentru export",
      life: 3000,
    });
    return;
  }

  // Generate columns based on data
  const columns = Object.keys(data[0]).map((key) => ({
    field: key,
    header: key,
    type: key === "Perioada" ? "text" : "currency",
  }));

  const result = exportToPDF(
    data,
    columns,
    "date_trend",
    `Date Trend (${selectedPeriod.value}) - ${companyStore.selectedCompany?.name || "ROA Reports"}`,
  );

  if (result.success) {
    toast.add({
      severity: "success",
      summary: "Export Reușit",
      detail: "Fișier PDF generat cu succes",
      life: 3000,
    });
  }
};

const refreshTrendData = async () => {
  await loadTrendData();
  toast.add({
    severity: "success",
    summary: "Actualizat",
    detail: "Datele de trend au fost actualizate",
    life: 2000,
  });
};

const getLastTrendValue = (datasetLabel) => {
  if (!dashboardStore.trends?.datasets) {
    console.warn("No trends data available for", datasetLabel);
    return 0;
  }

  const dataset = dashboardStore.trends.datasets.find(
    (d) => d.label === datasetLabel,
  );
  if (!dataset?.data?.length) {
    console.warn("No dataset or data found for", datasetLabel);
    return 0;
  }

  const lastValue = dataset.data[dataset.data.length - 1];
  return typeof lastValue === "number" ? lastValue : 0;
};

const getTrendChange = (datasetLabel) => {
  if (!dashboardStore.trends?.datasets) {
    console.warn("No trends data available for trend change calculation");
    return "0%";
  }

  const dataset = dashboardStore.trends.datasets.find(
    (d) => d.label === datasetLabel,
  );
  if (!dataset?.data?.length || dataset.data.length < 2) {
    console.warn(
      "Insufficient data points for trend change calculation:",
      datasetLabel,
    );
    return "0%";
  }

  const current = Number(dataset.data[dataset.data.length - 1]) || 0;
  const previous = Number(dataset.data[dataset.data.length - 2]) || 0;

  // Handle edge cases
  if (previous === 0 && current === 0) return "0%";
  if (previous === 0) return current > 0 ? "+∞%" : "-∞%";

  const change = ((current - previous) / Math.abs(previous)) * 100;

  // Handle very large changes
  if (!isFinite(change)) return "0%";

  const sign = change > 0 ? "+" : "";
  return `${sign}${change.toFixed(1)}%`;
};

const getTrendChangeClass = (datasetLabel) => {
  const changeStr = getTrendChange(datasetLabel);

  // Handle infinite cases
  if (changeStr.includes("∞")) return "neutral";

  const change = parseFloat(changeStr.replace("%", ""));

  // Handle NaN cases
  if (isNaN(change)) return "neutral";

  // For suppliers, negative change is good (less debt)
  if (datasetLabel === "Furnizori - Sold Net") {
    if (Math.abs(change) < 0.1) return "neutral"; // Very small changes
    if (change > 0) return "negative"; // More debt = bad
    if (change < 0) return "positive"; // Less debt = good
    return "neutral";
  }

  // For clients and treasury, positive change is good
  if (Math.abs(change) < 0.1) return "neutral"; // Very small changes
  if (change > 0) return "positive";
  if (change < 0) return "negative";
  return "neutral";
};

const searchCompanies = (event) => {
  // Handle undefined or null query
  const query = (event?.query || "").toLowerCase();

  // Ensure companyListFormatted exists and has valid data
  if (
    !companyStore.companyListFormatted ||
    companyStore.companyListFormatted.length === 0
  ) {
    filteredCompanies.value = [];
    return;
  }

  filteredCompanies.value = companyStore.companyListFormatted.filter(
    (company) => {
      // Ensure displayName exists before using includes
      const displayName = company?.displayName || "";
      return displayName.toLowerCase().includes(query);
    },
  );
};

const handleCompanySelect = async (event) => {
  const selectedCompany = event.value;
  if (selectedCompany && selectedCompany.id_firma) {
    const company = companyStore.getCompanyById(selectedCompany.id_firma);
    if (company) {
      companyStore.setSelectedCompany(company);
      await loadDashboardData();
    }
  }
};

// Fixed: Changed company_id to company parameter
// Updated: Added luna/an from period selector + cache info
const loadMonthlyFlows = async () => {
  if (!companyStore.selectedCompany) return;

  try {
    const params = { company: companyStore.selectedCompany.id_firma };
    if (periodStore.selectedPeriod) {
      params.luna = periodStore.selectedPeriod.luna;
      params.an = periodStore.selectedPeriod.an;
    }

    const data = await getWithCacheInfo("/dashboard/monthly-flows", { params });
    monthlyInflows.value = data.inflows || 0;
    monthlyOutflows.value = data.outflows || 0;

    // Extract cache metadata
    cashflowCacheInfo.value = {
      hit: data.cache_hit || false,
      time: data.response_time_ms || 0,
      source: data.cache_source || null,
    };
  } catch (error) {
    console.error("Failed to load monthly flows:", error);
  }
};

const loadTreasuryBreakdown = async () => {
  if (!companyStore.selectedCompany) return;

  try {
    const params = { company: companyStore.selectedCompany.id_firma };
    if (periodStore.selectedPeriod) {
      params.luna = periodStore.selectedPeriod.luna;
      params.an = periodStore.selectedPeriod.an;
    }

    const data = await getWithCacheInfo("/dashboard/treasury-breakdown", { params });
    treasuryData.value = data;

    // Extract cache metadata
    treasuryCacheInfo.value = {
      hit: data.cache_hit || false,
      time: data.response_time_ms || 0,
      source: data.cache_source || null,
    };
  } catch (error) {
    console.error("Failed to load treasury breakdown:", error);
  }
};

const loadNetBalanceBreakdown = async () => {
  if (!companyStore.selectedCompany) return;

  try {
    const params = { company: companyStore.selectedCompany.id_firma };
    if (periodStore.selectedPeriod) {
      params.luna = periodStore.selectedPeriod.luna;
      params.an = periodStore.selectedPeriod.an;
    }

    const data = await getWithCacheInfo("/dashboard/net-balance-breakdown", { params });

    // Folosește direct datele structurate de la backend
    netBalanceData.value = {
      clienti_total: data.clienti_total || 0,
      furnizori_total: data.furnizori_total || 0,
      breakdown: data.breakdown || {
        clienti: {
          total: 0,
          in_termen: { total: 0 },
          restant: { total: 0, perioade: {} },
        },
        furnizori: {
          total: 0,
          in_termen: { total: 0 },
          restant: { total: 0, perioade: {} },
        },
      },
    };

    // Extract cache metadata
    netBalanceCacheInfo.value = {
      hit: data.cache_hit || false,
      time: data.response_time_ms || 0,
      source: data.cache_source || null,
    };

    console.log("[NetBalance] Loaded balance data:", {
      clienti_total: netBalanceData.value.clienti_total,
      furnizori_total: netBalanceData.value.furnizori_total,
      breakdown: netBalanceData.value.breakdown,
    });
  } catch (error) {
    console.error("Failed to load net balance breakdown:", error);
  }
};

const loadDashboardData = async () => {
  if (!companyStore.selectedCompany) return;

  // FIX: Guard against null period - don't load dashboard without valid period
  // This prevents API calls with luna=null, an=null which cause backend errors
  if (!periodStore.selectedPeriod?.luna || !periodStore.selectedPeriod?.an) {
    console.log('[DashboardView] Skipping load - no valid period selected, luna:', periodStore.selectedPeriod?.luna, 'an:', periodStore.selectedPeriod?.an)
    return;
  }

  isLoading.value = true;

  // FIX: Reset state înainte de a încărca date noi
  // Previne afișarea datelor de la firma anterioară în timpul încărcării
  treasuryData.value = null;
  netBalanceData.value = null;
  monthlyInflows.value = 0;
  monthlyOutflows.value = 0;

  // Reset cache info
  treasuryCacheInfo.value = { hit: false, time: 0, source: null };
  netBalanceCacheInfo.value = { hit: false, time: 0, source: null };
  cashflowCacheInfo.value = { hit: false, time: 0, source: null };

  // Reset dashboard store financial indicators (afișează loading state imediat)
  dashboardStore.financialIndicators.loading = true;
  dashboardStore.financialIndicators.error = null;
  dashboardStore.financialIndicators.data = null;
  dashboardStore.financialIndicators.cacheInfo = { hit: false, time: 0, source: null };

  const luna = periodStore.selectedPeriod?.luna || null;
  const an = periodStore.selectedPeriod?.an || null;

  // Pentru indicatori financiari folosim luna anterioară (luna curentă e în lucru)
  const prevPeriod = previousPeriodForIndicators.value;
  const indicatorLuna = prevPeriod?.luna || null;
  const indicatorAn = prevPeriod?.an || null;

  try {
    // Fire financial indicators independently - it has its own loading state
    // and should not block the main dashboard cards from appearing
    dashboardStore.loadFinancialIndicators(
      companyStore.selectedCompany.id_firma,
      indicatorLuna,
      indicatorAn,
    );

    await Promise.all([
      dashboardStore.loadDashboardSummary(
        companyStore.selectedCompany.id_firma,
        luna,
        an,
      ),
      dashboardStore.loadCurrentPeriod(companyStore.selectedCompany.id_firma),
      loadTrendData(),
      loadMonthlyFlows(),
      loadTreasuryBreakdown(),
      loadNetBalanceBreakdown(),
    ]);
  } catch (error) {
    console.error("Failed to load dashboard data:", error);
    toast.add({
      severity: "error",
      summary: "Error",
      detail: "Nu s-au putut încărca datele dashboard-ului",
      life: 3000,
    });
  } finally {
    isLoading.value = false;
  }
};

const refreshData = async () => {
  await loadDashboardData();
  // Toast notification removed - it was covering the company and user selectors
};

const exportData = () => {
  // Export functionality can be implemented for different sections
  console.log("Export data triggered");
};

const searchData = () => {
  // Focus on the detail filter input
  const filterInput = document.querySelector(".detail-input");
  if (filterInput) {
    filterInput.focus();
  }
};

// Watch for company changes - reload dashboard when company changes
watch(
  () => companyStore.selectedCompany,
  async (newCompany) => {
    if (newCompany) {
      await loadDashboardData();
    }
  },
);

// Watch for period selector changes - reload dashboard when period changes
watch(
  () => periodStore.selectedPeriod,
  async (newPeriod, oldPeriod) => {
    // Only reload if period actually changed and we have a company selected
    if (companyStore.selectedCompany && newPeriod &&
        (newPeriod.luna !== oldPeriod?.luna || newPeriod.an !== oldPeriod?.an)) {
      console.log("Period changed, reloading dashboard:", newPeriod);
      await loadDashboardData();
    }
  },
  { deep: true }
);

// Lifecycle
onMounted(async () => {
  // Add resize listener for mobile detection
  window.addEventListener('resize', handleResize);

  // Load companies first
  if (!companyStore.hasCompanies) {
    await companyStore.loadCompanies();
  }

  filteredCompanies.value = companyStore.companyListFormatted;

  // Check for saved company and verify it exists in loaded companies
  if (companyStore.selectedCompany) {
    const exists = companyStore.getCompanyById(
      companyStore.selectedCompany.id_firma,
    );
    if (exists) {
      // Update with fresh company data from API
      companyStore.setSelectedCompany(exists);
      await loadDashboardData();
    } else {
      // Saved company no longer exists, clear it
      companyStore.clearSelectedCompany();
    }
  }
});

// Cleanup resize listener
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
/* Dashboard Styles - Using Global Patterns */

/* Mobile Layout - Padding for fixed top/bottom bars */
.main-content.mobile-layout {
  padding-top: 56px;  /* MobileTopBar height */
  padding-bottom: 56px; /* MobileBottomNav height */
}

/* US-2008: Refresh Button Styles */
.refresh-btn {
  color: var(--color-text-secondary);
  transition: color var(--transition-fast), transform var(--transition-fast);
}

.refresh-btn:hover {
  color: var(--color-primary);
}

/* US-2008: Rotating animation during loading */
.refresh-btn.is-loading .pi-refresh {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* Company Selection */
.company-selection {
  max-width: 500px;
  margin: 0 auto var(--space-xl) auto;
}

.company-input {
  width: 100%;
}

.no-companies {
  text-align: center;
  color: var(--color-text-secondary);
  font-style: italic;
}

/* Dashboard Sections */
.dashboard-section {
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--card-radius);
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-lg) var(--space-xl);
  background: var(--color-bg-secondary);
  border-bottom: 1px solid var(--color-border);
  flex-wrap: wrap;
  gap: var(--space-md);
}

.section-title {
  font-size: var(--text-xl);
  font-weight: var(--font-semibold);
  color: var(--color-text);
  margin: 0;
}

.section-controls {
  display: flex;
  align-items: center;
  gap: var(--space-md);
  flex-wrap: wrap;
}

.control-group {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
}

.control-group label {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--color-text-secondary);
  white-space: nowrap;
}

.detail-select,
.detail-input,
.trend-select {
  padding: var(--space-xs) var(--space-sm);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  min-width: 120px;
}

.detail-select:focus,
.detail-input:focus,
.trend-select:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px rgba(var(--color-primary-rgb), 0.2);
}

/* Tables - All table styles removed (tables are in card components) */

/* Trends Section */
.trends-container {
  padding: var(--space-xl);
}

.trend-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-xl);
  color: var(--color-text-secondary);
  text-align: center;
}

.trend-error {
  text-align: center;
  padding: var(--space-xl);
  background: var(--color-bg-secondary);
  border-radius: var(--radius-lg);
  color: var(--color-text-secondary);
}

.error-icon {
  font-size: 48px;
  color: var(--color-warning);
  margin-bottom: var(--space-lg);
}

.trend-error h3 {
  font-size: var(--text-xl);
  font-weight: var(--font-semibold);
  color: var(--color-text);
  margin: 0 0 var(--space-md) 0;
}

.trend-error p {
  font-size: var(--text-base);
  margin: 0 0 var(--space-lg) 0;
  line-height: 1.6;
}

.trend-chart-wrapper {
  display: flex;
  flex-direction: column;
  gap: var(--space-lg);
}

.trend-chart-component {
  height: 300px;
  background: var(--color-bg);
  border-radius: var(--radius-lg);
  padding: var(--space-md);
}

.trend-summary {
  background: var(--color-bg-secondary);
  border-radius: var(--radius-lg);
  padding: var(--space-lg);
}

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

.stat-item {
  display: flex;
  flex-direction: column;
  gap: var(--space-xs);
  padding: var(--space-md);
  background: var(--color-bg);
  border-radius: var(--radius-md);
  text-align: center;
}

.stat-label {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--color-text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-value {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  font-family: var(--font-mono, monospace);
}

.stat-item.positive .stat-value {
  color: var(--color-success);
}

.stat-item.negative .stat-value {
  color: var(--color-error);
}

.stat-item.neutral .stat-value {
  color: var(--color-text);
}

.stat-change {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  padding: var(--space-xs) var(--space-sm);
  border-radius: var(--radius-full);
}

.stat-change.positive {
  background: var(--color-success-bg);
  color: var(--color-success);
}

.stat-change.negative {
  background: var(--color-error-bg);
  color: var(--color-error);
}

.stat-change.neutral {
  background: var(--color-bg-muted);
  color: var(--color-text-secondary);
}

/* Loading Bar - non-blocking, subtle indicator at top of content */
.loading-bar-container {
  height: 3px;
  background: var(--surface-border);
  border-radius: var(--radius-full);
  overflow: hidden;
  margin-bottom: var(--space-md);
}

.loading-bar {
  height: 100%;
  background: var(--color-primary);
  animation: loading-progress 1.5s ease-in-out infinite;
  border-radius: var(--radius-full);
}

@keyframes loading-progress {
  0% { width: 0%; transform: translateX(0%); }
  50% { width: 60%; transform: translateX(60%); }
  100% { width: 30%; transform: translateX(300%); }
}

/* Responsive Design - Consolidated (Component-specific only) */
@media (max-width: 768px) {
  /* Trend section adjustments */
  .trends-container {
    padding: var(--space-lg);
  }

  .trend-chart-component {
    height: 250px;
  }

  .trend-stats {
    grid-template-columns: 1fr;
    gap: var(--space-md);
  }

  .stat-item {
    padding: var(--space-sm);
  }

  .error-icon {
    font-size: 36px;
  }

  .trend-error h3 {
    font-size: var(--text-lg);
  }
}

/* Compact Layout Styles - Removed (tables are in card components) */

/* Print Styles - Simplified (card components handle their own print styles) */
@media print {
  @page {
    margin: 0.5in;
    size: A4;
  }

  * {
    -webkit-print-color-adjust: exact;
    print-color-adjust: exact;
  }

  .trends-container,
  .loading-state,
  .no-print {
    display: none !important;
  }
}

/* Mobile Table Styles - Removed (tables are in card components) */

/* Secțiune Carduri Noi */
.metrics-cards-section {
  margin-bottom: 2rem;
  padding: 0 var(--space-md);
}

/* Metrics Cards Layout - Component-specific grid layouts */
.metrics-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--space-md);
  margin-bottom: var(--space-lg);
}

.analysis-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--space-md);
  margin-bottom: var(--space-lg);
}

/* US-014: Financial Indicators Section - Desktop Only */


/* Mobile Budget Card wrapper (card-6 in SwipeableCards) */
.mobile-budget-card {
  background: var(--surface-card);
  border-radius: var(--radius-md);
  border: 1px solid var(--surface-border);
  overflow: hidden;
}

.mobile-budget-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-sm) var(--space-md);
  border-bottom: 1px solid var(--surface-border);
}

.mobile-budget-card-title {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  color: var(--text-color-secondary);
  text-transform: uppercase;
  letter-spacing: 0.04em;
}

.mobile-budget-card-value {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  color: var(--text-color);
}

.mobile-budget-card-value.positive { color: var(--green-600); }
.mobile-budget-card-value.negative { color: var(--red-600); }

/* Budget Debt Breakdown in Desktop CollapsibleCard */
.budget-debt-breakdown-desktop {
  display: flex;
  flex-direction: column;
  padding: var(--space-md);
}

.budget-debt-breakdown-header {
  display: grid;
  grid-template-columns: 1fr auto auto auto;
  gap: var(--space-md);
  padding: var(--space-xs) 0 var(--space-sm) 0;
  border-bottom: 1px solid var(--surface-border);
  margin-bottom: var(--space-xs);
}

.budget-debt-breakdown-row {
  display: grid;
  grid-template-columns: 1fr auto auto auto;
  gap: var(--space-md);
  padding: var(--space-xs) 0;
  align-items: center;
}

.budget-debt-col-label {
  font-size: var(--text-sm);
  color: var(--color-text-secondary);
  font-weight: var(--font-medium);
}

.budget-debt-breakdown-header .budget-debt-col-label {
  font-size: var(--text-xs);
  font-weight: var(--font-semibold);
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.budget-debt-col-value {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  font-family: var(--font-mono, monospace);
  color: var(--color-text);
  white-space: nowrap;
  min-width: 100px;
  text-align: right;
}

.budget-debt-col-header-value {
  font-size: var(--text-xs);
  font-weight: var(--font-semibold);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--color-text-secondary);
  white-space: nowrap;
  min-width: 100px;
  text-align: right;
}

/* Coloana "Achitat" - verde pentru plăți efectuate */
.budget-debt-paid {
  color: var(--green-600);
}

[data-theme="dark"] .budget-debt-paid {
  color: var(--green-400);
}

/* Coloana "Sold" când e 0 (datoria achitată integral) */
.budget-debt-cleared {
  color: var(--green-600);
  font-weight: var(--font-bold);
}

[data-theme="dark"] .budget-debt-cleared {
  color: var(--green-400);
}

.budget-debt-breakdown-empty {
  padding: var(--space-sm) 0;
  color: var(--color-text-secondary);
  font-style: italic;
  font-size: var(--text-sm);
}

/* Grup row - clickabil, bold */
.budget-debt-group-row {
  cursor: pointer;
  font-weight: var(--font-semibold);
  background: var(--surface-ground);
  border-radius: var(--radius-sm);
}
.budget-debt-group-row:hover { background: var(--surface-hover); }

.budget-debt-group-label {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
}

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

/* Sub-conturi indentate */
.budget-debt-sub-accounts {
  background: var(--surface-card);
  border-left: 2px solid var(--surface-border);
  margin-left: var(--space-sm);
}

.budget-debt-subrow { opacity: 0.85; }
.budget-debt-sub-label { padding-left: var(--space-md); font-size: var(--text-xs); }
.budget-debt-sub-value { font-size: var(--text-xs); }

/* Mobile: reduce columns (hide Achitat, shrink values) */
@media (max-width: 768px) {
  .budget-debt-breakdown-header,
  .budget-debt-breakdown-row {
    grid-template-columns: 1fr auto auto;
    gap: var(--space-sm);
  }

  .budget-debt-col-achitat {
    display: none;
  }

  .budget-debt-col-value {
    min-width: 72px;
  }

  .budget-debt-breakdown-desktop {
    padding: var(--space-sm);
  }
}

/* Separator între precedent și curent */
.budget-debt-section-divider {
  height: 1px;
  background: var(--surface-border);
  margin: var(--space-sm) 0;
}

/* Obligații curente - compact, o singură linie */
.budget-debt-curent-summary {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: var(--space-sm);
  padding: var(--space-xs) 0;
}

.budget-debt-curent-title {
  font-size: var(--text-xs);
  font-weight: var(--font-semibold);
  color: var(--text-color-secondary);
  text-transform: uppercase;
  letter-spacing: 0.04em;
}

.budget-debt-curent-chip {
  font-size: var(--text-sm);
  font-weight: var(--font-semibold);
  font-family: var(--font-mono, monospace);
  color: var(--text-color-secondary);
}

.budget-debt-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 - All breakpoints consolidated */
@media (max-width: 1200px) {
  .metrics-row {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 1024px) {
  .analysis-row {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .metrics-cards-section {
    padding: 0 0.25rem;
  }
}

@media (max-width: 480px) {
  .metrics-cards-section {
    padding: 0;
    margin-bottom: 1rem;
  }
}

/* Mobile KPI Carousel Styles */
.mobile-kpi-carousel {
  margin-bottom: var(--space-lg);
}

/* Eliminare culori semantice în contextul caruselului mobil */
/* Clase globale utility (colors.css): text-success/error/primary/danger */
.mobile-kpi-carousel :deep(.text-success),
.mobile-kpi-carousel :deep(.text-error),
.mobile-kpi-carousel :deep(.text-primary),
.mobile-kpi-carousel :deep(.text-danger) {
  color: var(--text-color) !important;
}

/* Clase positive/negative pe header-total (Clienti/FurnizoriBalanceCard) */
.mobile-kpi-carousel :deep(.header-total.positive),
.mobile-kpi-carousel :deep(.header-total.negative),
.mobile-kpi-carousel :deep(.positive),
.mobile-kpi-carousel :deep(.negative) {
  color: var(--text-color) !important;
}

/* Clase value--success/danger (SolduriCompactCard) */
.mobile-kpi-carousel :deep(.solduri-compact-card__value--success),
.mobile-kpi-carousel :deep(.solduri-compact-card__value--danger) {
  color: var(--text-color) !important;
}

/* Trend colors - neutralizate */
.mobile-kpi-carousel :deep(.trend-up),
.mobile-kpi-carousel :deep(.trend-down) {
  color: var(--text-color-secondary) !important;
}

/* Eliminare chenar exterior pe cardurile din carusel (paginile 2+)
   pentru a avea același stil ca pagina 1 (solduri grid fără chenar) */
.mobile-kpi-carousel :deep(.metric-card) {
  border: none;
  background: transparent;
  box-shadow: none;
}

/* FinancialIndicatorsCard now has its own card styling - do NOT strip it */

.mobile-kpi-carousel .mobile-budget-card {
  border: none;
  background: transparent;
  box-shadow: none;
}

/* Uniformizare dimensiuni fonturi în cardurile din carusel */
@media (max-width: 768px) {
  /* Valorile principale din toate tipurile de carduri */
  .mobile-kpi-carousel :deep(.metric-value),
  .mobile-kpi-carousel :deep(.treasury-value),
  .mobile-kpi-carousel :deep(.header-total),
  .mobile-kpi-carousel :deep(.solduri-compact-card__value) {
    font-size: 1.5rem !important;
    line-height: 1.2;
  }

  /* Label-uri card */
  .mobile-kpi-carousel :deep(.metric-label),
  .mobile-kpi-carousel :deep(.treasury-label),
  .mobile-kpi-carousel :deep(.header-label) {
    font-size: var(--text-xs) !important;
  }
}

/* US-2002: Solduri list for mobile first page - 1 card per row */
.solduri-grid-2x2 {
  display: flex;
  flex-direction: column;
  gap: var(--space-sm);
  padding: var(--space-xs);
}

/* Touch target compliance - SolduriCompactCard handles its own min-height */
.solduri-grid-2x2 > * {
  /* Height auto - only as tall as content needs */
}

</style>
