import { ref, onUnmounted } from 'vue'

export type PaneLayout = 'split' | 'editor-only' | 'preview-only'

export function useResizablePane(defaultSplit = 50) {
  const splitPercent = ref(defaultSplit)
  const layout = ref<PaneLayout>('split')
  const isDragging = ref(false)

  let containerEl: HTMLElement | null = null

  function startDrag(e: MouseEvent, container: HTMLElement) {
    e.preventDefault()
    isDragging.value = true
    containerEl = container
    document.addEventListener('mousemove', onDrag)
    document.addEventListener('mouseup', stopDrag)
    document.body.style.cursor = 'col-resize'
    document.body.style.userSelect = 'none'
  }

  function onDrag(e: MouseEvent) {
    if (!containerEl) return
    const rect = containerEl.getBoundingClientRect()
    const pct = ((e.clientX - rect.left) / rect.width) * 100
    splitPercent.value = Math.min(85, Math.max(15, pct))
  }

  function stopDrag() {
    isDragging.value = false
    containerEl = null
    document.removeEventListener('mousemove', onDrag)
    document.removeEventListener('mouseup', stopDrag)
    document.body.style.cursor = ''
    document.body.style.userSelect = ''
  }

  function cycleLayout() {
    if (layout.value === 'split') {
      layout.value = 'editor-only'
    } else if (layout.value === 'editor-only') {
      layout.value = 'preview-only'
    } else {
      layout.value = 'split'
    }
  }

  function setLayout(l: PaneLayout) {
    layout.value = l
  }

  onUnmounted(() => {
    document.removeEventListener('mousemove', onDrag)
    document.removeEventListener('mouseup', stopDrag)
  })

  return {
    splitPercent,
    layout,
    isDragging,
    startDrag,
    cycleLayout,
    setLayout,
  }
}
