import { useState, useEffect } from 'react';
import { safeJsonParse } from '@/lib/utils';

/**
 * 사용자 역할을 관리하는 최적화된 훅
 * localStorage 변경 감지 및 자동 업데이트
 */
export function useUserRole() {
  const [userRole, setUserRole] = useState<string>(() => {
    // SSR-safe: 서버에서는 기본값 반환
    if (typeof window === 'undefined') return "CEO";
    const userData = safeJsonParse<Record<string, unknown> | null>(localStorage.getItem("user"), null);
    return (userData?.role as string) || "CEO";
  });

  useEffect(() => {
    const handleStorageChange = () => {
      const userData = safeJsonParse<Record<string, unknown> | null>(localStorage.getItem("user"), null);
      const newRole = (userData?.role as string) || "CEO";
      setUserRole(newRole);
    };

    // Listen to custom storage event
    window.addEventListener('storage', handleStorageChange);
    // Listen to custom role change event
    window.addEventListener('roleChanged', handleStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('roleChanged', handleStorageChange);
    };
  }, []);

  return userRole;
}
