// Basit XLSX üretici (JSZip gerekir) - inline string, minimum parçalar, yüksek uyumluluk
// Kullanım: exportToExcel({ headers: [{ key: "field", title: "Başlık" }], rows, filename, sheetName })

(function() {
  const XML_NS    = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
  const REL_NS    = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
  const PKG_NS    = "http://schemas.openxmlformats.org/package/2006/content-types";
  const RELS_TYPE = "application/vnd.openxmlformats-package.relationships+xml";

  const escapeXml = s => String(s ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");

  function normalizeHeaders(headers) {
    return (headers || []).map(h => {
      if (typeof h === "string") return { key: h, title: h };
      return {
        key: h.key || h.data || h.field || "",
        title: h.title || h.label || h.header || h.key || h.data || ""
      };
    });
  }

  function sanitizeSheetName(name) {
    const cleaned = String(name || "Veri").replace(/[\\/:\\?\\*\\[\\]]/g, " ").trim().slice(0, 31);
    return cleaned || "Veri";
  }

  function colName(idx) {
    let name = "";
    let n = idx;
    do {
      name = String.fromCharCode(65 + (n % 26)) + name;
      n = Math.floor(n / 26) - 1;
    } while (n >= 0);
    return name;
  }

  function cellInline(v, cIdx, rIdx) {
    const coord = `${colName(cIdx)}${rIdx}`;
    const text = escapeXml(v);
    return `<c r="${coord}" t="inlineStr"><is><t xml:space="preserve">${text}</t></is></c>`;
  }

  function sheetXml(headers, rows) {
    const headerCells = headers.map((h, i) => cellInline(h, i, 1)).join("");
    let rowsXml = `<row r="1">${headerCells}</row>`;
    rows.forEach((row, rIdx) => {
      const cells = row.map((v, cIdx) => cellInline(v, cIdx, rIdx + 2)).join("");
      rowsXml += `<row r="${rIdx + 2}">${cells}</row>`;
    });
    const lastRow = rows.length + 1;
    const lastColName = colName(headers.length - 1);
    const dimension = `A1:${lastColName}${lastRow}`;
    return `<?xml version="1.0" encoding="UTF-8"?>` +
      `<worksheet xmlns="${XML_NS}" xmlns:r="${REL_NS}">` +
      `<dimension ref="${dimension}"/>` +
      `<sheetData>${rowsXml}</sheetData>` +
      `</worksheet>`;
  }

  function workbookXml(sheetName) {
    return `<?xml version="1.0" encoding="UTF-8"?>` +
      `<workbook xmlns="${XML_NS}" xmlns:r="${REL_NS}">` +
      `<sheets><sheet name="${escapeXml(sheetName)}" sheetId="1" r:id="rId1"/></sheets>` +
      `</workbook>`;
  }

  function contentTypesXml() {
    return `<?xml version="1.0" encoding="UTF-8"?>` +
      `<Types xmlns="${PKG_NS}">` +
      `<Default Extension="rels" ContentType="${RELS_TYPE}"/>` +
      `<Default Extension="xml" ContentType="application/xml"/>` +
      `<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>` +
      `<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>` +
      `</Types>`;
  }

  function rootRelsXml() {
    return `<?xml version="1.0" encoding="UTF-8"?>` +
      `<Relationships xmlns="${REL_NS}">` +
      `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>` +
      `</Relationships>`;
  }

  function workbookRelsXml() {
    return `<?xml version="1.0" encoding="UTF-8"?>` +
      `<Relationships xmlns="${REL_NS}">` +
      `<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>` +
      `</Relationships>`;
  }

  function triggerDownload(blob, filename) {
    const url = URL.createObjectURL(blob);
    const saveName = filename.endsWith(".xlsx") ? filename : `${filename}.xlsx`;
    if (typeof chrome !== "undefined" && chrome.downloads) {
      chrome.downloads.download({ url, filename: saveName, saveAs: true }, () =>
        setTimeout(() => URL.revokeObjectURL(url), 5000)
      );
    } else {
      const a = document.createElement("a");
      a.href = url;
      a.download = saveName;
      document.body.appendChild(a);
      a.click();
      a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 5000);
    }
  }

  async function exportToExcel({ headers = [], rows = [], filename = "veri.xlsx", sheetName = "Veri" } = {}) {
    if (typeof JSZip === "undefined") throw new Error("JSZip yüklü değil.");

    const cols  = normalizeHeaders(headers);
    const names = cols.map(c => c.title || c.key || "");
    const data  = (rows || []).map(row => {
      if (Array.isArray(row)) return row.map(v => v ?? "");
      return cols.map(c => (row && Object.prototype.hasOwnProperty.call(row, c.key)) ? (row[c.key] ?? "") : "");
    });

    const sheetStr = sheetXml(names, data);

    const zip = new JSZip();
    zip.file("[Content_Types].xml", contentTypesXml());
    zip.folder("_rels").file(".rels", rootRelsXml());

    const xl = zip.folder("xl");
    xl.file("workbook.xml", workbookXml(sanitizeSheetName(sheetName)));
    xl.folder("_rels").file("workbook.xml.rels", workbookRelsXml());
    xl.folder("worksheets").file("sheet1.xml", sheetStr);

    const blob = await zip.generateAsync({
      type: "blob",
      compression: "DEFLATE",
      mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    triggerDownload(blob, filename);
  }

  window.exportToExcel = exportToExcel;
})();
