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

/**
 * Console log/history lives here instead of in ConsolePanel so it survives
 * the panel unmounting when the active workspace (Revision Control /
 * Organization / Time Tracking) switches.
 */

const ConsoleContext = createContext(null);

export function ConsoleProvider({ children }) {
  const [lines, setLines] = useState([]);
  const [history, setHistory] = useState([]);

  const appendLine = useCallback((line) => {
    setLines((prev) => [...prev, line]);
  }, []);

  const appendHistory = useCallback((command) => {
    setHistory((prev) => [...prev, command]);
  }, []);

  const value = useMemo(
    () => ({ lines, appendLine, history, appendHistory }),
    [lines, appendLine, history, appendHistory]
  );

  return <ConsoleContext.Provider value={value}>{children}</ConsoleContext.Provider>;
}

export function useConsoleLog() {
  const ctx = useContext(ConsoleContext);
  if (!ctx) throw new Error('useConsoleLog must be used within ConsoleProvider');
  return ctx;
}
