
import React, { createContext, useState, useContext, useCallback } from 'react';

export type LogType = 'info' | 'success' | 'error' | 'warn';

export interface LogMessage {
  type: LogType;
  message: string;
  timestamp: string;
}

interface LoggingContextType {
  logs: LogMessage[];
  log: (type: LogType, message: string) => void;
  clearLogs: () => void;
}

const LoggingContext = createContext<LoggingContextType | undefined>(undefined);

export const LoggingProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [logs, setLogs] = useState<LogMessage[]>([]);

  const log = useCallback((type: LogType, message: string) => {
    const timestamp = new Date().toLocaleTimeString();
    setLogs(prevLogs => [...prevLogs, { type, message, timestamp }]);
  }, []);
  
  const clearLogs = useCallback(() => {
    setLogs([]);
  }, []);

  return (
    <LoggingContext.Provider value={{ logs, log, clearLogs }}>
      {children}
    </LoggingContext.Provider>
  );
};

export const useLogger = (): LoggingContextType => {
  const context = useContext(LoggingContext);
  if (context === undefined) {
    throw new Error('useLogger must be used within a LoggingProvider');
  }
  return context;
};
