document.addEventListener('DOMContentLoaded', () => {
  const displayNameSpan = document.getElementById('display-name');
  const editIcon = document.getElementById('edit-display-name-icon');
  const editControls = document.getElementById('display-name-edit-controls');
  const displayNameInput = document.getElementById('display-name-input');
  const saveButton = document.getElementById('save-display-name-ws-button');
  const cancelButton = document.getElementById('cancel-display-name-button');

  // Get playerId from meta tag
  const displayNameMeta = document.querySelector('meta[name="displayName"]');
  const initialDisplayName = displayNameMeta
    ? displayNameMeta.content
    : 'New Player';

  // Initialize display name with initial name
  displayNameSpan.textContent = initialDisplayName;

  function setEditMode(isEditing) {
    if (isEditing) {
      displayNameSpan.style.display = 'none';
      editIcon.style.display = 'none';
      editControls.style.display = 'flex';
      displayNameInput.value = displayNameSpan.textContent;
      displayNameInput.focus();
    } else {
      displayNameSpan.style.display = 'inline';
      editIcon.style.display = 'inline';
      editControls.style.display = 'none';
    }
  }

  editIcon.addEventListener('click', () => setEditMode(true));
  cancelButton.addEventListener('click', () => setEditMode(false));

  saveButton.addEventListener('click', () => {
    // The actual sending of the message is handled by hx-trigger and send-ws-messages.js
    // We just handle the optimistic UI update here.
    const newName = displayNameInput.value.trim();
    if (newName && newName !== displayNameSpan.textContent) {
      displayNameSpan.textContent = newName; // Optimistically update display
    }
    setEditMode(false);
  });
});
