const DT_LANG = {
  emptyTable: "Gösterilecek veri yok",
  info: "_TOTAL_ kayıttan _START_ - _END_ arası",
  infoEmpty: "Kayıt yok",
  infoFiltered: "(_MAX_ kayıt içinden süzüldü)",
  lengthMenu: "_MENU_ satır göster",
  loadingRecords: "Yükleniyor...",
  processing: "İşleniyor...",
  search: "Ara",
  zeroRecords: "Eşleşen kayıt bulunamadı",
  paginate: { first: "İlk", last: "Son", next: "Sonraki", previous: "Önceki" }
};

function fmtDate(v){
  if(!v) return "";
  try{
    const d=new Date(v);
    if(isNaN(d)) return v;
    const dd=String(d.getDate()).padStart(2,"0");
    const mm=String(d.getMonth()+1).padStart(2,"0");
    const yy=d.getFullYear();
    return `${dd}.${mm}.${yy}`;
  }catch(e){return v;}
}

let rows=[];
let table=null;

(function ensureTheme(){
  if (window.setTheme) {
    window.setTheme(localStorage.getItem("uyap_theme") || "dark");
  } else {
    const t = localStorage.getItem("uyap_theme") || "dark";
    document.documentElement.setAttribute("data-theme", t);
  }
})();

function exportWithButtons(headers, rows, filename = "export.xlsx", sheetName = "Export") {
  const wrapper = document.createElement("div");
  wrapper.style.position = "fixed";
  wrapper.style.left = "-9999px";
  const table = document.createElement("table");
  const id = `tmpExport_${Date.now()}`;
  table.id = id;
  wrapper.appendChild(table);
  document.body.appendChild(wrapper);

  const dt = new DataTable(`#${id}`, {
    data: rows,
    columns: headers.map(h => ({ title: h.title || h, data: h.key || h })),
    paging: false,
    searching: false,
    info: false,
    ordering: false,
    dom: "B",
    buttons: [{
      extend: "excelHtml5",
      title: sheetName,
      filename: filename.replace(/\.xlsx$/i, ""),
      exportOptions: { columns: headers.map((_, i) => i) }
    }]
  });

  dt.button(0).trigger();
  setTimeout(() => {
    try { dt.destroy(true); } catch (_) {}
    wrapper.remove();
  }, 1000);
}

(function ensureTheme(){
  if (window.setTheme) {
    window.setTheme(localStorage.getItem("uyap_theme") || "dark");
  } else {
    const t = localStorage.getItem("uyap_theme") || "dark";
    document.documentElement.setAttribute("data-theme", t);
  }
})();

function render(){
  const data = rows.map((r,idx)=>({
    index: idx+1,
    birim: r.birimAdi||"",
    dosya: r.dosyaNo||"",
    kararNo: r.kararNo||"",
    acilis: fmtDate(r.acilis),
    karar: fmtDate(r.karar),
    kapanis: fmtDate(r.kapanis),
    hakimBaskan: r.hakimBaskan||"",
    hakimUye1: r.hakimUye1||"",
    hakimUye2: r.hakimUye2||""
  }));

  if(table){
    table.clear();
    table.rows.add(data);
    table.draw();
    return;
  }

  table = new DataTable("#tblOthers",{
    data,
    columns:[
      { title:"#", data:"index", className:"mono text-end" },
      { title:"Birim", data:"birim" },
      { title:"Esas/Dosya No", data:"dosya", className:"mono" },
      { title:"Karar No", data:"kararNo", className:"mono" },
      { title:"Açılış", data:"acilis", className:"mono" },
      { title:"Karar", data:"karar", className:"mono" },
      { title:"Kapanış", data:"kapanis", className:"mono" },
      { title:"Hakim/Başkan", data:"hakimBaskan", className:"mono" },
      { title:"Üye 1", data:"hakimUye1", className:"mono" },
      { title:"Üye 2", data:"hakimUye2", className:"mono" }
    ],
    pageLength: 25,
    responsive: true,
    language: DT_LANG,
    columnDefs: [{ targets: "_all", className: "dt-center" }],
    layout:{
      topEnd: "search",
      bottomStart: "info",
      bottomEnd: "paging"
    }
  });
}

async function exportAll(){
  if(!rows.length){
    alert("İndirilecek kayıt yok.");
    return;
  }
  const headers=[
    { key:"birimAdi", title:"Birim" },
    { key:"dosyaNo", title:"Dosya No" },
    { key:"kararNo", title:"Karar No" },
    { key:"acilis", title:"Açılış" },
    { key:"karar", title:"Karar" },
    { key:"kapanis", title:"Kapanış" },
    { key:"hakimBaskan", title:"Hakim/Başkan" },
    { key:"hakimUye1", title:"Üye 1" },
    { key:"hakimUye2", title:"Üye 2" }
  ];
  const prepared = rows.map(r=>({
    birimAdi: r.birimAdi||"",
    dosyaNo: r.dosyaNo||"",
    kararNo: r.kararNo||"",
    acilis: fmtDate(r.acilis),
    karar: fmtDate(r.karar),
    kapanis: fmtDate(r.kapanis),
    hakimBaskan: r.hakimBaskan||"",
    hakimUye1: r.hakimUye1||"",
    hakimUye2: r.hakimUye2||""
  }));
  exportWithButtons(headers, prepared, "terfi-diger-dosyalar.xlsx", "Terfi");
}

document.getElementById("btnExport").addEventListener("click",exportAll);

chrome.storage.local.get("terfiOthersRows",d=>{
  rows=d.terfiOthersRows||[];
  render();
});
