export function initCustomersPage() {
  const el = {
    search: document.getElementById("cust-search"),
    list: document.getElementById("cust-list"),
    backdrop: document.getElementById("cust-backdrop"),
    drawer: document.getElementById("cust-drawer"),
    drawerClose: document.getElementById("cust-drawer-close"),
    avatar: document.getElementById("cust-avatar"),
    drawerName: document.getElementById("cust-drawer-name"),
    drawerMeta: document.getElementById("cust-drawer-meta"),
    ozetSatis: document.getElementById("cust-ozet-satis"),
    ozetPesinat: document.getElementById("cust-ozet-pesinat"),
    ozetKalan: document.getElementById("cust-ozet-kalan"),
    satisList: document.getElementById("cust-satis-list")
  };

  let searchTimer = null;

  el.search?.addEventListener("input", () => {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => doSearch(el.search.value.trim()), 250);
  });

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

  // İlk yükte tüm müşterileri getir
  doSearch("");

  async function doSearch(q) {
    try {
      const res = await fetch(`/api/musteriler/ara?q=${encodeURIComponent(q)}`);
      const data = await res.json();
      renderList(Array.isArray(data) ? data : []);
    } catch (_) {
      el.list.innerHTML = `<div class="cust-empty">Yüklenemedi.</div>`;
    }
  }

  function renderList(items) {
    if (!items.length) {
      el.list.innerHTML = `<div class="cust-empty">Sonuç bulunamadı.</div>`;
      return;
    }

    el.list.innerHTML = items.map(m => {
      const initials = getInitials(m.ad_soyad);
      const sub = [m.telefon, m.tc_no ? `TC: ${m.tc_no}` : null].filter(Boolean).join(" · ") || "Bilgi yok";
      return `
        <div class="cust-row" data-id="${m.id}">
          <div class="cust-row-avatar">${escHtml(initials)}</div>
          <div class="cust-row-info">
            <div class="cust-row-name">${escHtml(m.ad_soyad)}</div>
            <div class="cust-row-sub">${escHtml(sub)}</div>
          </div>
          <div class="cust-row-arrow">›</div>
        </div>
      `;
    }).join("");

    el.list.querySelectorAll(".cust-row").forEach(row => {
      row.addEventListener("click", () => openDrawer(Number(row.dataset.id)));
    });
  }

  async function openDrawer(id) {
    el.drawerName.textContent = "Yükleniyor...";
    el.drawerMeta.textContent = "";
    el.avatar.textContent = "";
    el.ozetSatis.textContent = "—";
    el.ozetPesinat.textContent = "—";
    el.ozetKalan.textContent = "—";
    el.satisList.innerHTML = `<div class="cust-loading">Yükleniyor...</div>`;

    el.backdrop.classList.add("open");
    el.drawer.classList.add("open");

    try {
      const res = await fetch(`/api/musteriler/${id}`);
      const data = await res.json();

      if (!data.ok) throw new Error(data.hata || "Hata");

      const m = data.musteri;
      const oz = data.ozet;

      el.avatar.textContent = getInitials(m.ad_soyad);
      el.drawerName.textContent = m.ad_soyad;

      const metaParts = [m.telefon, m.tc_no ? `TC: ${m.tc_no}` : null].filter(Boolean);
      el.drawerMeta.textContent = metaParts.join(" · ") || "Bilgi yok";

      el.ozetSatis.textContent = "₺" + fmt(oz.toplam_satis);
      el.ozetPesinat.textContent = "₺" + fmt(oz.toplam_pesinat);
      el.ozetKalan.textContent = "₺" + fmt(oz.toplam_kalan);

      renderSatisList(data.satislar);
    } catch (_) {
      el.satisList.innerHTML = `<div class="cust-no-satis">Bilgi yüklenemedi.</div>`;
    }
  }

  function renderSatisList(satislar) {
    if (!satislar.length) {
      el.satisList.innerHTML = `<div class="cust-no-satis">Henüz satış kaydı yok.</div>`;
      return;
    }

    el.satisList.innerHTML = satislar.map(s => {
      const tarihStr = formatTarih(s.tarih);
      const kalanClass = Number(s.kalan) > 0 ? " red" : "";
      const kaynakLabel = s.kaynak === "gecmis" ? "Geçmiş" : "Yeni";
      const notHtml = s.notlar ? `<div class="cust-satis-not">${escHtml(s.notlar)}</div>` : "";

      return `
        <div class="cust-satis-card">
          <div class="cust-satis-top">
            <div class="cust-satis-urun">${escHtml(s.urun_ad || "—")}</div>
            <span class="cust-satis-kaynak ${s.kaynak}">${kaynakLabel}</span>
            <div class="cust-satis-tarih">${tarihStr}</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>
          ${notHtml}
        </div>
      `;
    }).join("");
  }

  function closeDrawer() {
    el.backdrop.classList.remove("open");
    el.drawer.classList.remove("open");
  }

  function getInitials(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 formatTarih(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 escHtml(v) {
    return String(v || "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  }
}
