import { useEffect } from 'react';
import { useMiningStore } from '../store/mining';

/**
 * Hook to setup and cleanup mining event listeners
 * Should be called once at the app level
 */
export function useMiningEvents() {
  const setupEventListeners = useMiningStore(
    (state) => state.setupEventListeners
  );
  const cleanupEventListeners = useMiningStore(
    (state) => state.cleanupEventListeners
  );

  useEffect(() => {
    setupEventListeners();
    return () => cleanupEventListeners();
  }, [setupEventListeners, cleanupEventListeners]);
}

/**
 * Hook to auto-start mining if enabled in settings
 */
export function useAutoStartMining() {
  const autoStartMining = useMiningStore((state) => state.autoStartMining);
  const defaultThreads = useMiningStore((state) => state.defaultThreads);
  const defaultCoinbaseAddress = useMiningStore(
    (state) => state.defaultCoinbaseAddress
  );
  const status = useMiningStore((state) => state.status);
  const startMining = useMiningStore((state) => state.startMining);

  useEffect(() => {
    // Only auto-start if setting is enabled and not already mining
    if (!autoStartMining || status.isMining || !defaultCoinbaseAddress) return;

    const autoStart = async () => {
      try {
        await startMining(defaultCoinbaseAddress, defaultThreads);
      } catch (error) {
        // Silently fail auto-start
        console.debug('Auto-start mining failed:', error);
      }
    };

    // Delay auto-start to allow node to connect first
    const timeout = setTimeout(autoStart, 3000);
    return () => clearTimeout(timeout);
  }, [
    autoStartMining,
    defaultThreads,
    defaultCoinbaseAddress,
    status.isMining,
    startMining,
  ]);
}
