export function initSalesListPage() {
  const el = {
    search:    document.getElementById("sl-search"),
    tbody:     document.getElementById("sl-tbody"),
    empty:     document.getElementById("sl-empty"),
    loading:   document.getElementById("sl-loading"),
    tarihPills: document.querySelectorAll("#sl-tarih-pills .sl-pill"),
    durumPills: document.querySelectorAll("#sl-durum-pills .sl-pill"),

    backdrop:   document.getElementById("sl-backdrop"),
    drawer:     document.getElementById("sl-drawer"),
    drawerClose: document.getElementById("sl-drawer-close"),
    drawerUrun:  document.getElementById("sl-drawer-urun"),
    drawerMusteri: document.getElementById("sl-drawer-musteri"),
    dTarih:     document.getElementById("sl-d-tarih"),
    dFiyat:     document.getElementById("sl-d-fiyat"),
    dPesinat:   document.getElementById("sl-d-pesinat"),
    dOdenen:    document.getElementById("sl-d-odened") || document.getElementById("sl-d-odenen"),
    dKalan:     document.getElementById("sl-d-kalan"),
    gecmis:     document.getElementById("sl-drawer-gecmis"),
    form:       document.getElementById("sl-drawer-form"),
    miktar:     document.getElementById("sl-miktar"),
    not:        document.getElementById("sl-not"),
    submitBtn:  document.getElementById("sl-submit-btn"),
  };

  if (!el.tbody) return;

  // dOdenen id düzeltmesi
  const dOdened = document.getElementById("sl-d-odened") || document.getElementById("sl-d-odenen");

  let state = {
    rows: [],
    filtered: [],
    sortCol: "tarih",
    sortDir: "desc",
    q: "",
    tarih: "",
    durum: "",
    activeSale: null,
    searchTimer: null,
  };

  // ---- OLAYLAR ----
  el.search?.addEventListener("input", () => {
    clearTimeout(state.searchTimer);
    state.q = el.search.value.trim();
    state.searchTimer = setTimeout(loadData, 250);
  });

  el.tarihPills.forEach(btn => {
    btn.addEventListener("click", () => {
      el.tarihPills.forEach(b => b.classList.remove("active"));
      btn.classList.add("active");
      state.tarih = btn.dataset.val;
      loadData();
    });
  });

  el.durumPills.forEach(btn => {
    btn.addEventListener("click", () => {
      el.durumPills.forEach(b => b.classList.remove("active"));
      btn.classList.add("active");
      state.durum = btn.dataset.val;
      loadData();
    });
  });

  // Sıralama: header tıklama
  document.querySelectorAll(".sl-th-sort").forEach(th => {
    th.addEventListener("click", () => {
      const col = th.dataset.col;
      if (state.sortCol === col) {
        state.sortDir = state.sortDir === "asc" ? "desc" : "asc";
      } else {
        state.sortCol = col;
        state.sortDir = col === "tarih" ? "desc" : "asc";
      }
      updateSortHeaders();
      renderTable();
    });
  });

  el.drawerClose?.addEventListener("click", closeDrawer);
  el.backdrop?.addEventListener("click", closeDrawer);
  el.submitBtn?.addEventListener("click", submitPayment);

  // ---- VERİ YÜKLEMİ ----
  async function loadData() {
    el.loading.style.display = "block";
    el.empty.style.display = "none";
    el.tbody.innerHTML = "";

    const params = new URLSearchParams();
    if (state.q)     params.set("q", state.q);
    if (state.tarih) params.set("tarih", state.tarih);
    if (state.durum) params.set("durum", state.durum);

    try {
      const res  = await fetch("/api/satislar?" + params.toString());
      state.rows = await res.json();
    } catch (_) {
      state.rows = [];
    }

    el.loading.style.display = "none";
    renderTable();
  }

  // ---- SIRA / RENDER ----
  function sortRows(rows) {
    const col = state.sortCol;
    const dir = state.sortDir === "asc" ? 1 : -1;

    return [...rows].sort((a, b) => {
      let va, vb;
      if (col === "tarih")   { va = a.tarih || ""; vb = b.tarih || ""; }
      else if (col === "musteri") { va = (a.musteri_ad || "").toLowerCase(); vb = (b.musteri_ad || "").toLowerCase(); }
      else if (col === "urun")    { va = (a.urun_ad || "").toLowerCase();    vb = (b.urun_ad || "").toLowerCase(); }
      else if (col === "fiyat")   { va = a.satis_fiyati || 0; vb = b.satis_fiyati || 0; }
      else if (col === "odenen")  { va = a.toplam_odenen || 0; vb = b.toplam_odenen || 0; }
      else if (col === "kalan")   { va = a.kalan || 0; vb = b.kalan || 0; }
      else { return 0; }

      if (va < vb) return -1 * dir;
      if (va > vb) return  1 * dir;
      return 0;
    });
  }

  function renderTable() {
    const sorted = sortRows(state.rows);

    if (!sorted.length) {
      el.empty.style.display = "block";
      el.tbody.innerHTML = "";
      return;
    }
    el.empty.style.display = "none";

    const today = new Date().toISOString().slice(0, 10);

    el.tbody.innerHTML = sorted.map(s => {
      const kapali = s.kalan <= 0.009;
      const tarihStr = fmtTarih(s.tarih);
      const isToday  = (s.tarih || "").slice(0, 10) === today;

      return `
        <tr class="sl-tr${kapali ? " kapali" : ""}" data-id="${s.id}">
          <td class="sl-td sl-td-tarih">${tarihStr}${isToday ? ' <span class="sl-badge" style="background:#e8f4d0;color:#2d6e1a;font-size:9px">Bugün</span>' : ""}</td>
          <td class="sl-td sl-td-musteri">${esc(s.musteri_ad || "—")}</td>
          <td class="sl-td sl-td-urun">${esc(s.urun_ad || "—")}</td>
          <td class="sl-td sl-td-num sl-td-fiyat">₺${fmt(s.satis_fiyati)}</td>
          <td class="sl-td sl-td-num sl-td-odenen">₺${fmt(s.toplam_odenen)}</td>
          <td class="sl-td sl-td-num sl-td-kalan${kapali ? " zero" : ""}">₺${fmt(s.kalan)}</td>
          <td class="sl-td sl-td-center">
            <span class="sl-badge ${kapali ? "kapali" : "borclu"}">${kapali ? "Kapandı" : "Borçlu"}</span>
          </td>
        </tr>`;
    }).join("");

    el.tbody.querySelectorAll(".sl-tr").forEach(tr => {
      tr.addEventListener("click", () => {
        const s = state.rows.find(x => x.id === Number(tr.dataset.id));
        if (s) openDrawer(s);
      });
    });
  }

  function updateSortHeaders() {
    document.querySelectorAll(".sl-th-sort").forEach(th => {
      th.classList.remove("asc", "desc");
      const ico = th.querySelector(".sl-sort-ico");
      if (ico) ico.textContent = "";
      if (th.dataset.col === state.sortCol) {
        th.classList.add(state.sortDir);
        if (ico) ico.textContent = state.sortDir === "asc" ? "↑" : "↓";
      }
    });
  }

  // ---- DRAWER ----
  async function openDrawer(s) {
    state.activeSale = s;

    el.drawerUrun.textContent     = s.urun_ad || "—";
    el.drawerMusteri.textContent  = s.musteri_ad || "—";
    el.dTarih.textContent         = fmtTarih(s.tarih);
    el.dFiyat.textContent         = "₺" + fmt(s.satis_fiyati);
    el.dPesinat.textContent       = "₺" + fmt(s.pesinat);
    if (dOdened) dOdened.textContent = "₺" + fmt(s.toplam_odenen);
    el.dKalan.textContent         = "₺" + fmt(s.kalan);

    el.miktar.value = "";
    el.not.value = "";
    el.submitBtn.disabled = false;

    // Ödeme geçmişini çek (canlı)
    renderGecmis(null); // loading
    const detail = await fetchSaleDetail(s.id);
    if (detail) renderGecmis(detail);

    // Kapandıysa formu gizle
    if (s.kalan <= 0.009) {
      el.form.style.display = "none";
    } else {
      el.form.style.display = "flex";
    }

    el.backdrop.style.display = "block";
    el.drawer.style.display = "flex";
    requestAnimationFrame(() => el.drawer.classList.add("open"));
    document.body.style.overflow = "hidden";
  }

  async function fetchSaleDetail(satis_id) {
    try {
      // Satışın güncel ödeme geçmişini payment servisinden al
      const res  = await fetch(`/api/odeme/musteri/${state.activeSale?.musteri_id || 0}`);
      const data = await res.json();
      return Array.isArray(data) ? data.find(x => x.id === satis_id) : null;
    } catch (_) {
      return null;
    }
  }

  function renderGecmis(s) {
    if (!s) {
      el.gecmis.innerHTML = `<div class="sl-gecmis-title">Ödeme Geçmişi</div><div class="sl-no-gecmis">Yükleniyor…</div>`;
      return;
    }

    const today = new Date().toISOString().slice(0, 10);
    const odemeler = s.odemeler || [];

    if (!odemeler.length) {
      el.gecmis.innerHTML =
        `<div class="sl-gecmis-title">Ödeme Geçmişi</div>` +
        `<div class="sl-no-gecmis">Henüz ödeme yapılmamış.</div>`;
      return;
    }

    const items = odemeler.map(o => {
      const isToday = (o.tarih || "").slice(0, 10) === today;
      return `
        <div class="sl-gecmis-item${isToday ? " sl-gecmis-bugun" : ""}">
          <div>
            <div class="sl-gecmis-tarih">
              ${fmtTarih(o.tarih)}
              ${isToday ? `<span class="sl-gecmis-bugun-badge">Bugün</span>` : ""}
            </div>
            ${o.notlar ? `<div class="sl-gecmis-not">${esc(o.notlar)}</div>` : ""}
          </div>
          <div class="sl-gecmis-miktar">+₺${fmt(o.miktar)}</div>
        </div>`;
    }).join("");

    el.gecmis.innerHTML = `<div class="sl-gecmis-title">Ödeme Geçmişi</div>${items}`;

    // Bugünkü ödemeye scroll
    const bugunEl = el.gecmis.querySelector(".sl-gecmis-bugun");
    if (bugunEl) setTimeout(() => bugunEl.scrollIntoView({ behavior: "smooth", block: "nearest" }), 100);
  }

  function closeDrawer() {
    el.drawer.classList.remove("open");
    setTimeout(() => {
      el.backdrop.style.display = "none";
      el.drawer.style.display   = "none";
    }, 220);
    document.body.style.overflow = "";
    state.activeSale = null;
  }

  async function submitPayment() {
    const s = state.activeSale;
    if (!s) return;

    const miktar = parseFloat(el.miktar.value || 0);
    if (!miktar || miktar <= 0) { window.showToast("Tutar giriniz", "err"); return; }
    if (miktar > s.kalan + 0.01) { window.showToast("Tutar kalandan fazla olamaz", "err"); return; }

    el.submitBtn.disabled = true;
    try {
      const res  = await fetch("/api/odeme/ekle", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ satis_id: s.id, miktar, notlar: el.not.value }),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) {
        window.showToast(data.hata || "Kaydedilemedi", "err");
        el.submitBtn.disabled = false;
        return;
      }
      window.showToast("Ödeme kaydedildi", "ok");

      // State güncelle
      s.kalan = data.kalan;
      s.toplam_odenen = s.satis_fiyati - data.kalan;

      // dOdenen güncelle
      if (dOdened) dOdened.textContent = "₺" + fmt(s.toplam_odenen);
      el.dKalan.textContent = "₺" + fmt(s.kalan);

      el.miktar.value = "";
      el.not.value = "";

      if (s.kalan <= 0.009) el.form.style.display = "none";

      const detail = await fetchSaleDetail(s.id);
      if (detail) renderGecmis(detail);

      el.submitBtn.disabled = false;
      loadData(); // tabloyu güncelle
      if (typeof window.loadDashboard === "function") window.loadDashboard();
    } catch (_) {
      window.showToast("Kaydedilemedi", "err");
      el.submitBtn.disabled = false;
    }
  }

  // ---- YARDIMCILAR ----
  function fmt(val) {
    return Number(val || 0).toLocaleString("tr-TR", { minimumFractionDigits: 0, maximumFractionDigits: 2 });
  }
  function fmtTarih(str) {
    if (!str) return "—";
    const d = new Date(str.replace(" ", "T"));
    if (isNaN(d)) return str.slice(0, 10);
    return d.toLocaleDateString("tr-TR", { day: "2-digit", month: "short", year: "numeric" });
  }
  function esc(v) {
    return String(v || "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  }

  // ---- BAŞLAT ----
  updateSortHeaders();
  loadData();
}