import { ref } from 'vue';

export function useFormulaReferenceMode() {
  const active = ref(false);
  const pickedCell = ref<{ row: number; col: number } | null>(null);
  const caret = ref(0);

  function setCaret(pos: number) {
    caret.value = Math.max(0, pos);
  }

  function enterIfNeeded(draft: string, focused: boolean, editable: boolean) {
    if (!focused || !editable) {
      active.value = false;
      pickedCell.value = null;
      return;
    }
    const on = draft.trimStart().startsWith('=');
    active.value = on;
    if (!on) pickedCell.value = null;
  }

  function exit() {
    active.value = false;
    pickedCell.value = null;
  }

  function insertAtCaret(draft: string, text: string): string {
    const pos = caret.value;
    const next = draft.slice(0, pos) + text + draft.slice(pos);
    caret.value = pos + text.length;
    return next;
  }

  function pickCell(row: number, col: number) {
    pickedCell.value = { row, col };
  }

  return {
    active,
    pickedCell,
    caret,
    setCaret,
    enterIfNeeded,
    exit,
    insertAtCaret,
    pickCell,
  };
}
