import { useEffect, useRef } from 'react';
import LogSender from '../lib/browser-index.js';

/**
 * React Hook for LogSender
 * @param {Object} config - 配置对象
 * @param {string} config.serverUrl - 服务器地址
 * @param {string} config.appName - 应用名称
 * @param {boolean} config.enabled - 是否启用
 * @returns {Object} { logSender, isInstalled }
 */
export const useLogSender = ({ 
  serverUrl = 'http://localhost:3001', 
  appName = 'react-app',
  enabled = true 
} = {}) => {
  const logSenderRef = useRef(null);
  const isInstalledRef = useRef(false);

  useEffect(() => {
    if (!enabled) return;

    // 创建 LogSender 实例
    logSenderRef.current = new LogSender(serverUrl, appName);
    
    // 安装 LogSender（只在首次安装）
    if (!isInstalledRef.current) {
      logSenderRef.current.install();
      isInstalledRef.current = true;
      
      console.log('LogSender Hook 已初始化', {
        serverUrl,
        appName
      });
    }

    // 清理函数
    return () => {
      if (logSenderRef.current && isInstalledRef.current) {
        logSenderRef.current.uninstall();
        isInstalledRef.current = false;
        console.log('LogSender Hook 已卸载');
      }
    };
  }, [serverUrl, appName, enabled]);

  return {
    logSender: logSenderRef.current,
    isInstalled: isInstalledRef.current
  };
};

// 自定义Hook的便捷版本
export const useLogSenderSimple = (serverUrl = 'http://localhost:3001', appName = 'react-app') => {
  return useLogSender({ serverUrl, appName, enabled: true });
};