/**
 * Application state - single source of truth for view, timer, cache, and filters.
 * Used by app.js to avoid scattered globals.
 * API client lifecycle is owned by ConnectionManager; this field is synced for legacy call sites.
 */
const state = {
  apiClient: null,
  /** Count consecutive background checks that failed with auth (401) while on main UI */
  authFailureStreak: 0,
  /** Last timer poll error shown to user (avoid spam) */
  lastTimerPollUserMessageAt: 0,
  currentView: 'dashboard',
  timerInterval: null,
  isTimerRunning: false,
  connectionCheckInterval: null,
  currentUserProfile: { is_admin: false, can_approve: false },
  cachedInvoices: [],
  cachedExpenses: [],
  cachedWorkforce: { periods: [], capacity: [], timeOffRequests: [], balances: [] },
  viewFilters: { invoiceQuery: '', expenseQuery: '', timeoffQuery: '' },
  viewLimits: { invoices: 20, expenses: 20, timeoff: 20 },
  pagination: {
    invoices: { page: 1, perPage: 20, totalPages: 1, total: 0 },
    expenses: { page: 1, perPage: 20, totalPages: 1, total: 0 },
  },
};

function clearViewCaches() {
  state.cachedInvoices = [];
  state.cachedExpenses = [];
  state.cachedWorkforce = { periods: [], capacity: [], timeOffRequests: [], balances: [] };
}

state.clearViewCaches = clearViewCaches;
module.exports = state;
