import { ref } from "vue";

type Selection = { text: string; start: number; end: number };

export function useFloatingAssist(onRequest: (sel: Selection) => void) {
  const floatingAssist = ref({ show: false, top: 0, left: 0 });
  const pendingSelection = ref<Selection | null>(null);

  function onSelectionChange(payload: Selection) {
    if (payload.text.trim().length > 0) {
      const sel = window.getSelection();
      if (sel && sel.rangeCount > 0) {
        const rect = sel.getRangeAt(0).getBoundingClientRect();
        floatingAssist.value = {
          show: true,
          top: rect.top - 44,
          left: rect.left + rect.width / 2,
        };
        pendingSelection.value = payload;
      }
    } else {
      floatingAssist.value.show = false;
      pendingSelection.value = null;
    }
  }

  function handleInlineAssist() {
    if (!pendingSelection.value) return;
    floatingAssist.value.show = false;
    onRequest(pendingSelection.value);
  }

  return { floatingAssist, onSelectionChange, handleInlineAssist };
}
