/* ============================================================
   page-vendor-import.js — vendor_stockout Excel 匯入流程
   ============================================================ */
(function () {
  const dropzone = document.getElementById('stockoutDropzone');
  if (!dropzone) return;

  const fileInput = document.getElementById('stockoutFileInput');
  const filePanel = document.getElementById('stockoutFilePanel');
  const fileName = document.getElementById('stockoutFileName');
  const fileSize = document.getElementById('stockoutFileSize');
  const uploadButton = document.getElementById('stockoutUploadButton');
  const progressPanel = document.getElementById('stockoutProgressPanel');
  const resultPanel = document.getElementById('stockoutResultPanel');
  const errorPanel = document.getElementById('stockoutErrorPanel');
  const errorMessage = document.getElementById('stockoutErrorMessage');
  const importAgainButton = document.getElementById('stockoutImportAgainButton');
  let selectedFile = null;

  const show = (panel) => panel.classList.add('is-visible');
  const hide = (panel) => panel.classList.remove('is-visible');

  function resetTransientPanels() {
    hide(progressPanel);
    hide(resultPanel);
    hide(errorPanel);
  }

  function formatFileSize(bytes) {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
  }

  function handleFile(file) {
    if (!file) return;
    if (!file.name.match(/\.(xlsx|xls)$/i)) {
      errorMessage.textContent = '先選擇供應商缺貨 Excel 檔。';
      show(errorPanel);
      return;
    }
    selectedFile = file;
    fileName.textContent = file.name;
    fileSize.textContent = formatFileSize(file.size);
    resetTransientPanels();
    show(filePanel);
  }

  dropzone.addEventListener('click', () => fileInput.click());
  fileInput.addEventListener('change', (e) => handleFile(e.target.files[0]));

  dropzone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropzone.classList.add('is-dragover');
  });
  dropzone.addEventListener('dragleave', () => dropzone.classList.remove('is-dragover'));
  dropzone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropzone.classList.remove('is-dragover');
    handleFile(e.dataTransfer.files[0]);
  });

  uploadButton.addEventListener('click', async () => {
    if (!selectedFile) return;

    const formData = new FormData();
    formData.append('file', selectedFile);
    hide(filePanel);
    hide(resultPanel);
    hide(errorPanel);
    show(progressPanel);

    try {
      const response = await fetchWithCSRF('/vendor-stockout/api/import/excel', {
        method: 'POST',
        body: formData
      });
      const result = await response.json();
      hide(progressPanel);

      if (result.success) {
        document.getElementById('stockoutTotalCount').textContent = result.data.total_count;
        document.getElementById('stockoutSuccessCount').textContent = result.data.success_count;
        document.getElementById('stockoutDuplicateCount').textContent = result.data.duplicate_count;
        document.getElementById('stockoutFailedCount').textContent = result.data.failed_count;
        document.getElementById('stockoutBatchId').textContent = result.data.batch_id;
        show(resultPanel);
      } else {
        errorMessage.textContent = result.message || '匯入失敗';
        show(errorPanel);
      }
    } catch (error) {
      hide(progressPanel);
      errorMessage.textContent = '網路錯誤：' + error.message;
      show(errorPanel);
    }
  });

  importAgainButton.addEventListener('click', () => {
    selectedFile = null;
    fileInput.value = '';
    hide(filePanel);
    resetTransientPanels();
  });
})();
