import { useState, useEffect } from 'react';
import { useAuthStore } from '../../store/authStore';

export default function ResourceDebugToggle() {
  const { user } = useAuthStore();
  const [enabled, setEnabled] = useState(false);

  const isAdminOrDeveloper = user?.role === 'admin' || user?.role === 'developer';

  // Load saved state from localStorage
  useEffect(() => {
    if (isAdminOrDeveloper) {
      const saved = localStorage.getItem('debug_resource_tracking_enabled');
      setEnabled(saved === 'true');
    }
  }, [isAdminOrDeveloper]);

  const toggle = () => {
    const newValue = !enabled;
    setEnabled(newValue);
    localStorage.setItem('debug_resource_tracking_enabled', String(newValue));
    // Dispatch event for overlay component
    window.dispatchEvent(new CustomEvent('debug-resource-tracking-toggle', { detail: newValue }));
  };

  if (!isAdminOrDeveloper) return null;

  return (
    <button
      onClick={toggle}
      className={`flex items-center justify-center w-10 h-10 rounded-lg transition-colors ${
        enabled
          ? 'bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400'
          : 'text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800'
      }`}
      title={enabled ? 'Disable Resource Debug' : 'Enable Resource Debug'}
    >
      🔍
    </button>
  );
}

