/* ------------------------------------------------------------------
 * store.js — Camada de dados (localStorage)
 * Guarda toda a informação da aplicação de forma persistente no browser.
 * Não há servidor: é uma app single-page. Tudo vive em localStorage.
 * ------------------------------------------------------------------ */

const Store = (function () {
  const KEY = "gt_data_v1";

  const DEFAULTS = {
    trucks: [],
    drivers: [],
    trips: [],
    expenses: [],
    settings: {
      orsApiKey: "",
      fuelPricePerL: 1.65, // €/litro (gasóleo)
      driverCostPerHour: 12, // €/hora
      currency: "€",
      maxDailyDrivingHours: 9, // Regulamento UE 561/2006
    },
    _seq: 1,
  };

  let data = null;

  function load() {
    if (data) return data;
    try {
      const raw = localStorage.getItem(KEY);
      data = raw ? JSON.parse(raw) : structuredClone(DEFAULTS);
    } catch (e) {
      console.error("Falha a ler dados, a recomeçar:", e);
      data = structuredClone(DEFAULTS);
    }
    // Garante que novas chaves de settings existem em dados antigos
    data.settings = Object.assign({}, DEFAULTS.settings, data.settings || {});
    return data;
  }

  function save() {
    localStorage.setItem(KEY, JSON.stringify(data));
  }

  function nextId(prefix) {
    load();
    const id = `${prefix}${data._seq++}`;
    save();
    return id;
  }

  /* --- CRUD genérico por coleção --- */
  function list(collection) {
    return load()[collection] || [];
  }

  function get(collection, id) {
    return list(collection).find((x) => x.id === id) || null;
  }

  function upsert(collection, obj) {
    load();
    if (!obj.id) obj.id = nextId(collection[0]);
    const arr = data[collection];
    const idx = arr.findIndex((x) => x.id === obj.id);
    if (idx >= 0) arr[idx] = obj;
    else arr.push(obj);
    save();
    return obj;
  }

  function remove(collection, id) {
    load();
    data[collection] = data[collection].filter((x) => x.id !== id);
    save();
  }

  /* --- Settings --- */
  function getSettings() {
    return load().settings;
  }
  function saveSettings(patch) {
    load();
    data.settings = Object.assign({}, data.settings, patch);
    save();
    return data.settings;
  }

  /* --- Export / Import (backup) --- */
  function exportJSON() {
    return JSON.stringify(load(), null, 2);
  }
  function importJSON(json) {
    data = JSON.parse(json);
    save();
  }
  function reset() {
    data = structuredClone(DEFAULTS);
    save();
  }

  function seedDemo() {
    load();
    if (data.trucks.length || data.trips.length) return false;
    const t1 = upsert("trucks", {
      plate: "AA-01-BB", brand: "Volvo", model: "FH16", maxWeightKg: 26000,
      tareKg: 9000, heightM: 4.0, widthM: 2.55, lengthM: 16.5,
      fuelConsumptionLper100: 32, status: "disponível",
      inspectionDue: addDays(45), insuranceDue: addDays(120),
    });
    const t2 = upsert("trucks", {
      plate: "CC-22-DD", brand: "Mercedes", model: "Actros", maxWeightKg: 24000,
      tareKg: 8500, heightM: 3.9, widthM: 2.55, lengthM: 16.5,
      fuelConsumptionLper100: 30, status: "disponível",
      inspectionDue: addDays(15), insuranceDue: addDays(200),
    });
    const d1 = upsert("drivers", {
      name: "João Silva", licenseNumber: "PT-123456", licenseCategories: "C+E",
      licenseExpiry: addDays(300), phone: "912345678", status: "ativo",
    });
    const d2 = upsert("drivers", {
      name: "Maria Santos", licenseNumber: "PT-654321", licenseCategories: "C+E",
      licenseExpiry: addDays(20), phone: "934567890", status: "ativo",
    });
    upsert("trips", {
      cargoDesc: "Material de construção", weightKg: 18000,
      origin: { name: "Lisboa", lat: 38.7223, lon: -9.1393 },
      destination: { name: "Porto", lat: 41.1579, lon: -8.6291 },
      waypoints: [], truckId: t1.id, driverId: d1.id,
      status: "planeada", plannedDate: addDays(2),
      priceCharged: 850, distanceKm: 313, durationMin: 195,
      tollCost: 45, geometry: null, notes: "",
    });
    save();
    return true;
  }

  function addDays(n) {
    const d = new Date();
    d.setDate(d.getDate() + n);
    return d.toISOString().slice(0, 10);
  }

  return {
    list, get, upsert, remove,
    getSettings, saveSettings,
    exportJSON, importJSON, reset, seedDemo,
  };
})();
