import { useCallback, useRef, useState } from 'react';
import type { NodeAction } from './types';
import styles from './ProcessDiagram.module.css';

const HIDE_DELAY = 150;

interface NodeToolbarProps {
  nodeId: string;
  /** Screen-space position (already transformed by zoom/pan) */
  screenX: number;
  screenY: number;
  onAction: (nodeId: string, action: NodeAction) => void;
  onMouseEnter: () => void;
  onMouseLeave: () => void;
}

const ACTIONS: { icon: string; action: NodeAction; title: string }[] = [
  { icon: '\uD83D\uDD0D', action: 'inspect', title: 'Inspect' },
  { icon: 'T', action: 'toggle-trace', title: 'Toggle tracing' },
  { icon: '\u270E', action: 'configure-tap', title: 'Configure tap' },
  { icon: '\u22EF', action: 'copy-id', title: 'Copy ID' },
];

export function NodeToolbar({
  nodeId, screenX, screenY, onAction, onMouseEnter, onMouseLeave,
}: NodeToolbarProps) {
  return (
    <div
      className={styles.nodeToolbar}
      style={{ left: screenX, top: screenY }}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
    >
      {ACTIONS.map(a => (
        <button
          key={a.action}
          className={styles.nodeToolbarBtn}
          title={a.title}
          onClick={(e) => {
            e.stopPropagation();
            onAction(nodeId, a.action);
          }}
        >
          {a.icon}
        </button>
      ))}
    </div>
  );
}

/** Hook to manage toolbar visibility with hide delay */
export function useToolbarHover() {
  const [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null);
  const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const onNodeEnter = useCallback((nodeId: string) => {
    if (hideTimer.current) {
      clearTimeout(hideTimer.current);
      hideTimer.current = null;
    }
    setHoveredNodeId(nodeId);
  }, []);

  const onNodeLeave = useCallback(() => {
    hideTimer.current = setTimeout(() => {
      setHoveredNodeId(null);
      hideTimer.current = null;
    }, HIDE_DELAY);
  }, []);

  const onToolbarEnter = useCallback(() => {
    if (hideTimer.current) {
      clearTimeout(hideTimer.current);
      hideTimer.current = null;
    }
  }, []);

  const onToolbarLeave = useCallback(() => {
    hideTimer.current = setTimeout(() => {
      setHoveredNodeId(null);
      hideTimer.current = null;
    }, HIDE_DELAY);
  }, []);

  return { hoveredNodeId, onNodeEnter, onNodeLeave, onToolbarEnter, onToolbarLeave };
}
