/*
 * T Market POS - Módulo Ventas
 * v5.8.6 caja configurable
 *
 * Este archivo separa utilidades seguras del módulo de ventas sin mover todavía
 * toda la lógica del POS. Objetivo: reducir riesgo y preparar futuras versiones.
 */
(function(window) {
  "use strict";

  const VERSION = "v5.8.6-caja-configurable";
  const DEFAULT_KEYS = {
    pendingSales: "TMARKET_POS_PENDING_SALES",
    offlineQueue: "TMARKET_OFFLINE_QUEUE",
    provisionalCuts: "TMARKET_PROVISIONAL_CUTS"
  };

  function safeJsonParse(value, fallback) {
    if(value === null || value === undefined || value === "") return fallback;
    try {
      return JSON.parse(value);
    } catch {
      return fallback;
    }
  }

  function saveJson(key, value) {
    try {
      window.localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch(error) {
      console.warn("[TMarketVentas] No se pudo guardar en localStorage:", key, error);
      return false;
    }
  }

  function loadJson(key, fallback) {
    try {
      return safeJsonParse(window.localStorage.getItem(key), fallback);
    } catch(error) {
      console.warn("[TMarketVentas] No se pudo leer localStorage:", key, error);
      return fallback;
    }
  }

  function removeKey(key) {
    try {
      window.localStorage.removeItem(key);
      return true;
    } catch(error) {
      console.warn("[TMarketVentas] No se pudo limpiar localStorage:", key, error);
      return false;
    }
  }

  function makeClientRequestId(prefix = "REQ") {
    return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
  }

  function normalizeSaleTabsSnapshot(snapshot = {}) {
    return {
      saleTabs: Array.isArray(snapshot.saleTabs) ? snapshot.saleTabs : [],
      activeSaleTabId: snapshot.activeSaleTabId || "",
      nextSaleNumber: Math.max(1, Number(snapshot.nextSaleNumber) || 1),
      savedAt: snapshot.savedAt || new Date().toISOString(),
      moduleVersion: VERSION
    };
  }

  function savePendingSales(snapshot, key = DEFAULT_KEYS.pendingSales) {
    return saveJson(key, normalizeSaleTabsSnapshot({
      ...snapshot,
      savedAt: new Date().toISOString(),
      moduleVersion: VERSION
    }));
  }

  function loadPendingSales(key = DEFAULT_KEYS.pendingSales) {
    return normalizeSaleTabsSnapshot(loadJson(key, {}));
  }

  function clearPendingSales(key = DEFAULT_KEYS.pendingSales) {
    return removeKey(key);
  }

  function hasRecoverableSaleDraft(key = DEFAULT_KEYS.pendingSales) {
    const saved = loadPendingSales(key);
    return saved.saleTabs.some(tab => Array.isArray(tab.cart) && tab.cart.length);
  }

  function summarizePendingSales(key = DEFAULT_KEYS.pendingSales) {
    const saved = loadPendingSales(key);
    const tabs = saved.saleTabs || [];
    const items = tabs.reduce((total, tab) => total + ((tab.cart || []).reduce((sum, item) => sum + (Number(item.quantity) || 0), 0)), 0);
    return {
      tabs: tabs.length,
      items,
      activeSaleTabId: saved.activeSaleTabId,
      savedAt: saved.savedAt || ""
    };
  }

  function loadQueue(key) {
    const rows = loadJson(key, []);
    return Array.isArray(rows) ? rows : [];
  }

  function saveQueue(key, rows) {
    return saveJson(key, Array.isArray(rows) ? rows : []);
  }

  window.TMarketVentas = Object.freeze({
    version: VERSION,
    keys: Object.freeze({ ...DEFAULT_KEYS }),
    safeJsonParse,
    saveJson,
    loadJson,
    removeKey,
    makeClientRequestId,
    savePendingSales,
    loadPendingSales,
    clearPendingSales,
    hasRecoverableSaleDraft,
    summarizePendingSales,
    loadQueue,
    saveQueue
  });
})(window);
