// public/readCSV.js
// Fetch a CSV file and render a small table into the given container.
// Usage: window.readCSV.renderCSV(containerOrId, csvUrl)

(function () {
  async function renderCSV(container, csvUrl) {
    console.log("readCSV should start");
    console.log('readCSV.renderCSV', container, csvUrl);

    const el = (typeof container === 'string') ? document.getElementById(container) : container;
    if (!el) return;
    if (!csvUrl) {
      el.innerHTML = '<em>No CSV URL provided</em>';
      return;
    }
    el.innerHTML = 'Loading CSV…';
    try {
      const res = await fetch(csvUrl, { cache: 'no-store' });
      if (!res.ok) {
        el.innerHTML = `<em>CSV not found (HTTP ${res.status})</em>`;
        return;
      }
      const text = await res.text();
      const lines = text.trim().split(/\r?\n/).filter(Boolean);
      if (!lines.length) {
        el.innerHTML = '<em>CSV is empty</em>';
        return;
      }
      const headers = lines[0].split(',').map(h => h.trim());
      // Look for id,x,y,z columns (case-insensitive)
      const lower = headers.map(h => h.toLowerCase());
      const ids = {
        id: lower.indexOf('id'),
        x: lower.indexOf('x_mm'),
        y: lower.indexOf('y_mm'),
        z: lower.indexOf('z_mm')
      };
      // If any of these are missing, show a helpful message
      if (ids.id === -1 || ids.x === -1 || ids.y === -1 || ids.z === -1) {
        el.innerHTML = `<em>CSV does not contain required columns: id, x, y, z</em> ${csvUrl}`;
        return;
      }

      // Build table
      const table = document.createElement('table');
      table.className = 'csv-table';
      const thead = table.createTHead();
      const thr = thead.insertRow();
      ['id', 'x [mm]', 'y [mm]', 'z [mm]'].forEach(h => {
        const th = document.createElement('th');
        th.textContent = h;
        thr.appendChild(th);
      });
      const tbody = table.createTBody();

      for (let i = 1; i < lines.length; i++) {
        const row = lines[i].split(',').map(c => c.trim());
        // Skip if row doesn't have enough columns
        if (row.length < headers.length) continue;
        const tr = tbody.insertRow();
        ['id', 'x', 'y', 'z'].forEach(k => {
          const td = tr.insertCell();
          td.textContent = row[ids[k]] ?? '';
        });
      }

      el.innerHTML = ''; // clear
      el.appendChild(table);
    } catch (err) {
      console.error('readCSV error', err);
      el.innerHTML = `<em>Error loading CSV</em>`;
    }
  }

  window.readCSV = { renderCSV };
})();
