/**
 * Utility functions for localStorage operations
 */

/**
 * Generate site-specific localStorage key
 * @param {string} settingsType - Type of settings (e.g., 'comment', 'author')
 * @returns {string} - Site-specific localStorage key
 */
export const generateStorageKey = (settingsType) => {
  const pathParts = window.location.pathname.split("/").filter(Boolean);
  const indexOfAdmin = pathParts.indexOf('wp-admin');
  const siteIdentifier = indexOfAdmin !== -1 
    ? pathParts.slice(indexOfAdmin - 1, indexOfAdmin).pop() 
    : pathParts.slice(-1).pop();
  
  return `wpnts_${settingsType}_settings_${siteIdentifier}`;
};

/**
 * Save settings to localStorage
 * @param {string} key - Storage key
 * @param {object} data - Data to save
 */
export const saveToStorage = (key, data) => {
  try {
    localStorage.setItem(key, JSON.stringify(data));
  } catch (error) {
    console.error('Error saving to localStorage:', error);
  }
};

/**
 * Get settings from localStorage
 * @param {string} key - Storage key
 * @param {object} defaultValue - Default value if not found
 * @returns {object} - Parsed data or default value
 */
export const getFromStorage = (key, defaultValue = {}) => {
  try {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : defaultValue;
  } catch (error) {
    console.error('Error reading from localStorage:', error);
    return defaultValue;
  }
};

/**
 * Remove item from localStorage
 * @param {string} key - Storage key
 */
export const removeFromStorage = (key) => {
  try {
    localStorage.removeItem(key);
  } catch (error) {
    console.error('Error removing from localStorage:', error);
  }
};