import { create } from "zustand";
import * as api from "../api/client";

// Configuration par défaut
const DEFAULT_CONFIG = {
  ui: {
    theme: "gruvbox_vintage_dark",
    button_mode: "text/icon",
    columns_desktop: 3,
    card_density: "comfortable",
    image_ratio: 40, // % de la hauteur du body pour l'image (20-60)
    show_fields: {
      price: true,
      stock: true,
      ratings: true,
      badges: true,
    },
    refresh_auto_seconds: 300,
  },
  versions: {
    frontend: "0.1.0",
    backend_expected: "0.1.0",
  },
};

const useConfigStore = create((set) => ({
  config: DEFAULT_CONFIG,
  loading: false,
  error: null,

  fetchConfig: async () => {
    set({ loading: true, error: null });
    try {
      const config = await api.fetchFrontendConfig();
      set({ config, loading: false });
    } catch (err) {
      // En cas d'erreur, on garde la config par défaut
      console.warn("Impossible de charger config_frontend.json:", err.message);
      set({ loading: false });
    }
  },

  // Getters pratiques
  getColumns: () => {
    const state = useConfigStore.getState();
    return state.config.ui?.columns_desktop || 3;
  },

  getShowFields: () => {
    const state = useConfigStore.getState();
    return state.config.ui?.show_fields || DEFAULT_CONFIG.ui.show_fields;
  },

  getImageRatio: () => {
    const state = useConfigStore.getState();
    return state.config.ui?.image_ratio || 40;
  },

  getRefreshInterval: () => {
    const state = useConfigStore.getState();
    return state.config.ui?.refresh_auto_seconds || 0;
  },

  // Setter local pour mise à jour en temps réel (sans sauvegarder)
  setImageRatioLocal: (ratio) => {
    set((state) => ({
      config: {
        ...state.config,
        ui: {
          ...state.config.ui,
          image_ratio: ratio,
        },
      },
    }));
  },
}));

export default useConfigStore;
