let files = [];

document.getElementById("folderInput").addEventListener("change", e => {
  files = [...e.target.files]
    // Ignore Excel temp / lock files
    .filter(f => !f.name.startsWith("~$"));

  document.getElementById("fileCount").innerText =
    files.length ? `${files.length} Excel files loaded` : "";

  document.getElementById("status").innerHTML = "";
});

/* ============================
   MAIN ENTRY
============================ */
async function compile() {
  if (!files.length) {
    showError("No valid Excel files found (temp files ignored).");
    return;
  }

  const fields = document.getElementById("fieldInput").value
    .split("\n")
    .map(f => f.trim())
    .filter(Boolean);

  if (!fields.length) {
    showError("Please define fields to extract.");
    return;
  }

  const layout = document.querySelector("input[name=layout]:checked").value;

  try {
    const allData = await readAllFiles(fields);
    layout === "horizontal"
      ? exportHorizontal(allData, fields)
      : exportVertical(allData, fields);
  } catch (err) {
    showError(err);
  }
}

/* ============================
   READ & PARSE FILES (ROBUST)
============================ */
function readAllFiles(requiredFields) {
  return Promise.all(files.map(file => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();

      reader.onload = evt => {
        try {
          const wb = XLSX.read(evt.target.result, { type: "binary" });
          const ws = wb.Sheets[wb.SheetNames[0]];
          const rows = XLSX.utils.sheet_to_json(ws, {
            header: 1,
            defval: ""
          });

          const extracted = {};

          // Full-sheet scan
          rows.forEach(row => {
            row.forEach((cell, colIndex) => {
              if (!cell) return;

              const label = String(cell).trim();

              if (requiredFields.includes(label) && !(label in extracted)) {

                // Only take the **cell immediately to the right** as value
                const value = row[colIndex + 1] !== undefined ? row[colIndex + 1] : "";
                extracted[label] = value;
              }
            });
          });

          // Final validation: only warn if field not found at all
          requiredFields.forEach(field => {
            if (!(field in extracted)) {
              throw `Missing field "${field}" in ${file.name}`;
            }
          });

          resolve({
            name: file.name,
            data: extracted
          });

        } catch (e) {
          reject(e);
        }
      };

      reader.readAsBinaryString(file);
    });
  }));
}

/* ============================
   EXPORT: HORIZONTAL
============================ */
function exportHorizontal(allData, fields) {
  const output = [];

  const header = ["Field"];
  allData.forEach(f => header.push(f.name));
  output.push(header);

  fields.forEach(field => {
    const row = [field];
    allData.forEach(f => {
      // if field exists but value is blank -> keep blank
      row.push(f.data[field] !== undefined ? f.data[field] : "");
    });
    output.push(row);
  });

  exportExcel(output);
}

/* ============================
   EXPORT: VERTICAL
============================ */
function exportVertical(allData, fields) {
  const output = [];
  output.push(["File Name", ...fields]);

  allData.forEach(f => {
    const row = [f.name];
    fields.forEach(field => {
      row.push(f.data[field] !== undefined ? f.data[field] : "");
    });
    output.push(row);
  });

  exportExcel(output);
}

/* ============================
   EXPORT FILE
============================ */
function exportExcel(data) {
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Compiled");
  XLSX.writeFile(wb, "Compiled_Data.xlsx");
  showSuccess("Compilation completed successfully.");
}

/* ============================
   UI HELPERS
============================ */
function showError(msg) {
  document.getElementById("status").innerHTML =
    `<div class="error">${msg}</div>`;
}

function showSuccess(msg) {
  document.getElementById("status").innerHTML =
    `<div class="success">${msg}</div>`;
}
