'use client';

import {
  createContext,
  useContext,
  useState,
  type ReactNode
} from 'react';

interface DebugContextType {
  showComponentNames: boolean;
  toggleComponentNames: () => void;
}

const DebugContext = createContext<DebugContextType | null>(null);

export function DebugProvider({ children }: { children: ReactNode }) {
  // Initialize from localStorage if available
  const [showComponentNames, setShowComponentNames] = useState(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem('debug-show-component-names');
      return saved === 'true';
    }
    return false;
  });

  const toggleComponentNames = () => {
    setShowComponentNames(prev => {
      const newValue = !prev;
      localStorage.setItem('debug-show-component-names', String(newValue));
      return newValue;
    });
  };

  return (
    <DebugContext.Provider value={{ showComponentNames, toggleComponentNames }}>
      {children}
    </DebugContext.Provider>
  );
}

export function useDebug() {
  const context = useContext(DebugContext);
  if (!context) {
    // Return default values if used outside provider
    return { showComponentNames: false, toggleComponentNames: () => {} };
  }
  return context;
}

// Wrapper component to show component name in debug mode
interface DebugNameProps {
  name: string;
  children: ReactNode;
}

export function DebugName({ name, children }: DebugNameProps) {
  const { showComponentNames } = useDebug();

  if (!showComponentNames) {
    return <>{children}</>;
  }

  return (
    <div className="relative">
      <div className="absolute -top-5 left-0 text-[10px] font-mono text-yellow-400 bg-yellow-900/50 px-1 rounded z-50">
        {name}
      </div>
      {children}
    </div>
  );
}

DebugName.displayName = "DebugName";
