document.addEventListener('DOMContentLoaded', () => {
  feather.replace();

  const SwalConfirm = (title, text, onConfirm) => {
    Swal.fire({
      title,
      text,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, save it!',
      cancelButtonText: 'No, cancel'
    }).then(result => {
      if (result.isConfirmed) onConfirm();
    });
  };

  const SwalSuccess = (title, text, callback) => {
    Swal.fire({
      icon: 'success',
      title,
      text,
      confirmButtonText: 'OK'
    }).then(() => callback && callback());
  };

  const addSaveHandler = (buttonId, redirectUrl) => {
    const btn = document.getElementById(buttonId);
    if (!btn) {
      console.log(`Button with id ${buttonId} not found`);
      return;
    }

    btn.addEventListener('click', e => {
      e.preventDefault();
      console.log(`Clicked button ${buttonId}`);

      Swal.fire({
        title: 'Are you sure?',
        text: 'Do you want to save the changes?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, save it!',
        cancelButtonText: 'No, cancel'
      }).then(result => {
        if (result.isConfirmed) {
          Swal.fire({
            icon: 'success',
            title: 'Saved!',
            text: 'Your data has been saved.',
            confirmButtonText: 'OK'
          }).then(() => {
            // Redirect ke page yang kamu nak
            if (redirectUrl) {
              window.location.href = redirectUrl;
            }
          });
        }
      });
    });
  };

  // details indicator
  document.querySelectorAll('.btn-details').forEach(btn => {
    btn.addEventListener('click', () => {
      const type = btn.getAttribute('data-type');
      window.location.href = `/details/${type}`;
    });
  });

  // details achievement
  document.querySelectorAll('.btn-details-achievement').forEach(btn => {
    btn.addEventListener('click', () => {
      const type = btn.getAttribute('data-type');
      window.location.href = `/achievement-details/${type}`;
    });
  });

  // Save button handlers (next steps)
  addSaveHandler('saveModal5Btn', '/kpi-achievement-updated');
  addSaveHandler('saveModal6Btn', '/kpi-achievement-updated');
  addSaveHandler('saveBtn', '/kpi-achievement-updated');
  addSaveHandler('saveBtnSaved', '/kpi-achievement-updated');
  addSaveHandler('saveBtnStep2', '/kpi-achievement-updated');
  addSaveHandler('saveModal2Btn', '/kpi-achievement-updated');

  // Back button handlers
  backHandlers.forEach(([btnId, hideId, showId]) => {
    const btn = document.getElementById(btnId);
    if (btn) {
      btn.addEventListener('click', () => {
        document.getElementById(hideId).style.display = 'none';
        document.getElementById(showId).style.display = 'block';
      });
    }
  });

  // Back to modal from saved page
  const backToModalBtn = document.getElementById('backToModalBtn');
  if (backToModalBtn) {
    backToModalBtn.addEventListener('click', () => {
      document.getElementById('afterSavePage').style.display = 'none';
      new bootstrap.Modal(document.getElementById('detailsModal')).show();
    });
  }

  // Upload button
  const uploadBtn = document.getElementById('uploadBtn');
  if (uploadBtn) {
    uploadBtn.addEventListener('click', () => {
      new bootstrap.Modal(document.getElementById('addDocModal')).show();
    });
  }

  // Save companies button
  const saveCompaniesBtn = document.getElementById('saveCompaniesBtn');
  if (saveCompaniesBtn) {
    saveCompaniesBtn.addEventListener('click', () => {
      Swal.fire({
        title: 'Success!',
        text: 'Successfully saved.',
        icon: 'success',
        confirmButtonText: 'OK'
      });
    });
  }
});

document.getElementById('toggleSearchFilter').addEventListener('click', function () {
  const filterCard = document.getElementById('searchFilterCard');
  filterCard.classList.toggle('d-none');
});

document.addEventListener('DOMContentLoaded', () => {
  const saveDocBtn = document.getElementById('saveDocBtn');
  if (saveDocBtn) {
    saveDocBtn.addEventListener('click', () => {
      const title = document.getElementById('docTitle').value;
      const fileInput = document.getElementById('docFile');
      const file = fileInput.files[0];

      if (!title || !file) {
        Swal.fire({
          title: 'Missing Info',
          text: 'Please provide both title and file.',
          icon: 'warning',
          confirmButtonText: 'OK'
        });
        return;
      }

      // Simulasi: Tambah ke table atau console log
      const fileTableBody = document.getElementById('fileTableBody');
      const newRow = document.createElement('tr');
      newRow.innerHTML = `
        <td>-</td>
        <td>${title}</td>
        <td><span class="text-muted">Uploaded</span></td>
      `;
      fileTableBody.appendChild(newRow);

      // Optional: Clear input selepas save
      document.getElementById('docTitle').value = '';
      fileInput.value = '';

      // Papar success message
      Swal.fire({
        title: 'Uploaded!',
        text: 'Document saved successfully.',
        icon: 'success',
        confirmButtonText: 'OK'
      });
    });
  }
});

document.getElementById('docFile').addEventListener('change', function () {
  const fileNameDisplay = document.getElementById('fileName');
  fileNameDisplay.textContent = this.files.length > 0 ? this.files[0].name : 'No file uploaded';
});
