// daygig-state.js — Shared globals, utilities, and constants
// Load this FIRST before all other daygig-*.js files.

// ── Shared state ─────────────────────────────────────────────────────────────
let settings       = {};
let _settingsData  = {};
let _allMaterials  = [];   // cached for BOM dropdowns — bust on material save
let _allProducts   = [];   // cached for movements dropdown
let _rcpAccounts   = [];   // cached for receipt parser account dropdowns
let acctAccounts   = [];   // cached for accounting dropdowns
let postSelectedRow = null;
let receiptStoredFilename = null;
let receiptParsed         = null;
let complianceSummaryCache = null;
let compliancePacketsCache = [];

// Canonical profile/module defaults used by boot + nav.
const DAYGIG_DEFAULT_SETTINGS = {
  user_profile: 'business',
  sales_tax_rate: '0.0',
  state_tax_rate: '0.0',
  local_tax_rate: '0.0',
  enable_personal_budgeting: '0',
  enable_spending_categories: '0',
  enable_subscription_tracking: '0',
  enable_inventory: '1',
  enable_materials: '1',
  enable_bom: '0',
  enable_receipts: '1',
  enable_shipments: '1',
  enable_campaigns: '1',
  enable_deadlines: '1',
};

function dgTruth(v) {
  return ['1','true','yes','on','enabled'].includes(String(v ?? '').trim().toLowerCase());
}

function dgNormalizeSettings(raw = {}) {
  const out = { ...DAYGIG_DEFAULT_SETTINGS, ...(raw || {}) };
  const features = String(out.features || '').split(',').map(x => x.trim()).filter(Boolean);
  const featureToFlag = {
    campaigns: 'enable_campaigns',
    inventory: 'enable_inventory',
    bom: 'enable_bom',
    materials: 'enable_materials',
    receipts: 'enable_receipts',
    deadlines: 'enable_deadlines',
    shipments: 'enable_shipments',
    personal_budgeting: 'enable_personal_budgeting',
    spending_categories: 'enable_spending_categories',
    subscription_tracking: 'enable_subscription_tracking',
  };
  features.forEach(f => {
    if (featureToFlag[f] && raw[featureToFlag[f]] == null) out[featureToFlag[f]] = '1';
  });
  if (dgTruth(out.enable_bom)) out.enable_materials = '1';
  if ((out.user_profile || '').toLowerCase() === 'personal') {
    out.enable_personal_budgeting = raw.enable_personal_budgeting ?? '1';
    out.enable_spending_categories = raw.enable_spending_categories ?? '1';
    out.enable_subscription_tracking = raw.enable_subscription_tracking ?? '1';
  }
  return out;
}

function dgSettingsFromPayload(data = {}) {
  return dgNormalizeSettings(data?.public_settings?.settings || data?.settings || data?.profile || data || {});
}

function dgIsPersonalProfile(s = settings) {
  return String((s || {}).user_profile || 'business').toLowerCase() === 'personal';
}

function dgSetValue(id, value) {
  const el = document.getElementById(id);
  if (!el || value === undefined || value === null) return;
  if (el.type === 'checkbox') el.checked = dgTruth(value);
  else el.value = value;
}

function dgReadSettingInput(key) {
  const el = document.getElementById('set-' + key);
  if (!el) return undefined;
  return el.type === 'checkbox' ? (el.checked ? '1' : '0') : el.value;
}


// ── Utility functions ─────────────────────────────────────────────────────────
function cap(s) { return s ? s.charAt(0).toUpperCase() + s.slice(1) : s; }

function money(v) {
  return window.dgMoney ? window.dgMoney(v) : '$' + Number(v || 0).toFixed(2);
}

function todayIso() {
  return new Date().toISOString().slice(0, 10);
}

function flashMsg(id) {
  const el = document.getElementById(id);
  if (!el) return;
  el.style.display = 'inline';
  setTimeout(() => el.style.display = 'none', 2500);
}
