import { jsx } from 'react/jsx-runtime';
import { useRef, useCallback } from 'react';
import { cn } from '../../../utils/cn.js';
import { useGanttContext } from './GanttChart.js';

const STEP = 20;
const MIN_WIDTH = 200;
const MAX_WIDTH = 800;
const GanttSplitter = () => {
    const { theme, tablePanelWidth, setTablePanelWidth } = useGanttContext();
    const startX = useRef(0);
    const startWidth = useRef(0);
    const onPointerDown = useCallback((e) => {
        e.preventDefault();
        startX.current = e.clientX;
        startWidth.current = tablePanelWidth;
        const onPointerMove = (ev) => {
            const delta = ev.clientX - startX.current;
            const next = Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, startWidth.current + delta));
            setTablePanelWidth(next);
        };
        const onPointerUp = () => {
            document.removeEventListener("pointermove", onPointerMove);
            document.removeEventListener("pointerup", onPointerUp);
        };
        document.addEventListener("pointermove", onPointerMove);
        document.addEventListener("pointerup", onPointerUp);
    }, [tablePanelWidth, setTablePanelWidth]);
    const onKeyDown = useCallback((e) => {
        if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
            e.preventDefault();
            const delta = e.key === "ArrowRight" ? STEP : -STEP;
            setTablePanelWidth(Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, tablePanelWidth + delta)));
        }
    }, [tablePanelWidth, setTablePanelWidth]);
    return (jsx("div", { className: cn(theme.splitterStyle), onPointerDown: onPointerDown, onKeyDown: onKeyDown, role: "separator", "aria-orientation": "vertical", "aria-valuenow": tablePanelWidth, "aria-valuemin": MIN_WIDTH, "aria-valuemax": MAX_WIDTH, "aria-label": "Resize table panel", tabIndex: 0 }));
};

export { GanttSplitter };
