// ui/src/components/layout/ResizeHandle.tsx
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';

interface ResizeHandleProps {
  /** drag 中に呼ばれる。新しい chatPx を渡す。ref-based で React 再 render しない想定。 */
  onResize: (chatPx: number) => void;
  /** drag 終了時に 1 度だけ呼ばれる。localStorage 保存用。 */
  onResizeEnd: (chatPx: number) => void;
  /** ダブルクリックでリセット。 */
  onReset: () => void;
  railPx: number;
  minChatPx: number;
  minWorkspacePx: number;
  handlePx: number;
}

export function ResizeHandle({
  onResize,
  onResizeEnd,
  onReset,
  railPx,
  minChatPx,
  minWorkspacePx,
  handlePx,
}: ResizeHandleProps) {
  const { t } = useTranslation('layout');
  // latest-ref pattern: callback が render 毎に新しくなっても useEffect の
  // listener を付け直さずに済む。これが無いと drag 中に listener が外れる。
  const onResizeRef = useRef(onResize);
  const onResizeEndRef = useRef(onResizeEnd);
  onResizeRef.current = onResize;
  onResizeEndRef.current = onResizeEnd;

  const draggingRef = useRef(false);
  const lastChatPxRef = useRef<number | null>(null);

  useEffect(() => {
    const handleMove = (e: PointerEvent) => {
      if (!draggingRef.current) return;
      const grid = document.querySelector<HTMLElement>('[data-focused-grid="1"]');
      if (!grid) return;
      const rect = grid.getBoundingClientRect();
      const maxChatPx = rect.width - railPx - handlePx - minWorkspacePx;
      const raw = e.clientX - rect.left - railPx;
      const chatPx = Math.max(minChatPx, Math.min(maxChatPx, raw));
      lastChatPxRef.current = chatPx;
      onResizeRef.current(chatPx);
    };
    const handleUp = () => {
      if (!draggingRef.current) return;
      draggingRef.current = false;
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
      if (lastChatPxRef.current !== null) {
        onResizeEndRef.current(lastChatPxRef.current);
      }
    };
    window.addEventListener('pointermove', handleMove);
    window.addEventListener('pointerup', handleUp);
    window.addEventListener('pointercancel', handleUp);
    return () => {
      window.removeEventListener('pointermove', handleMove);
      window.removeEventListener('pointerup', handleUp);
      window.removeEventListener('pointercancel', handleUp);
    };
  }, [railPx, handlePx, minChatPx, minWorkspacePx]);

  const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
    e.preventDefault();
    draggingRef.current = true;
    document.body.style.cursor = 'col-resize';
    document.body.style.userSelect = 'none';
  };

  return (
    <div
      role="separator"
      aria-orientation="vertical"
      aria-label={t('resize.chatWorkspace')}
      onPointerDown={handlePointerDown}
      onDoubleClick={onReset}
      className="cursor-col-resize bg-transparent hover:bg-slate-300/60 transition-colors flex items-stretch group"
      style={{ width: handlePx, touchAction: 'none' }}
    >
      <div className="w-px bg-hairline mx-auto group-hover:bg-slate-500/40" />
    </div>
  );
}
