// MetLAB JS

document.addEventListener('DOMContentLoaded', () => {

  // Sidebar toggle
  const sidebar  = document.getElementById('sidebar');
  const main     = document.getElementById('main-content');
  const toggle   = document.getElementById('sidebarToggle');

  if (toggle && sidebar) {
    toggle.addEventListener('click', () => {
      if (window.innerWidth <= 768) {
        sidebar.classList.toggle('open');
      } else {
        sidebar.classList.toggle('collapsed');
        main.classList.toggle('expanded');
      }
    });
  }

  // Auto-dismiss alerts
  setTimeout(() => {
    document.querySelectorAll('.alert-success, .alert-info').forEach(el => {
      const bsAlert = bootstrap.Alert.getOrCreateInstance(el);
      bsAlert.close();
    });
  }, 4000);

  // AJAX: load equipment by company
  const compSelect = document.getElementById('company_id');
  const equipSelect = document.getElementById('equipment_id');
  const contactSelect = document.getElementById('contact_id');

  if (compSelect && equipSelect) {
    compSelect.addEventListener('change', () => {
      const cid = compSelect.value;
      if (!cid) return;
      fetch(`?page=equipment&action=index&company_id=${cid}&format=json`)
        .then(r => r.json()).then(data => {
          equipSelect.innerHTML = '<option value="">Select equipment...</option>';
          data.forEach(e => {
            equipSelect.innerHTML += `<option value="${e.equipment_id}">${e.equipment_name} (${e.serial_number})</option>`;
          });
        }).catch(() => {});
      if (contactSelect) {
        fetch(`?page=contacts&action=list&company_id=${cid}`)
          .then(r => r.json()).then(data => {
            contactSelect.innerHTML = '<option value="">Select contact (optional)...</option>';
            data.forEach(c => {
              contactSelect.innerHTML += `<option value="${c.contact_id}">${c.contact_name} - ${c.position}</option>`;
            });
          }).catch(() => {});
      }
    });
  }

  // Measurement table – add/remove rows
  const addRowBtn = document.getElementById('addMeasRow');
  const measTable = document.getElementById('measTableBody');
  let rowCount = measTable ? measTable.querySelectorAll('tr').length : 0;

  if (addRowBtn && measTable) {
    addRowBtn.addEventListener('click', () => {
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td><input type="text" name="meas_rows[${rowCount}][name]" class="form-control form-control-sm" placeholder="e.g. Repeatability"></td>
        <td><input type="number" step="any" name="meas_rows[${rowCount}][nominal]" class="form-control form-control-sm"></td>
        <td><input type="number" step="any" name="meas_rows[${rowCount}][measured]" class="form-control form-control-sm"></td>
        <td><input type="number" step="any" name="meas_rows[${rowCount}][error]" class="form-control form-control-sm"></td>
        <td><input type="number" step="any" name="meas_rows[${rowCount}][uncertainty]" class="form-control form-control-sm"></td>
        <td><input type="text" name="meas_rows[${rowCount}][unit]" class="form-control form-control-sm" placeholder="g, mm, K..."></td>
        <td><button type="button" class="btn btn-sm btn-outline-danger remove-row"><i class="bi bi-trash"></i></button></td>`;
      measTable.appendChild(tr);
      rowCount++;
      tr.querySelector('.remove-row').addEventListener('click', () => tr.remove());
    });

    // Bind existing remove buttons
    measTable.querySelectorAll('.remove-row').forEach(btn => {
      btn.addEventListener('click', () => btn.closest('tr').remove());
    });
  }

  // Reference equipment rows
  const addRefBtn = document.getElementById('addRefRow');
  const refTable  = document.getElementById('refTableBody');
  let refCount    = refTable ? refTable.querySelectorAll('tr').length : 0;

  if (addRefBtn && refTable) {
    addRefBtn.addEventListener('click', () => {
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td><input type="text" name="ref_equipment[${refCount}][name]" class="form-control form-control-sm" placeholder="Equipment name"></td>
        <td><input type="text" name="ref_equipment[${refCount}][serial]" class="form-control form-control-sm" placeholder="Serial No."></td>
        <td><input type="text" name="ref_equipment[${refCount}][cert]" class="form-control form-control-sm" placeholder="Cert. No."></td>
        <td><button type="button" class="btn btn-sm btn-outline-danger remove-ref"><i class="bi bi-trash"></i></button></td>`;
      refTable.appendChild(tr);
      refCount++;
      tr.querySelector('.remove-ref').addEventListener('click', () => tr.remove());
    });
    refTable.querySelectorAll('.remove-ref').forEach(btn => {
      btn.addEventListener('click', () => btn.closest('tr').remove());
    });
  }

  // Confirm deletes
  document.querySelectorAll('[data-confirm]').forEach(el => {
    el.addEventListener('click', e => {
      if (!confirm(el.dataset.confirm || 'Are you sure?')) e.preventDefault();
    });
  });

  // Copy cert number
  const copyBtn = document.getElementById('copyCertNum');
  if (copyBtn) {
    copyBtn.addEventListener('click', () => {
      navigator.clipboard.writeText(copyBtn.dataset.cert);
      copyBtn.textContent = 'Copied!';
      setTimeout(() => copyBtn.textContent = 'Copy', 1500);
    });
  }
});
