import { useState, useEffect, useCallback, useRef } from "react";

interface AutoHideOptions {
  timeout?: number;
  enabled?: boolean;
}

export function useAutoHide(options: AutoHideOptions = {}) {
  const { timeout = 3000, enabled = true } = options;
  const [isVisible, setIsVisible] = useState(true);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const lastInteractionRef = useRef(Date.now());

  const show = useCallback(() => {
    if (!enabled) return;
    setIsVisible(true);
    lastInteractionRef.current = Date.now();

    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }

    timerRef.current = setTimeout(() => {
      setIsVisible(false);
    }, timeout);
  }, [enabled, timeout]);

  const hide = useCallback(() => {
    if (!enabled) return;
    setIsVisible(false);
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
  }, [enabled]);

  const toggle = useCallback(() => {
    if (!enabled) return;
    if (isVisible) {
      hide();
    } else {
      show();
    }
  }, [enabled, isVisible, show, hide]);

  useEffect(() => {
    if (!enabled) {
      setIsVisible(true);
      return;
    }

    // Start the timer initially
    show();

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, [enabled, show]);

  return {
    isVisible,
    show,
    hide,
    toggle,
  };
}
