import { useState, useEffect } from 'react';

/**
 * Custom hook for managing localStorage with site-specific keys
 * @param {string} settingsKey - The settings key (e.g., 'comment_settings')
 * @param {object} defaultSettings - Default settings object
 * @returns {[object, function]} - [settings, updateSettings]
 */
export const useLocalStorage = (settingsKey, defaultSettings) => {
  // Generate site-specific localStorage key
  const getSiteIdentifier = () => {
    const pathParts = window.location.pathname.split("/").filter(Boolean);
    const indexOfAdmin = pathParts.indexOf('wp-admin');
    return indexOfAdmin !== -1 
      ? pathParts.slice(indexOfAdmin - 1, indexOfAdmin).pop() 
      : pathParts.slice(-1).pop();
  };

  const localStorageKey = `wpnts_${settingsKey}_${getSiteIdentifier()}`;

  const [settings, setSettings] = useState(() => {
    try {
      const stored = localStorage.getItem(localStorageKey);
      return stored ? JSON.parse(stored) : defaultSettings;
    } catch (error) {
      console.error('Error parsing localStorage:', error);
      return defaultSettings;
    }
  });

  const updateSettings = (newSettings) => {
    try {
      localStorage.setItem(localStorageKey, JSON.stringify(newSettings));
      setSettings(newSettings);
    } catch (error) {
      console.error('Error saving to localStorage:', error);
    }
  };

  return [settings, updateSettings];
};