// src/client/features/tasks/model/useTaskItemEdit.ts
// Composable for managing task item text editing state and operations
//
// FIX: Uses a local `committedText` ref so text updates appear instantly
// after editing, without waiting for the server roundtrip. The ref syncs
// with the prop value when the store eventually updates.

import { ref, watch } from 'vue';
import type { Task } from '../../../shared/api/repositories';

interface UseTaskItemEditParams {
  task: Task;
  onUpdateText: (text: string) => void;
  onAddSubtask?: () => void;
}

export function useTaskItemEdit({
  task,
  onUpdateText,
  onAddSubtask,
}: UseTaskItemEditParams) {
  const isEditing = ref(false);
  const editText = ref(task.text);

  // Local "committed" text — shows the last value we sent to the server,
  // even before the server responds. Syncs back when task.text updates.
  const committedText = ref(task.text);

  // Sync committedText when the store/prop updates (server response, external change)
  watch(() => task.text, (newText) => {
    committedText.value = newText;
  });

  // Display text: editing → editText, otherwise → committedText (optimistic)
  const displayText = () => {
    return isEditing.value ? editText.value : committedText.value;
  };

  // Start editing
  const startEdit = () => {
    isEditing.value = true;
    editText.value = committedText.value;
  };

  // Finish editing
  const finishEdit = () => {
    const trimmed = editText.value.trim();
    if (trimmed) {
      committedText.value = trimmed; // ← optimistic update, instant display
      onUpdateText(trimmed);
    }
    isEditing.value = false;
  };

  // Cancel editing
  const cancelEdit = () => {
    editText.value = committedText.value;
    isEditing.value = false;
  };

  // Handle Enter key
  const handleKeydown = (e: KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      finishEdit();
    } else if (e.key === 'Escape') {
      cancelEdit();
    }
  };

  // Handle blur
  const handleBlur = () => {
    if (editText.value.trim() !== committedText.value) {
      finishEdit();
    } else {
      cancelEdit();
    }
  };

  // Focus input when editing starts
  const inputRef = ref<HTMLInputElement>();
  const focusInput = () => {
    inputRef.value?.focus();
  };

  // Watch for editing changes to focus input
  watch(isEditing, (newVal) => {
    if (newVal) {
      setTimeout(focusInput, 0);
    }
  });

  return {
    isEditing,
    editText,
    inputRef,
    displayText,
    startEdit,
    finishEdit,
    cancelEdit,
    handleKeydown,
    handleBlur,
    focusInput,
  };
}