import { create } from 'zustand';
import type { ModelTemplate, JewelryType } from '../types';

const STORAGE_KEY = 'safnaturel_templates';

function loadFromLocalStorage(): ModelTemplate[] {
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    return data ? JSON.parse(data) : [];
  } catch {
    return [];
  }
}

function saveToLocalStorage(templates: ModelTemplate[]): void {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(templates));
  } catch {
    // silently ignore storage errors
  }
}

interface TemplateStore {
  templates: ModelTemplate[];
  loading: boolean;
  error: string | null;
  fetchTemplates: (jewelryType?: JewelryType) => Promise<void>;
  addTemplate: (template: ModelTemplate) => void;
  removeTemplate: (id: number) => void;
}

export const useTemplateStore = create<TemplateStore>((set, get) => ({
  templates: [],
  loading: false,
  error: null,

  fetchTemplates: async (jewelryType?: JewelryType) => {
    set({ loading: true, error: null });
    try {
      const params = jewelryType ? `?type=${jewelryType}` : '';
      const response = await fetch(`/api/templates.php${params}`);
      if (!response.ok) throw new Error('API request failed');
      const json = await response.json();
      const templates: ModelTemplate[] = json.data ?? json;
      set({ templates, loading: false });
      saveToLocalStorage(templates);
    } catch {
      // API failed — fall back to localStorage
      const cached = loadFromLocalStorage();
      const filtered = jewelryType
        ? cached.filter((t) => t.jewelryType === jewelryType)
        : cached;
      set({ templates: filtered, loading: false, error: 'API bağlantısı başarısız, önbellekten yüklendi' });
    }
  },

  addTemplate: (template: ModelTemplate) => {
    const current = get().templates;
    const exists = current.some((t) => t.id === template.id);
    if (exists) return;
    const updated = [...current, template];
    set({ templates: updated });
    // Sync full list to localStorage (merge with existing)
    const all = loadFromLocalStorage();
    const allUpdated = all.some((t) => t.id === template.id)
      ? all
      : [...all, template];
    saveToLocalStorage(allUpdated);
  },

  removeTemplate: (id: number) => {
    const updated = get().templates.filter((t) => t.id !== id);
    set({ templates: updated });
    const all = loadFromLocalStorage().filter((t) => t.id !== id);
    saveToLocalStorage(all);
  },
}));
