import { useCallback, useEffect, useState } from 'react';
import { useSessionStorage } from 'src/contexts/sessionStorageContext';

export const useSessionStorageValue = (key: string) => {
  const { getItem, setItem } = useSessionStorage();
  const [value, setValue] = useState<string | null>(() => getItem(key));

  useEffect(() => {
    const handleStorageChange = (event: StorageEvent) => {
      if (event.key === key) {
        setValue(event.newValue);
      }
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, [key, getItem]);

  const updateValue = useCallback(
    (newValue: string) => {
      setItem(key, newValue);
      setValue(newValue);
    },
    [key, setItem],
  );

  return { value, setValue: updateValue };
};
