export function initPaymentPage() {
  // Modül DOM'a inject edildikten hemen sonra çalışır.
  // document.addEventListener yerine section içindeki elemanları kullanıyoruz
  // böylece modül değiştiğinde stale listener sorun çıkarmaz.

  const el = {
    input:        document.getElementById("pay-customer-input"),
    results:      document.getElementById("pay-customer-results"),
    panel:        document.getElementById("pay-customer-panel"),
    avatar:       document.getElementById("pay-avatar"),
    name:         document.getElementById("pay-customer-name"),
    meta:         document.getElementById("pay-customer-meta"),
    profileBtn:   document.getElementById("pay-profile-btn"),
    changeBtn:    document.getElementById("pay-change-btn"),
    salesList:    document.getElementById("pay-sales-list"),

    backdrop:     document.getElementById("pay-backdrop"),
    drawer:       document.getElementById("pay-drawer"),
    drawerClose:  document.getElementById("pay-drawer-close"),
    drawerUrun:   document.getElementById("pay-drawer-urun"),
    dTarih:       document.getElementById("pay-d-tarih"),
    dFiyat:       document.getElementById("pay-d-fiyat"),
    dPesinat:     document.getElementById("pay-d-pesinat"),
    dOdenen:      document.getElementById("pay-d-odened"),
    dKalan:       document.getElementById("pay-d-kalan"),
    drawerGecmis: document.getElementById("pay-drawer-gecmis"),
    miktar:       document.getElementById("pay-miktar"),
    not:          document.getElementById("pay-not"),
    submitBtn:    document.getElementById("pay-submit-btn"),

    custBackdrop:   document.getElementById("pay-cust-backdrop"),
    custDrawer:     document.getElementById("pay-cust-drawer"),
    custClose:      document.getElementById("pay-cust-close"),
    custAvatar:     document.getElementById("pay-cust-avatar"),
    custName:       document.getElementById("pay-cust-name"),
    custMeta:       document.getElementById("pay-cust-meta"),
    custOzet:       document.getElementById("pay-cust-ozet"),
    custSatisList:  document.getElementById("pay-cust-satis-list"),
  };

  // Herhangi bir eleman eksikse hepsini logla ve dur
  const missing = Object.entries(el).filter(([k,v]) => !v).map(([k]) => k);
  if (!el.input || !el.results) {
    console.error("[payment] Eksik DOM elementleri:", missing);
    return;
  }

  let state = { customer: null, activeSale: null, searchTimer: null, acItems: [] };

  // ---- OLAYLAR ----
  el.input.addEventListener("input", onSearchInput);
  el.input.addEventListener("keydown", onSearchKeydown);
  el.input.addEventListener("focus", onSearchFocus);
  el.changeBtn?.addEventListener("click", resetCustomer);
  el.profileBtn?.addEventListener("click", openProfileDrawer);
  el.drawerClose?.addEventListener("click", closePayDrawer);
  el.backdrop?.addEventListener("click", closePayDrawer);
  el.submitBtn?.addEventListener("click", submitPayment);
  el.custClose?.addEventListener("click", closeProfileDrawer);
  el.custBackdrop?.addEventListener("click", closeProfileDrawer);

  // Dışarı tıklanınca autocomplete kapat
  // AbortController ile modül değişince listener'ı temizle
  const ctrl = new AbortController();
  document.addEventListener("click", (e) => {
    if (!el.results.contains(e.target) && e.target !== el.input) {
      hideAC();
    }
  }, { signal: ctrl.signal });

  // Modül değişince (module-root temizlenince) listener'ı iptal et
  const observer = new MutationObserver(() => {
    if (!document.getElementById("pay-customer-input")) {
      ctrl.abort();
      observer.disconnect();
    }
  });
  const root = document.getElementById("module-root");
  if (root) observer.observe(root, { childList: true });

  // ---- ARAMA ----
  function onSearchInput() {
    clearTimeout(state.searchTimer);
    const q = (el.input.value || "").trim();
    if (!q) { hideAC(); return; }
    state.searchTimer = setTimeout(() => fetchCustomers(q), 200);
  }

  function onSearchFocus() {
    const q = (el.input.value || "").trim();
    if (q && !state.customer) fetchCustomers(q);
  }

  async function fetchCustomers(q) {
    try {
      const res  = await fetch(`/api/musteriler/ara?q=${encodeURIComponent(q)}`);
      const data = await res.json();
      renderAC(Array.isArray(data) ? data.slice(0, 6) : []);
    } catch (_) {
      hideAC();
    }
  }

  function renderAC(items) {
    state.acItems = items;
    el.results.innerHTML = "";
    if (!items.length) { hideAC(); return; }

    // Fixed pozisyonu için input'un ekrandaki konumunu hesapla
    const rect = el.input.getBoundingClientRect();
    el.results.style.top    = (rect.bottom + 6) + "px";
    el.results.style.left   = rect.left + "px";
    el.results.style.width  = rect.width + "px";

    items.forEach(m => {
      const div = document.createElement("div");
      div.className = "pay-autocomplete-item";
      const sub = [m.telefon, m.tc_no ? `TC: ${m.tc_no}` : null].filter(Boolean).join(" · ");
      div.innerHTML = `<div class="pay-ac-name">${esc(m.ad_soyad)}</div>` +
                      (sub ? `<div class="pay-ac-sub">${esc(sub)}</div>` : "");
      div.addEventListener("click", () => selectCustomer(m));
      el.results.appendChild(div);
    });

    el.results.style.display = "block";
  }

  function hideAC() {
    el.results.style.display = "none";
    el.results.innerHTML = "";
    state.acItems = [];
  }

  function onSearchKeydown(e) {
    if (e.key === "Enter" && state.acItems.length) {
      selectCustomer(state.acItems[0]);
    }
  }

  // ---- MÜŞTERİ SEÇ ----
  function selectCustomer(m) {
    state.customer = m;
    hideAC();
    el.input.value    = m.ad_soyad;
    el.input.readOnly = true;

    el.avatar.textContent = initials(m.ad_soyad);
    el.name.textContent   = m.ad_soyad;
    const parts = [m.telefon, m.tc_no ? `TC: ${m.tc_no}` : null].filter(Boolean);
    el.meta.textContent = parts.join(" · ") || "Bilgi yok";

    el.panel.style.display = "flex";
    loadSales(m.id);
  }

  function resetCustomer() {
    state.customer   = null;
    state.activeSale = null;
    el.input.value    = "";
    el.input.readOnly = false;
    el.panel.style.display = "none";
    el.salesList.innerHTML = "";
    closePayDrawer();
    el.input.focus();
  }

  // ---- SATIŞ LİSTESİ ----
  async function loadSales(musteriId) {
    el.salesList.innerHTML = `<div class="pay-loading">Yükleniyor...</div>`;
    try {
      const res  = await fetch(`/api/odeme/musteri/${musteriId}`);
      const data = await res.json();
      renderSales(Array.isArray(data) ? data : []);
    } catch (_) {
      el.salesList.innerHTML = `<div class="pay-no-sales">Yüklenemedi.</div>`;
    }
  }

  function renderSales(satislar) {
    if (!satislar.length) {
      el.salesList.innerHTML = `<div class="pay-no-sales">Bu müşteriye ait satış kaydı yok.</div>`;
      return;
    }

    el.salesList.innerHTML = satislar.map(s => {
      const paid = s.kalan <= 0.009;
      return `
        <div class="pay-sale-card${paid ? " paid" : ""}" data-id="${s.id}">
          <div class="pay-sale-main">
            <div class="pay-sale-urun">${esc(s.urun_ad || "—")}</div>
            <div class="pay-sale-tarih">${fmtTarih(s.tarih)}</div>
          </div>
          <div class="pay-sale-nums">
            <div class="pay-sale-num">
              <div class="pay-sale-num-label">Ödenen</div>
              <div class="pay-sale-num-val green">₺${fmt(s.toplam_odenen)}</div>
            </div>
            <div class="pay-sale-num">
              <div class="pay-sale-num-label">Kalan</div>
              <div class="pay-sale-num-val${paid ? "" : " red"}">₺${fmt(s.kalan)}</div>
            </div>
          </div>
          ${paid ? "" : `<div class="pay-sale-arrow">›</div>`}
        </div>`;
    }).join("");

    el.salesList.querySelectorAll(".pay-sale-card:not(.paid)").forEach(card => {
      card.addEventListener("click", () => {
        const s = satislar.find(x => x.id === Number(card.dataset.id));
        if (s) openPayDrawer(s);
      });
    });
  }

  // ---- ÖDEME DRAWER ----
  function openPayDrawer(s) {
    state.activeSale = s;

    el.drawerUrun.textContent = s.urun_ad || "—";
    el.dTarih.textContent     = fmtTarih(s.tarih);
    el.dFiyat.textContent     = "₺" + fmt(s.satis_fiyati);
    el.dPesinat.textContent   = "₺" + fmt(s.ilk_pesinat);

    // dOdened null olabilir — doğrudan id'yi kullan
    const dOdened = document.getElementById("pay-d-odened");
    if (dOdened) dOdened.textContent = "₺" + fmt(s.toplam_odenen);
    el.dKalan.textContent = "₺" + fmt(s.kalan);

    renderGecmis(s);
    el.miktar.value = "";
    el.not.value    = "";
    el.submitBtn.disabled = false;

    el.backdrop.style.display = "block";
    el.drawer.style.display   = "flex";
    document.body.style.overflow = "hidden";
  }

  function renderGecmis(s) {
    if (!s.odemeler || !s.odemeler.length) {
      el.drawerGecmis.innerHTML =
        `<div class="pay-gecmis-title">Ödeme Geçmişi</div>` +
        `<div class="pay-no-gecmis">Henüz ödeme yapılmamış.</div>`;
      return;
    }
    const items = s.odemeler.map(o => `
      <div class="pay-gecmis-item">
        <div>
          <div class="pay-gecmis-tarih">${fmtTarih(o.tarih)}</div>
          ${o.notlar ? `<div class="pay-gecmis-not">${esc(o.notlar)}</div>` : ""}
        </div>
        <div class="pay-gecmis-miktar">+₺${fmt(o.miktar)}</div>
      </div>`).join("");
    el.drawerGecmis.innerHTML = `<div class="pay-gecmis-title">Ödeme Geçmişi</div>${items}`;
  }

  function closePayDrawer() {
    if (el.backdrop) el.backdrop.style.display = "none";
    if (el.drawer)   el.drawer.style.display   = "none";
    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");
      closePayDrawer();
      loadSales(state.customer.id);
      if (typeof window.loadDashboard === "function") window.loadDashboard();
    } catch (_) {
      window.showToast("Kaydedilemedi", "err");
      el.submitBtn.disabled = false;
    }
  }

  // ---- PROFİL DRAWER ----
  async function openProfileDrawer() {
    if (!state.customer) return;
    const m = state.customer;

    el.custAvatar.textContent = initials(m.ad_soyad);
    el.custName.textContent   = m.ad_soyad;
    const parts = [m.telefon, m.tc_no ? `TC: ${m.tc_no}` : null].filter(Boolean);
    el.custMeta.textContent   = parts.join(" · ") || "Bilgi yok";
    el.custOzet.innerHTML     = "";
    el.custSatisList.innerHTML = `<div class="cust-loading">Yükleniyor...</div>`;

    el.custBackdrop.style.display = "block";
    el.custDrawer.style.display   = "flex";
    // Bir frame bekle sonra open class ekle (CSS transition için)
    requestAnimationFrame(() => el.custDrawer.classList.add("open"));
    document.body.style.overflow = "hidden";

    try {
      const res  = await fetch(`/api/musteriler/${m.id}`);
      const data = await res.json();
      if (!data.ok) throw new Error();

      const oz = data.ozet;
      el.custOzet.innerHTML = `
        <div class="cust-ozet-item">
          <div class="cust-ozet-label">Toplam Satış</div>
          <div class="cust-ozet-val">₺${fmt(oz.toplam_satis)}</div>
        </div>
        <div class="cust-ozet-item">
          <div class="cust-ozet-label">Ödenen</div>
          <div class="cust-ozet-val cust-val-green">₺${fmt(oz.toplam_pesinat)}</div>
        </div>
        <div class="cust-ozet-item">
          <div class="cust-ozet-label">Kalan Borç</div>
          <div class="cust-ozet-val cust-val-red">₺${fmt(oz.toplam_kalan)}</div>
        </div>`;

      el.custSatisList.innerHTML = data.satislar.map(s => {
        const kalanClass = Number(s.kalan) > 0 ? " red" : "";
        return `
          <div class="cust-satis-card">
            <div class="cust-satis-top">
              <div class="cust-satis-urun">${esc(s.urun_ad || "—")}</div>
              <span class="cust-satis-kaynak ${s.kaynak}">${s.kaynak === "gecmis" ? "Geçmiş" : "Yeni"}</span>
              <div class="cust-satis-tarih">${fmtTarih(s.tarih)}</div>
            </div>
            <div class="cust-satis-nums">
              <div class="cust-satis-num">
                <div class="cust-satis-num-label">Satış</div>
                <div class="cust-satis-num-val">₺${fmt(s.satis_fiyati)}</div>
              </div>
              <div class="cust-satis-num">
                <div class="cust-satis-num-label">Ödenen</div>
                <div class="cust-satis-num-val">₺${fmt(s.pesinat)}</div>
              </div>
              <div class="cust-satis-num">
                <div class="cust-satis-num-label">Kalan</div>
                <div class="cust-satis-num-val${kalanClass}">₺${fmt(s.kalan)}</div>
              </div>
            </div>
            ${s.notlar ? `<div class="cust-satis-not">${esc(s.notlar)}</div>` : ""}
          </div>`;
      }).join("") || `<div class="cust-no-satis">Satış kaydı yok.</div>`;
    } catch (_) {
      el.custSatisList.innerHTML = `<div class="cust-no-satis">Bilgi yüklenemedi.</div>`;
    }
  }

  function closeProfileDrawer() {
    if (el.custDrawer)   el.custDrawer.classList.remove("open");
    setTimeout(() => {
      if (el.custBackdrop) el.custBackdrop.style.display = "none";
      if (el.custDrawer)   el.custDrawer.style.display   = "none";
    }, 220);
    document.body.style.overflow = "";
  }

  // ---- YARDIMCILAR ----
  function initials(name) {
    return (name || "?").split(" ").slice(0, 2).map(w => w[0]?.toUpperCase() || "").join("");
  }

  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;");
  }
}