import { state } from './state.js';
import { showLoading, hideLoading, setStatus } from './ui.js';
import { renderGrid, showEmptyGrid } from './grid.js';
import * as history from './history.js';
import * as fileExplorer from './handlers/file-explorer.js';

export function createFolderController({
  btnRename,
  btnSortName,
  btnSortDate,
  dirPath,
  inputPrefix,
  updatePreview,
}) {
  let homeDir = null;

  async function openFolder() {
    const folder = await window.api.selectFolder();
    if (!folder) return;

    if (folder.startsWith(homeDir)) {
      await fileExplorer.loadTree(homeDir, folder);
    } else {
      await fileExplorer.loadTree(folder, folder);
    }
    await loadFolder(folder);
  }

  async function loadFolder(folder) {
    if (!folder) return;
    state.currentFolder = folder;
    dirPath.textContent = folder;
    await window.api.setLastFolder(folder);
    await fileExplorer.setSelectedPath(folder);

    showLoading('이미지 목록 불러오는 중...');
    const list = await window.api.listImages(folder);
    hideLoading();

    if (!list.length) {
      state.files.length = 0;
      state.selectedIdxs.clear();
      showEmptyGrid();
      btnRename.disabled = true;
      setStatus('이미지 파일 없음', false);
      return;
    }

    state.files.length = 0;
    state.files.push(...list);
    state.selectedIdxs.clear();
    state.sortMode = 'name';
    updateSortButtons();
    setStatus(`${state.files.length}개 파일 로드됨`, true);

    const folderName = folder.replace(/\\/g, '/').split('/').pop();
    if (folderName) inputPrefix.value = folderName;

    renderGrid();
    updatePreview();
    btnRename.disabled = false;
    history.reset();
    history.pushReorder(state.files);
  }

  async function sortFiles(mode) {
    if (!state.files.length) return;
    if (mode === 'name') state.files.sort((a, b) => a.name.localeCompare(b.name, 'ko'));
    else                 state.files.sort((a, b) => a.mtime - b.mtime);

    state.sortMode = mode;
    state.selectedIdxs.clear();
    updateSortButtons();
    await renderGrid();
    setStatus(`${mode === 'name' ? '이름순' : '날짜순'}으로 정렬됨`, true);
    history.pushReorder(state.files);
  }

  function updateSortButtons() {
    btnSortName.classList.toggle('active', state.sortMode === 'name');
    btnSortDate.classList.toggle('active', state.sortMode === 'date');
  }

  return {
    loadFolder,
    openFolder,
    setHomeDir: value => { homeDir = value; },
    sortFiles,
    updateSortButtons,
  };
}
