<script setup lang="ts">
/**
 * Inline editable display name component.
 *
 * Shows the current display name with an edit button. When editing,
 * shows an input field with save/cancel buttons. Validates that the
 * name is not empty before saving.
 */
import { ref, watch } from 'vue'

const props = defineProps<{
  /** Current display name */
  modelValue: string
  /** Whether a save operation is in progress */
  isSaving: boolean
}>()

const emit = defineEmits<{
  /** Emitted when user saves a new name */
  'update:modelValue': [value: string]
  /** Emitted when user saves */
  save: [newName: string]
}>()

const isEditing = ref(false)
const editValue = ref('')
const validationError = ref<string | null>(null)

/** Start editing mode */
function startEdit(): void {
  editValue.value = props.modelValue
  validationError.value = null
  isEditing.value = true
}

/** Cancel editing and revert changes */
function cancelEdit(): void {
  isEditing.value = false
  editValue.value = ''
  validationError.value = null
}

/** Validate and save the new name */
function saveEdit(): void {
  const trimmed = editValue.value.trim()

  // Validation
  if (!trimmed) {
    validationError.value = 'Display name cannot be empty'
    return
  }

  if (trimmed.length < 2) {
    validationError.value = 'Display name must be at least 2 characters'
    return
  }

  if (trimmed.length > 32) {
    validationError.value = 'Display name cannot exceed 32 characters'
    return
  }

  // Clear validation and emit save
  validationError.value = null
  emit('save', trimmed)
}

/** Handle Enter key to save */
function handleKeydown(e: KeyboardEvent): void {
  if (e.key === 'Enter') {
    e.preventDefault()
    saveEdit()
  } else if (e.key === 'Escape') {
    cancelEdit()
  }
}

// Exit edit mode when save completes successfully
watch(
  () => props.modelValue,
  (newVal) => {
    if (isEditing.value && newVal === editValue.value.trim()) {
      isEditing.value = false
    }
  }
)
</script>

<template>
  <div class="flex flex-col gap-1">
    <!-- View mode -->
    <div
      v-if="!isEditing"
      class="flex items-center gap-2"
    >
      <span class="text-xl font-semibold text-white">{{ modelValue }}</span>
      <button
        class="p-1 text-gray-400 hover:text-white transition-colors"
        title="Edit display name"
        @click="startEdit"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          class="h-4 w-4"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
          />
        </svg>
      </button>
    </div>

    <!-- Edit mode -->
    <div
      v-else
      class="flex flex-col gap-2"
    >
      <div class="flex items-center gap-2">
        <input
          v-model="editValue"
          type="text"
          class="flex-1 px-3 py-2 bg-surface-light border border-gray-600 rounded-lg text-white focus:outline-none focus:border-primary"
          :class="{ 'border-red-500': validationError }"
          placeholder="Enter display name"
          maxlength="32"
          autofocus
          @keydown="handleKeydown"
        >
        <button
          class="px-3 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          :disabled="isSaving"
          @click="saveEdit"
        >
          <span v-if="isSaving">Saving...</span>
          <span v-else>Save</span>
        </button>
        <button
          class="px-3 py-2 bg-gray-700 text-gray-300 rounded-lg hover:bg-gray-600 hover:text-white transition-colors"
          :disabled="isSaving"
          @click="cancelEdit"
        >
          Cancel
        </button>
      </div>
      <p
        v-if="validationError"
        class="text-sm text-red-400"
      >
        {{ validationError }}
      </p>
      <p class="text-xs text-gray-500">
        {{ editValue.length }}/32 characters
      </p>
    </div>
  </div>
</template>
