import defaultCars from './carOptions.json';

const storageKey = 'kentekenCars';

const normalizeCars = (cars) =>
  Array.isArray(cars) && cars.length ? cars : defaultCars;

export const loadCars = async () => {
  if (typeof window === 'undefined') {
    return normalizeCars(defaultCars);
  }
  if (window.api?.loadCars) {
    try {
      const cars = await window.api.loadCars();
      return normalizeCars(cars);
    } catch (error) {
      return normalizeCars(defaultCars);
    }
  }
  const stored = window.localStorage.getItem(storageKey);
  if (!stored) {
    const fallback = normalizeCars(defaultCars);
    window.localStorage.setItem(storageKey, JSON.stringify(fallback));
    return fallback;
  }
  try {
    const parsed = JSON.parse(stored);
    return normalizeCars(parsed);
  } catch (error) {
    const fallback = normalizeCars(defaultCars);
    window.localStorage.setItem(storageKey, JSON.stringify(fallback));
    return fallback;
  }
};

export const saveCars = async (cars) => {
  if (typeof window === 'undefined') {
    return;
  }
  if (window.api?.saveCars) {
    await window.api.saveCars(normalizeCars(cars));
    return;
  }
  const normalized = normalizeCars(cars);
  window.localStorage.setItem(storageKey, JSON.stringify(normalized));
};

export const getCarsFolder = async () => {
  if (typeof window === 'undefined') {
    return '';
  }
  if (window.api?.getCarsFolder) {
    return window.api.getCarsFolder();
  }
  return '';
};

export const selectCarsFolder = async () => {
  if (typeof window === 'undefined') {
    return null;
  }
  if (window.api?.selectCarsFolder) {
    return window.api.selectCarsFolder();
  }
  return null;
};

export const resetCarsFolder = async () => {
  if (typeof window === 'undefined') {
    return null;
  }
  if (window.api?.resetCarsFolder) {
    return window.api.resetCarsFolder();
  }
  return null;
};
