import { useState, useEffect, useCallback } from 'react';

export const useDashboardFeatures = () => {
  const [isDarkMode, setIsDarkMode] = useState(false);

  useEffect(() => {
    const darkMode = localStorage.getItem('dashboard-dark-mode') === 'true';
    setIsDarkMode(darkMode);
    document.documentElement.classList.toggle('dark', darkMode);
  }, []);

  const toggleDarkMode = useCallback(() => {
    const newMode = !isDarkMode;
    setIsDarkMode(newMode);
    localStorage.setItem('dashboard-dark-mode', newMode.toString());
    document.documentElement.classList.toggle('dark', newMode);
  }, [isDarkMode]);

  const initializeTooltips = useCallback(() => {
    // Initialize tooltips for elements with data-tooltip attribute
    const tooltipElements = document.querySelectorAll('[data-tooltip]');
    tooltipElements.forEach(element => {
      element.addEventListener('mouseenter', (e) => {
        const target = e.target as HTMLElement;
        const tooltipText = target.getAttribute('data-tooltip');
        if (tooltipText) {
          showTooltip(target, tooltipText);
        }
      });
      
      element.addEventListener('mouseleave', () => {
        hideTooltip();
      });
    });
  }, []);

  const showTooltip = (element: HTMLElement, text: string) => {
    const tooltip = document.createElement('div');
    tooltip.className = 'dashboard-tooltip';
    tooltip.textContent = text;
    tooltip.style.cssText = `
      position: absolute;
      background-color: #333;
      color: white;
      padding: 8px 12px;
      border-radius: 6px;
      font-size: 12px;
      z-index: 1000;
      pointer-events: none;
      white-space: nowrap;
    `;
    
    document.body.appendChild(tooltip);
    
    const rect = element.getBoundingClientRect();
    tooltip.style.left = `${rect.left + rect.width / 2 - tooltip.offsetWidth / 2}px`;
    tooltip.style.top = `${rect.top - tooltip.offsetHeight - 8}px`;
  };

  const hideTooltip = () => {
    const tooltip = document.querySelector('.dashboard-tooltip');
    if (tooltip) {
      tooltip.remove();
    }
  };

  return {
    isDarkMode,
    toggleDarkMode,
    initializeTooltips
  };
};

export const useCounter = (end: number, duration: number = 2000) => {
  const [count, setCount] = useState(0);
  const [isVisible, setIsVisible] = useState(false);

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

    const startTime = Date.now();
    const timer = setInterval(() => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const currentCount = Math.floor(progress * end);
      
      setCount(currentCount);
      
      if (progress >= 1) {
        clearInterval(timer);
      }
    }, 16);

    return () => clearInterval(timer);
  }, [end, duration, isVisible]);

  const startCounter = () => setIsVisible(true);

  return { count, startCounter };
};