// Storage keys
const NOTES_KEY = 'notes';
const FOLDERS_KEY = 'folders';
const SETTINGS_KEY = 'settings';

// Notes functions
export const getNotes = async () => {
  try {
    const notesJson = localStorage.getItem(NOTES_KEY);
    return notesJson ? JSON.parse(notesJson) : [];
  } catch (error) {
    console.error('Error getting notes:', error);
    return [];
  }
};

export const saveNotes = async (notes) => {
  try {
    localStorage.setItem(NOTES_KEY, JSON.stringify(notes));
  } catch (error) {
    console.error('Error saving notes:', error);
  }
};

export const addNote = async (note) => {
  const newNote = {
    ...note,
    id: Date.now().toString(),
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    isStarred: note.isStarred || false,
    isTop: note.isTop || false,
    hasImage: note.hasImage || false
  };

  const notes = await getNotes();
  notes.push(newNote);
  await saveNotes(notes);

  return newNote;
};

export const updateNote = async (id, updates) => {
  const notes = await getNotes();
  const index = notes.findIndex(note => note.id === id);
  
  if (index === -1) return null;
  
  const updatedNote = {
    ...notes[index],
    ...updates,
    updatedAt: new Date().toISOString(),
  };
  
  notes[index] = updatedNote;
  await saveNotes(notes);
  
  return updatedNote;
};

export const deleteNote = async (id) => {
  const notes = await getNotes();
  const filteredNotes = notes.filter(note => note.id !== id);
  
  if (notes.length === filteredNotes.length) return false;
  
  await saveNotes(filteredNotes);
  return true;
};

// Folders functions
export const getFolders = async () => {
  try {
    const foldersJson = localStorage.getItem(FOLDERS_KEY);
    return foldersJson ? JSON.parse(foldersJson) : [];
  } catch (error) {
    console.error('Error getting folders:', error);
    return [];
  }
};

export const saveFolders = async (folders) => {
  try {
    localStorage.setItem(FOLDERS_KEY, JSON.stringify(folders));
  } catch (error) {
    console.error('Error saving folders:', error);
  }
};

export const addFolder = async (folder) => {
  const newFolder = {
    ...folder,
    id: Date.now().toString(),
    createdAt: new Date().toISOString(),
  };

  const folders = await getFolders();
  folders.push(newFolder);
  await saveFolders(folders);

  return newFolder;
};

// Settings functions
export const getSettings = async () => {
  try {
    const settingsJson = localStorage.getItem(SETTINGS_KEY);
    return settingsJson ? JSON.parse(settingsJson) : { cloudSync: false, darkMode: false };
  } catch (error) {
    console.error('Error getting settings:', error);
    return { cloudSync: false, darkMode: false };
  }
};

export const saveSettings = async (settings) => {
  try {
    localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
  } catch (error) {
    console.error('Error saving settings:', error);
  }
};