import { log } from './logger.js';

export function initKeyboardShortcuts({
  btnOpen,
  btnRename,
  btnPreviewToggle,
  deleteSelected,
  performUndo,
  performRedo,
  refreshSelection,
  selectAll,
}) {
  document.addEventListener('keydown', (e) => {
    if (hasOpenModal()) return;
    const isMetaOpenOrSave = e.metaKey && (e.code === 'KeyO' || e.code === 'KeyS');
    if (isEditableTarget(e.target) && !isMetaOpenOrSave) return;

    if (e.metaKey && e.code === 'KeyO') {
      e.preventDefault();
      log('keyboard', 'Cmd+O detected', {
        target: e.target?.tagName || null,
        btnOpenDisabled: btnOpen.disabled,
      });
      btnOpen.click();
    } else if (e.metaKey && e.code === 'KeyS') {
      e.preventDefault();
      if (!btnRename.disabled) btnRename.click();
    } else if (e.code === 'KeyA') {
      selectAll();
      refreshSelection();
    } else if (e.metaKey && !e.shiftKey && e.code === 'KeyZ') {
      e.preventDefault();
      performUndo();
    } else if (e.metaKey && e.shiftKey && e.code === 'KeyZ') {
      e.preventDefault();
      performRedo();
    } else if (e.code === 'KeyP') {
      btnPreviewToggle.click();
    } else if (e.code === 'Backspace' || e.code === 'Delete') {
      deleteSelected();
    }
  });
}

function isEditableTarget(target) {
  return ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName) || target.isContentEditable;
}

function hasOpenModal() {
  return [...document.querySelectorAll('.modal-overlay')]
    .some(modal => modal.style.display === 'flex');
}
