<template>
  <div class="app-container" :class="{ 'mobile-layout': isMobile }">
    <!-- US-108: Mobile Material Design Top Bar -->
    <MobileTopBar
      v-if="isMobile"
      title="Balanță de Verificare"
      :show-menu="true"
      :actions="mobileTopBarActions"
      @menu-click="toggleMobileMenu"
      @action-click="handleTopBarAction"
    />

    <!-- US-108: Mobile Hamburger Menu -->
    <Sidebar v-model:visible="mobileMenuVisible" position="left" class="mobile-sidebar">
      <template #header>
        <div class="sidebar-header">
          <span class="sidebar-title">ROA2WEB</span>
        </div>
      </template>
      <div class="sidebar-menu">
        <router-link to="/data-entry" class="sidebar-item">
          <i class="pi pi-receipt"></i>
          <span>Bonuri</span>
        </router-link>
        <router-link to="/reports/trial-balance" class="sidebar-item active">
          <i class="pi pi-calculator"></i>
          <span>Balanță</span>
        </router-link>
        <router-link to="/reports/dashboard" class="sidebar-item">
          <i class="pi pi-chart-bar"></i>
          <span>Rapoarte</span>
        </router-link>
        <router-link to="/data-entry/ocr-metrics" class="sidebar-item">
          <i class="pi pi-cog"></i>
          <span>Setări</span>
        </router-link>
      </div>
    </Sidebar>

    <!-- US-108: Filter BottomSheet for mobile -->
    <BottomSheet v-model="showFilters">
      <h3 class="bottom-sheet-title">Filtre</h3>
      <div class="bottom-sheet-filters">
        <!-- Cont Filter -->
        <div class="form-group">
          <label class="form-label">Număr Cont</label>
          <InputText
            v-model="localFilters.cont"
            placeholder="Ex: 512, 4111"
            class="w-full"
            @input="handleFilterChange"
          />
        </div>

        <!-- Denumire Filter -->
        <div class="form-group">
          <label class="form-label">Denumire Cont</label>
          <InputText
            v-model="localFilters.denumire"
            placeholder="Căutare după denumire..."
            class="w-full"
            @input="handleSearchChange"
          />
        </div>

        <!-- Bottom sheet actions -->
        <div class="bottom-sheet-actions">
          <Button
            icon="pi pi-filter-slash"
            label="Resetează"
            class="p-button-outlined p-button-secondary"
            @click="clearFilters(); showFilters = false"
          />
          <Button
            icon="pi pi-check"
            label="Aplică"
            @click="showFilters = false"
          />
        </div>
      </div>
    </BottomSheet>

    <div class="trial-balance">
      <!-- Page Header - Desktop only -->
      <div class="page-header" v-if="!isMobile">
        <h1 class="page-title">
          <i class="pi pi-calculator"></i>
          Balanță de Verificare
        </h1>
      </div>

      <!-- Company Selection -->
      <Card v-if="!companyStore.selectedCompany" class="company-selection-card">
        <template #content>
          <div class="company-selection">
            <p class="text-color-secondary mb-3">
              Selectați o companie pentru a vizualiza balanța de verificare:
            </p>
            <Dropdown
              v-model="selectedCompanyId"
              :options="companyStore.companyListFormatted"
              option-label="displayName"
              option-value="id_firma"
              placeholder="Alegeți compania"
              class="w-full"
              @change="handleCompanyChange"
            />
          </div>
        </template>
      </Card>

      <!-- US-108: Mobile Totals Bar -->
      <div v-if="isMobile && companyStore.selectedCompany && trialBalanceStore.hasData" class="mobile-totals-bar">
        <div class="mobile-totals-content">
          <div class="mobile-totals-grid two-totals">
            <div class="total-item">
              <span class="total-label">Sold D:</span>
              <span class="total-value">{{ formatCompact(trialBalanceStore.totals.total_sold_final_debit) }}</span>
            </div>
            <div class="total-item">
              <span class="total-label">Sold C:</span>
              <span class="total-value">{{ formatCompact(trialBalanceStore.totals.total_sold_final_credit) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Filters Section - Desktop only (mobile uses BottomSheet) -->
      <Card v-if="companyStore.selectedCompany && !isMobile" class="filters-card">
        <template #content>
          <div class="form">
            <div class="form-row">
              <!-- Cont Filter -->
              <div class="form-col">
                <div class="form-group">
                  <label class="form-label">Număr Cont</label>
                  <InputText
                    v-model="localFilters.cont"
                    placeholder="Ex: 512, 4111"
                    class="w-full"
                    @input="handleFilterChange"
                  />
                </div>
              </div>

              <!-- Denumire Filter -->
              <div class="form-col search-col">
                <div class="form-group">
                  <label class="form-label">Denumire Cont</label>
                  <InputText
                    v-model="localFilters.denumire"
                    placeholder="Căutare după denumire..."
                    class="w-full"
                    @input="handleSearchChange"
                  />
                </div>
              </div>
            </div>

            <!-- Desktop: Action buttons -->
            <div v-if="!isMobile" class="form-actions">
              <Button
                icon="pi pi-filter-slash"
                label="Resetează Filtre"
                class="p-button-outlined p-button-secondary"
                @click="clearFilters"
              />
              <Button
                icon="pi pi-file-excel"
                label="Export Excel"
                class="p-button-outlined p-button-success"
                @click="exportExcel"
                :disabled="!trialBalanceStore.hasData"
              />
              <Button
                icon="pi pi-file-pdf"
                label="Export PDF"
                class="p-button-outlined p-button-danger"
                @click="exportPDF"
                :disabled="!trialBalanceStore.hasData"
              />
              <Button
                icon="pi pi-refresh"
                label="Actualizează"
                :loading="trialBalanceStore.isLoading"
                @click="refreshData"
              />
            </div>
          </div>
        </template>
      </Card>

      <!-- Summary Totals - Uses shared stats.css (hidden on mobile - compact in toolbar) -->
      <!-- Totaluri din TOATE înregistrările filtrate (nu doar pagina curentă) -->
      <div v-if="!isMobile && companyStore.selectedCompany && trialBalanceStore.hasData" class="summary-stats-inline">
        <div class="stat-item">
          <span class="stat-label">Sume Prec. D:</span>
          <span class="stat-value">{{ formatCurrency(trialBalanceStore.totals.total_sold_precedent_debit) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">Sume Prec. C:</span>
          <span class="stat-value">{{ formatCurrency(trialBalanceStore.totals.total_sold_precedent_credit) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">Rulaj D:</span>
          <span class="stat-value">{{ formatCurrency(trialBalanceStore.totals.total_rulaj_lunar_debit) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">Rulaj C:</span>
          <span class="stat-value">{{ formatCurrency(trialBalanceStore.totals.total_rulaj_lunar_credit) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">Sold Final D:</span>
          <span class="stat-value">{{ formatCurrency(trialBalanceStore.totals.total_sold_final_debit) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">Sold Final C:</span>
          <span class="stat-value">{{ formatCurrency(trialBalanceStore.totals.total_sold_final_credit) }}</span>
        </div>
      </div>

      <!-- Trial Balance Table -->
      <Card v-if="companyStore.selectedCompany" class="table-card">
        <template #content>
          <!-- Mobile: Card Layout -->
          <div v-if="isMobile" class="mobile-card-list">
            <div
              v-for="account in trialBalanceStore.trialBalanceData.filter(a => a.sold_final_debit > 0 || a.sold_final_credit > 0)"
              :key="account.cont"
              class="mobile-data-card"
            >
              <div class="card-header">
                <strong>{{ account.cont }}</strong>&nbsp;&nbsp;{{ truncate(account.denumire, 30) }}
              </div>
              <div class="card-row">
                <span></span>
                <span class="card-amount">
                  {{ account.sold_final_debit > 0
                     ? formatCurrency(account.sold_final_debit) + ' D'
                     : formatCurrency(account.sold_final_credit) + ' C' }}
                </span>
              </div>
            </div>
            <div v-if="trialBalanceStore.trialBalanceData.filter(a => a.sold_final_debit > 0 || a.sold_final_credit > 0).length === 0" class="mobile-empty">
              <i class="pi pi-info-circle"></i>
              <p>Nu au fost găsite date</p>
            </div>
          </div>

          <!-- Desktop: DataTable -->
          <DataTable
            v-if="!isMobile"
            :value="trialBalanceStore.trialBalanceData"
            :loading="trialBalanceStore.isLoading"
            :paginator="true"
            :rows="trialBalanceStore.pagination.pageSize"
            :total-records="trialBalanceStore.pagination.totalItems"
            :lazy="true"
            :striped-rows="true"
            paginator-template="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
            :rows-per-page-options="[25, 50, 100]"
            current-page-report-template="Afișare {first} - {last} din {totalRecords} înregistrări"
            responsive-layout="scroll"
            @page="onPageChange"
            @sort="onSort"
          >
            <template #empty>
              <div class="table-empty">
                <i class="pi pi-info-circle table-empty-icon"></i>
                <p class="table-empty-message">
                  Nu au fost găsite date pentru perioada selectată
                </p>
              </div>
            </template>

            <template #loading>
              <div class="loading-state">
                <ProgressSpinner />
                <p>Se încarcă balanța de verificare...</p>
              </div>
            </template>

            <Column
              field="cont"
              header="Cont"
              sortable
              :style="{ width: '8%' }"
            >
              <template #body="slotProps">
                <strong>{{ slotProps.data.cont }}</strong>
              </template>
            </Column>

            <Column
              field="denumire"
              header="Denumire Cont"
              sortable
              :style="{ width: '20%' }"
            />

            <Column
              field="sold_precedent_debit"
              header="Sume Prec. D"
              sortable
              :style="{ width: '10%' }"
            >
              <template #body="slotProps">
                <div class="text-right">
                  {{ formatCurrency(slotProps.data.sold_precedent_debit) }}
                </div>
              </template>
            </Column>

            <Column
              field="sold_precedent_credit"
              header="Sume Prec. C"
              sortable
              :style="{ width: '10%' }"
            >
              <template #body="slotProps">
                <div class="text-right">
                  {{ formatCurrency(slotProps.data.sold_precedent_credit) }}
                </div>
              </template>
            </Column>

            <Column
              field="rulaj_lunar_debit"
              header="Rulaj D"
              sortable
              :style="{ width: '10%' }"
            >
              <template #body="slotProps">
                <div class="text-right">
                  {{ formatCurrency(slotProps.data.rulaj_lunar_debit) }}
                </div>
              </template>
            </Column>

            <Column
              field="rulaj_lunar_credit"
              header="Rulaj C"
              sortable
              :style="{ width: '10%' }"
            >
              <template #body="slotProps">
                <div class="text-right">
                  {{ formatCurrency(slotProps.data.rulaj_lunar_credit) }}
                </div>
              </template>
            </Column>

            <Column
              field="sold_final_debit"
              header="Sold Final D"
              sortable
              :style="{ width: '11%' }"
            >
              <template #body="slotProps">
                <div class="text-right">
                  {{ formatCurrency(slotProps.data.sold_final_debit) }}
                </div>
              </template>
            </Column>

            <Column
              field="sold_final_credit"
              header="Sold Final C"
              sortable
              :style="{ width: '11%' }"
            >
              <template #body="slotProps">
                <div class="text-right">
                  {{ formatCurrency(slotProps.data.sold_final_credit) }}
                </div>
              </template>
            </Column>
          </DataTable>
        </template>
      </Card>
    </div>

    <!-- US-108: Mobile Bottom Navigation -->
    <MobileBottomNav
      v-if="isMobile"
      :items="mobileBottomNavItems"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useToast } from "primevue/usetoast";
import { useCompanyStore } from "@reports/stores/sharedStores";
import { useTrialBalanceStore } from "@reports/stores/trialBalance";
import { useAccountingPeriodStore } from "@reports/stores/sharedStores";
import { exportToExcel, exportToPDF } from "@reports/utils/exportUtils";

// US-108: Mobile Material Design components
import MobileTopBar from "@shared/components/mobile/MobileTopBar.vue";
import MobileBottomNav from "@shared/components/mobile/MobileBottomNav.vue";
import BottomSheet from "@shared/components/mobile/BottomSheet.vue";
import Sidebar from "primevue/sidebar";

const toast = useToast();
const companyStore = useCompanyStore();
const trialBalanceStore = useTrialBalanceStore();
const periodStore = useAccountingPeriodStore();

// State
const selectedCompanyId = ref(companyStore.selectedCompany?.id_firma || null);

// Mobile state
const isMobile = ref(window.innerWidth < 768);
const showFilters = ref(false);
const mobileMenuVisible = ref(false);
const actionsMenu = ref(null);

// US-108: Toggle mobile hamburger menu
const toggleMobileMenu = () => {
  mobileMenuVisible.value = !mobileMenuVisible.value;
};

// US-108: Mobile TopBar actions (filter + export)
const mobileTopBarActions = computed(() => [
  {
    icon: "pi pi-filter",
    label: "Filtre",
    tooltip: "Filtre",
    active: hasActiveFilters.value
  },
  {
    icon: "pi pi-download",
    label: "Export",
    tooltip: "Export Excel"
  }
]);

// US-108: Handle top bar action clicks
const handleTopBarAction = (action) => {
  if (action.icon === "pi pi-filter") {
    showFilters.value = !showFilters.value;
  } else if (action.icon === "pi pi-download") {
    exportExcel();
  }
};

// US-108: Bottom nav items for MobileBottomNav component
const mobileBottomNavItems = computed(() => [
  { to: "/data-entry", icon: "pi pi-receipt", label: "Bonuri" },
  { to: "/reports/trial-balance", icon: "pi pi-calculator", label: "Balanță", active: true },
  { to: "/reports/dashboard", icon: "pi pi-chart-bar", label: "Rapoarte" },
  { to: "/data-entry/ocr-metrics", icon: "pi pi-cog", label: "Setări" }
]);

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

const localFilters = ref({
  cont: "",
  denumire: "",
});

// Computed
const currentPeriodText = computed(() => {
  // Use the global period store
  return periodStore.selectedPeriod?.display_name || "";
});

// Mobile: Check if any filter is active (non-default value)
const hasActiveFilters = computed(() => {
  return localFilters.value.cont !== "" || localFilters.value.denumire !== "";
});

// Mobile: Actions menu items
const actionMenuItems = computed(() => [
  {
    label: "Resetează Filtre",
    icon: "pi pi-filter-slash",
    command: clearFilters,
  },
  {
    label: "Export Excel",
    icon: "pi pi-file-excel",
    command: exportExcel,
    disabled: !trialBalanceStore.hasData,
  },
  {
    label: "Export PDF",
    icon: "pi pi-file-pdf",
    command: exportPDF,
    disabled: !trialBalanceStore.hasData,
  },
  { separator: true },
  {
    label: "Actualizează",
    icon: "pi pi-refresh",
    command: refreshData,
  },
]);

// Methods
const formatCurrency = (amount) => {
  if (!amount || amount === 0) return "0,00";
  return new Intl.NumberFormat("ro-RO", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(amount);
};

// Compact format for mobile totals (e.g., "449.881" instead of "449.881,12")
const formatCompact = (amount) => {
  if (!amount || amount === 0) return "0";
  const absAmount = Math.abs(amount);
  if (absAmount >= 1000000) {
    return new Intl.NumberFormat("ro-RO", {
      maximumFractionDigits: 1,
    }).format(amount / 1000000) + "M";
  }
  return new Intl.NumberFormat("ro-RO", {
    maximumFractionDigits: 0,
  }).format(amount);
};

// Truncate text for mobile cards
const truncate = (text, maxLength) => {
  if (!text || text.length <= maxLength) return text;
  return text.substring(0, maxLength) + "...";
};

const handleCompanyChange = async () => {
  if (!selectedCompanyId.value) return;

  const company = companyStore.getCompanyById(selectedCompanyId.value);
  if (company) {
    companyStore.setSelectedCompany(company);
    await loadTrialBalance();
  }
};

const handleFilterChange = async () => {
  await applyFilters();
};

const handleSearchChange = (() => {
  let timeout;
  return () => {
    clearTimeout(timeout);
    timeout = setTimeout(async () => {
      await applyFilters();
    }, 500);
  };
})();

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

  await trialBalanceStore.applyFilters(
    {
      cont: localFilters.value.cont,
      denumire: localFilters.value.denumire,
    },
    companyStore.selectedCompany.id_firma,
  );
};

const clearFilters = async () => {
  localFilters.value = {
    cont: "",
    denumire: "",
  };
  await trialBalanceStore.clearFilters(companyStore.selectedCompany.id_firma);
};

const refreshData = async () => {
  await loadTrialBalance();
  toast.add({
    severity: "success",
    summary: "Actualizare reușită",
    detail: "Balanța de verificare a fost actualizată cu succes",
    life: 3000,
  });
};

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

  try {
    await trialBalanceStore.fetchTrialBalance(
      companyStore.selectedCompany.id_firma,
    );
  } catch (error) {
    console.error("Failed to load trial balance:", error);
    toast.add({
      severity: "error",
      summary: "Eroare",
      detail: "Nu s-a putut încărca balanța de verificare",
      life: 5000,
    });
  }
};

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

  await trialBalanceStore.changePage(
    event.page + 1,
    companyStore.selectedCompany.id_firma,
  );
};

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

  const sortBy = event.sortField?.toUpperCase() || "CONT";
  const sortOrder = event.sortOrder === 1 ? "asc" : "desc";

  await trialBalanceStore.sort(
    sortBy,
    sortOrder,
    companyStore.selectedCompany.id_firma,
  );
};

// Export methods - Fetch ALL data (not just current page)
const fetchAllTrialBalanceData = async () => {
  if (!companyStore.selectedCompany) return [];

  try {
    const params = {
      company: companyStore.selectedCompany.id_firma,
      luna: trialBalanceStore.filters.luna,
      an: trialBalanceStore.filters.an,
      page: 1,
      page_size: 999999, // Get all data
      sort_by: trialBalanceStore.sorting.sortBy,
      sort_order: trialBalanceStore.sorting.sortOrder,
    };

    // Add optional filters
    if (trialBalanceStore.filters.cont) {
      params.cont_filter = trialBalanceStore.filters.cont;
    }
    if (trialBalanceStore.filters.denumire) {
      params.denumire_filter = trialBalanceStore.filters.denumire;
    }

    const apiService = (await import("../services/api")).apiService;
    const response = await api.get("/trial-balance/", { params });

    if (response.data.success) {
      return response.data.data.items || [];
    }
    return [];
  } catch (error) {
    console.error("Failed to fetch all trial balance data:", error);
    return [];
  }
};

const exportExcel = async () => {
  if (!trialBalanceStore.hasData) {
    toast.add({
      severity: "warn",
      summary: "Nu există date",
      detail: "Nu există date de exportat",
      life: 3000,
    });
    return;
  }

  // Fetch ALL data for export (not just current page)
  toast.add({
    severity: "info",
    summary: "Se pregătește exportul",
    detail: "Se încarcă toate datele...",
    life: 2000,
  });

  const allData = await fetchAllTrialBalanceData();

  if (allData.length === 0) {
    toast.add({
      severity: "error",
      summary: "Eroare",
      detail: "Nu s-au putut prelua datele pentru export",
      life: 3000,
    });
    return;
  }

  // Prepare data for export - Use raw numbers (not formatted) so Excel treats them as numbers
  const exportData = allData.map((row) => ({
    Cont: row.cont,
    Denumire: row.denumire,
    "Sume Prec. D": parseFloat(row.sold_precedent_debit) || 0,
    "Sume Prec. C": parseFloat(row.sold_precedent_credit) || 0,
    "Rulaj Lunar D": parseFloat(row.rulaj_lunar_debit) || 0,
    "Rulaj Lunar C": parseFloat(row.rulaj_lunar_credit) || 0,
    "Sold Final D": parseFloat(row.sold_final_debit) || 0,
    "Sold Final C": parseFloat(row.sold_final_credit) || 0,
  }));

  const result = exportToExcel(
    exportData,
    `balanta_verificare_${currentPeriodText.value.replace(/\s+/g, "_")}`,
    "Balanță de Verificare",
  );

  if (result.success) {
    toast.add({
      severity: "success",
      summary: "Export reușit",
      detail: `${allData.length} înregistrări exportate cu succes`,
      life: 3000,
    });
  } else {
    toast.add({
      severity: "error",
      summary: "Eroare la export",
      detail: "Nu s-a putut genera fișierul Excel",
      life: 3000,
    });
  }
};

const exportPDF = async () => {
  if (!trialBalanceStore.hasData) {
    toast.add({
      severity: "warn",
      summary: "Nu există date",
      detail: "Nu există date de exportat",
      life: 3000,
    });
    return;
  }

  // Fetch ALL data for export (not just current page)
  toast.add({
    severity: "info",
    summary: "Se pregătește exportul",
    detail: "Se încarcă toate datele...",
    life: 2000,
  });

  const allData = await fetchAllTrialBalanceData();

  if (allData.length === 0) {
    toast.add({
      severity: "error",
      summary: "Eroare",
      detail: "Nu s-au putut prelua datele pentru export",
      life: 3000,
    });
    return;
  }

  // Group data by account class (first digit) and add class totals + grand total
  const groupDataWithTotals = (data) => {
    // Sort by account number
    const sortedData = [...data].sort((a, b) =>
      String(a.cont).localeCompare(String(b.cont))
    );

    const result = [];
    const classTotals = {}; // { '1': {sume_prec_d, sume_prec_c, ...}, '2': {...}, ... }
    const grandTotal = {
      sold_precedent_debit: 0,
      sold_precedent_credit: 0,
      rulaj_lunar_debit: 0,
      rulaj_lunar_credit: 0,
      sold_final_debit: 0,
      sold_final_credit: 0,
    };

    let currentClass = null;

    sortedData.forEach((row) => {
      const accountClass = String(row.cont).charAt(0);

      // Initialize class totals if new class
      if (!classTotals[accountClass]) {
        classTotals[accountClass] = {
          sold_precedent_debit: 0,
          sold_precedent_credit: 0,
          rulaj_lunar_debit: 0,
          rulaj_lunar_credit: 0,
          sold_final_debit: 0,
          sold_final_credit: 0,
        };
      }

      // If class changed and we have a previous class, add its total row
      if (currentClass !== null && currentClass !== accountClass) {
        result.push({
          cont: "",
          denumire: `TOTAL CLASA ${currentClass}`,
          sold_precedent_debit: classTotals[currentClass].sold_precedent_debit,
          sold_precedent_credit: classTotals[currentClass].sold_precedent_credit,
          rulaj_lunar_debit: classTotals[currentClass].rulaj_lunar_debit,
          rulaj_lunar_credit: classTotals[currentClass].rulaj_lunar_credit,
          sold_final_debit: classTotals[currentClass].sold_final_debit,
          sold_final_credit: classTotals[currentClass].sold_final_credit,
          _isTotal: true,
        });
      }

      currentClass = accountClass;

      // Add the regular row
      result.push({
        cont: row.cont,
        denumire: row.denumire,
        sold_precedent_debit: row.sold_precedent_debit,
        sold_precedent_credit: row.sold_precedent_credit,
        rulaj_lunar_debit: row.rulaj_lunar_debit,
        rulaj_lunar_credit: row.rulaj_lunar_credit,
        sold_final_debit: row.sold_final_debit,
        sold_final_credit: row.sold_final_credit,
      });

      // Accumulate class totals
      classTotals[accountClass].sold_precedent_debit += parseFloat(row.sold_precedent_debit) || 0;
      classTotals[accountClass].sold_precedent_credit += parseFloat(row.sold_precedent_credit) || 0;
      classTotals[accountClass].rulaj_lunar_debit += parseFloat(row.rulaj_lunar_debit) || 0;
      classTotals[accountClass].rulaj_lunar_credit += parseFloat(row.rulaj_lunar_credit) || 0;
      classTotals[accountClass].sold_final_debit += parseFloat(row.sold_final_debit) || 0;
      classTotals[accountClass].sold_final_credit += parseFloat(row.sold_final_credit) || 0;

      // Accumulate grand total
      grandTotal.sold_precedent_debit += parseFloat(row.sold_precedent_debit) || 0;
      grandTotal.sold_precedent_credit += parseFloat(row.sold_precedent_credit) || 0;
      grandTotal.rulaj_lunar_debit += parseFloat(row.rulaj_lunar_debit) || 0;
      grandTotal.rulaj_lunar_credit += parseFloat(row.rulaj_lunar_credit) || 0;
      grandTotal.sold_final_debit += parseFloat(row.sold_final_debit) || 0;
      grandTotal.sold_final_credit += parseFloat(row.sold_final_credit) || 0;
    });

    // Add last class total
    if (currentClass !== null) {
      result.push({
        cont: "",
        denumire: `TOTAL CLASA ${currentClass}`,
        sold_precedent_debit: classTotals[currentClass].sold_precedent_debit,
        sold_precedent_credit: classTotals[currentClass].sold_precedent_credit,
        rulaj_lunar_debit: classTotals[currentClass].rulaj_lunar_debit,
        rulaj_lunar_credit: classTotals[currentClass].rulaj_lunar_credit,
        sold_final_debit: classTotals[currentClass].sold_final_debit,
        sold_final_credit: classTotals[currentClass].sold_final_credit,
        _isTotal: true,
      });
    }

    // Add grand total row
    result.push({
      cont: "",
      denumire: "TOTAL GENERAL",
      sold_precedent_debit: grandTotal.sold_precedent_debit,
      sold_precedent_credit: grandTotal.sold_precedent_credit,
      rulaj_lunar_debit: grandTotal.rulaj_lunar_debit,
      rulaj_lunar_credit: grandTotal.rulaj_lunar_credit,
      sold_final_debit: grandTotal.sold_final_debit,
      sold_final_credit: grandTotal.sold_final_credit,
      _isTotal: true,
      _isGrandTotal: true,
    });

    return result;
  };

  // Prepare data for export with class totals and grand total
  const exportData = groupDataWithTotals(allData);

  // Define columns for PDF with proper configuration
  // A4 landscape width: ~297mm total, margins 8mm left+right = 281mm usable
  // Use 'auto' width to fill entire page width
  const columns = [
    { field: "cont", header: "Cont", type: "text", width: "auto" },
    { field: "denumire", header: "Denumire Cont", type: "text", width: "auto" },
    {
      field: "sold_precedent_debit",
      header: "Sume Prec. D",
      type: "number",
      width: "auto",
    },
    {
      field: "sold_precedent_credit",
      header: "Sume Prec. C",
      type: "number",
      width: "auto",
    },
    {
      field: "rulaj_lunar_debit",
      header: "Rulaj D",
      type: "number",
      width: "auto",
    },
    {
      field: "rulaj_lunar_credit",
      header: "Rulaj C",
      type: "number",
      width: "auto",
    },
    {
      field: "sold_final_debit",
      header: "Sold Final D",
      type: "number",
      width: "auto",
    },
    {
      field: "sold_final_credit",
      header: "Sold Final C",
      type: "number",
      width: "auto",
    },
  ];

  const result = exportToPDF(
    exportData,
    columns,
    `balanta-verificare-${currentPeriodText.value.replace(/\s+/g, "-")}`,
    {
      companyName: companyStore.selectedCompany?.name || "",
      title: "Balanta de Verificare",
      period: currentPeriodText.value,
    },
  );

  if (result.success) {
    toast.add({
      severity: "success",
      summary: "Export reușit",
      detail: `${allData.length} înregistrări exportate cu succes`,
      life: 3000,
    });
  } else {
    toast.add({
      severity: "error",
      summary: "Eroare la export",
      detail: "Nu s-a putut genera fișierul PDF",
      life: 3000,
    });
  }
};

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

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

  // FIX: Sync period from global periodStore BEFORE loading data
  // This ensures Trial Balance shows the correct period when navigating
  // from other views (e.g., Invoices with November selected)
  if (periodStore.selectedPeriod) {
    trialBalanceStore.filters.luna = periodStore.selectedPeriod.luna;
    trialBalanceStore.filters.an = periodStore.selectedPeriod.an;
  }

  // Load trial balance if company is selected
  if (companyStore.selectedCompany) {
    await loadTrialBalance();
  }
});

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});

// Watch for company changes
watch(
  () => companyStore.selectedCompany,
  async (newCompany) => {
    if (newCompany) {
      await loadTrialBalance();
    }
  },
);

// Watch for period changes - sync luna/an with trial balance store
watch(
  () => periodStore.selectedPeriod,
  async (newPeriod) => {
    if (newPeriod && companyStore.selectedCompany) {
      await trialBalanceStore.changePeriod(
        newPeriod.luna,
        newPeriod.an,
        companyStore.selectedCompany.id_firma
      );
    }
  },
);
</script>

<style scoped>
/* ================================================
   US-108: TrialBalanceView Mobile Material Design Styles
   ================================================ */

/* ===== Page-Specific Styles Only ===== */
/* Uses shared CSS: dashboard.css (.page-header, .page-title, .page-subtitle) */
/* Uses shared CSS: forms.css (.form-actions) */
/* Uses shared CSS: tables.css (.table-empty, .loading-state) */
/* Uses shared CSS: primevue-overrides.css (DataTable striped rows, hover) */

/* Page Container */
.trial-balance {
  max-width: 1400px;
  margin: 0 auto;
  padding: var(--space-xl);
}

/* Mobile layout adjustments for top/bottom bars */
.mobile-layout .trial-balance {
  padding-top: calc(56px + var(--space-md)); /* Account for fixed MobileTopBar */
  padding-bottom: calc(56px + var(--space-md)); /* Account for fixed MobileBottomNav */
  padding-left: var(--space-md);
  padding-right: var(--space-md);
}

/* Card Spacing */
.company-selection-card,
.filters-card,
.table-card {
  margin-bottom: var(--space-xl);
}

/* Search field takes 2 columns in form grid */
.search-col {
  grid-column: span 2;
}

/* Text alignment utility - page specific */
.text-right {
  text-align: right;
}

/* Uses shared CSS: stats.css (.summary-stats-inline, .stat-item, .stat-label, .stat-value) */

/* ================================================
   US-108: Mobile Totals Bar
   ================================================ */

.mobile-totals-bar {
  background: var(--surface-card);
  border-bottom: 1px solid var(--surface-border);
  padding: var(--space-sm) var(--space-md);
  margin-bottom: var(--space-md);
  border-radius: var(--radius-md);
}

.mobile-totals-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.mobile-totals-grid {
  display: flex;
  gap: var(--space-lg);
}

.mobile-totals-grid.two-totals {
  justify-content: space-around;
  width: 100%;
}

.mobile-totals-bar .total-item {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
}

.mobile-totals-bar .total-label {
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
  font-weight: var(--font-medium);
}

.mobile-totals-bar .total-value {
  font-size: var(--text-lg);
  font-weight: var(--font-bold);
  color: var(--text-color);
}

/* ================================================
   US-108: Mobile Card List (Account Cards)
   ================================================ */

.mobile-card-list {
  display: flex;
  flex-direction: column;
  gap: var(--space-sm);
}

.mobile-data-card {
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-md);
  padding: var(--space-md);
}

.mobile-data-card .card-header {
  font-weight: var(--font-semibold);
  color: var(--text-color);
  margin-bottom: var(--space-xs);
  font-size: var(--text-base);
}

.mobile-data-card .card-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
}

.mobile-data-card .card-amount {
  font-weight: var(--font-semibold);
  color: var(--text-color);
}

.mobile-empty {
  text-align: center;
  padding: var(--space-xl);
  color: var(--text-color-secondary);
}

.mobile-empty i {
  font-size: var(--text-3xl);
  margin-bottom: var(--space-sm);
  display: block;
}

/* ================================================
   US-108: Bottom Sheet Styles
   ================================================ */

.bottom-sheet-title {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  color: var(--text-color);
  margin: 0 0 var(--space-md) 0;
}

.bottom-sheet-filters {
  display: flex;
  flex-direction: column;
  gap: var(--space-md);
}

.bottom-sheet-actions {
  display: flex;
  gap: var(--space-sm);
  justify-content: flex-end;
  margin-top: var(--space-md);
  padding-top: var(--space-md);
  border-top: 1px solid var(--surface-border);
}

/* ================================================
   US-108: Mobile Sidebar Menu Styles
   ================================================ */

.sidebar-header {
  padding: var(--space-md);
}

.sidebar-title {
  font-size: var(--text-xl);
  font-weight: var(--font-bold);
  color: var(--text-color);
}

.sidebar-menu {
  display: flex;
  flex-direction: column;
  padding: var(--space-sm);
}

.sidebar-item {
  display: flex;
  align-items: center;
  gap: var(--space-md);
  padding: var(--space-md);
  color: var(--text-color);
  text-decoration: none;
  border-radius: var(--radius-md);
  font-weight: var(--font-medium);
  transition: background var(--transition-fast);
}

.sidebar-item:hover {
  background: var(--surface-hover);
}

.sidebar-item.active {
  background: var(--blue-50);
  color: var(--color-primary);
}

.sidebar-item i {
  font-size: var(--text-xl);
  width: 24px;
  text-align: center;
}

/* ================================================
   Dark Mode Support
   ================================================ */

[data-theme="dark"] .sidebar-item.active {
  background: var(--blue-900);
  color: var(--blue-400);
}

/* Auto dark mode */
@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) .sidebar-item.active {
    background: var(--blue-900);
    color: var(--blue-400);
  }
}

/* ================================================
   Responsive Design
   ================================================ */

@media (max-width: 768px) {
  .trial-balance {
    padding: var(--space-md);
  }

  .search-col {
    grid-column: span 1;
  }
}
</style>
