import { state }                                        from './state.js';
import { setStatus, showToast }                          from './ui.js';
import { renderGrid, showEmptyGrid }                     from './grid.js';
import * as history                                      from './history.js';
import { openModal, closeModal }                         from './modal.js';
import { renderTextList }                                from './utils/dom.js';

const deleteModal    = document.getElementById('delete-modal');
const deleteFileList = document.getElementById('delete-file-list');
const deleteConfirmBtn = document.getElementById('delete-confirm');
const btnRename = document.getElementById('btn-rename');

let _pendingFiles = null;

deleteModal.addEventListener('modal:closed', () => {
  _pendingFiles = null;
});

deleteConfirmBtn.addEventListener('click', async () => {
  if (!_pendingFiles) return;
  const files = _pendingFiles;
  _pendingFiles = null;
  closeModal(deleteModal);
  await _doDelete(files);
});

function showDeleteModal(files) {
  renderTextList(deleteFileList, files.map(f => f.name));
  _pendingFiles = files;
  openModal(deleteModal);
}

export function deleteSelected() {
  if (!state.selectedIdxs.size) return;
  const filesToDelete = [...state.selectedIdxs].sort((a, b) => a - b)
    .map(i => state.files[i]).filter(Boolean);
  if (filesToDelete.length) showDeleteModal(filesToDelete);
}

export function init(gridEl) {
  gridEl.addEventListener('click', (e) => {
    const btn = e.target.closest('.card-delete');
    if (!btn) return;

    const card = btn.closest('.card');
    if (!card) return;
    const idx = parseInt(card.dataset.idx);

    const filesToDelete = (state.selectedIdxs.size > 0 && state.selectedIdxs.has(idx))
      ? [...state.selectedIdxs].sort((a, b) => a - b).map(i => state.files[i]).filter(Boolean)
      : [state.files[idx]].filter(Boolean);

    if (filesToDelete.length) showDeleteModal(filesToDelete);
  });
}

async function _doDelete(files) {
  const result = await window.api.stageDeleteFiles(files.map(f => f.path));

  if (result.errors.length) {
    alert('일부 오류:\n' + result.errors.join('\n'));
  }

  const stagedSet = new Set(result.staged.map(s => s.originalPath));
  for (let i = state.files.length - 1; i >= 0; i--) {
    if (stagedSet.has(state.files[i].path)) state.files.splice(i, 1);
  }
  state.selectedIdxs.clear();

  history.pushDelete([...state.files], result.staged);

  const n = result.staged.length;
  if (!state.files.length) {
    showEmptyGrid();
    btnRename.disabled = true;
    setStatus('이미지 파일 없음', false);
  } else {
    renderGrid();
    setStatus(`${n}개 파일 삭제됨`, true);
  }
  if (n > 0) showToast(`${n}개 파일 삭제됨`, '#8b1a1a', '#ffd0d0');
}
