export function initSalesPage() {
  const state = {
    selectedCustomer: null,
    selectedProduct: null,
    customerItems: [],
    productItems: [],
    customerActiveIndex: -1,
    productActiveIndex: -1
  };

  const el = {
    form: document.getElementById("sales-form"),

    customerName: document.getElementById("sales-customer-name"),
    customerResults: document.getElementById("sales-customer-results"),
    customerId: document.getElementById("sales-customer-id"),
    customerPhone: document.getElementById("sales-customer-phone"),
    customerTc: document.getElementById("sales-customer-tc"),
    customerType: document.getElementById("sales-customer-type"),

    productSearch: document.getElementById("sales-product-search"),
    productResults: document.getElementById("sales-product-results"),
    productId: document.getElementById("sales-product-id"),
    productName: document.getElementById("sales-product-name"),
    defaultPrice: document.getElementById("sales-default-price"),
    stockInfo: document.getElementById("sales-stock-info"),

    price: document.getElementById("sales-price"),
    pesinat: document.getElementById("sales-pesinat"),
    kalan: document.getElementById("sales-kalan"),
    note: document.getElementById("sales-note"),

    clearBtn: document.getElementById("sales-clear-btn"),
    historyBtn: document.getElementById("sales-history-btn"),

    gecmisModal: document.getElementById("gecmis-modal"),
    gecmisForm: document.getElementById("gecmis-form"),
    gecmisCloseBtn: document.getElementById("gecmis-close-btn"),
    gMusteri: document.getElementById("g-musteri-ad"),
    gTarih: document.getElementById("g-tarih"),
    gTelefon: document.getElementById("g-telefon"),
    gTc: document.getElementById("g-tc"),
    gUrun: document.getElementById("g-urun-ad"),
    gFiyat: document.getElementById("g-fiyat"),
    gPesinat: document.getElementById("g-pesinat"),
    gKalan: document.getElementById("g-kalan"),
    gNot: document.getElementById("g-not")
  };

  bindEvents();
  calculateKalan();

  function bindEvents() {
    el.customerName?.addEventListener("input", onCustomerInput);
    el.customerName?.addEventListener("keydown", onCustomerKeydown);

    el.productSearch?.addEventListener("input", onProductInput);
    el.productSearch?.addEventListener("keydown", onProductKeydown);

    el.price?.addEventListener("input", calculateKalan);
    el.pesinat?.addEventListener("input", calculateKalan);
    el.clearBtn?.addEventListener("click", clearForm);
    el.form?.addEventListener("submit", submitForm);

    el.customerPhone?.addEventListener("focus", onPhoneFocus);
    el.customerPhone?.addEventListener("input", onPhoneInput);
    el.customerTc?.addEventListener("input", onTcInput);

    el.historyBtn?.addEventListener("click", openGecmisModal);
    el.gecmisCloseBtn?.addEventListener("click", closeGecmisModal);
    el.gecmisModal?.addEventListener("click", (e) => {
      if (e.target === el.gecmisModal) closeGecmisModal();
    });
    el.gecmisForm?.addEventListener("submit", submitGecmis);
    el.gFiyat?.addEventListener("input", calcGecmisKalan);
    el.gPesinat?.addEventListener("input", calcGecmisKalan);
    el.gTelefon?.addEventListener("focus", onGPhoneFocus);
    el.gTelefon?.addEventListener("input", onGPhoneInput);
    el.gTc?.addEventListener("input", onGTcInput);

    document.addEventListener("click", handleOutsideClick);
  }


  function onPhoneFocus() {
    if (!el.customerPhone.value) {
      el.customerPhone.value = "+90";
    }
  }

  function onPhoneInput() {
    let val = el.customerPhone.value;
    if (!val.startsWith("+90")) val = "+90";
    const digits = val.slice(3).replace(/\D/g, "").slice(0, 10);
    el.customerPhone.value = "+90" + digits;
  }

  function onTcInput() {
    const digits = el.customerTc.value.replace(/\D/g, "").slice(0, 11);
    el.customerTc.value = digits;
  }

  function handleOutsideClick(event) {
    if (el.customerResults && !el.customerResults.contains(event.target) && event.target !== el.customerName) {
      hideCustomerList();
    }

    if (el.productResults && !el.productResults.contains(event.target) && event.target !== el.productSearch) {
      hideProductList();
    }
  }

  async function onCustomerInput() {
    const q = (el.customerName.value || "").trim();

    state.selectedCustomer = null;
    el.customerId.value = "";
    el.customerType.value = "";
    setCustomerEditable(true);

    if (!q) {
      el.customerPhone.value = "";
      el.customerTc.value = "";
      hideCustomerList();
      return;
    }

    try {
      const response = await fetch(`/api/musteriler/ara?q=${encodeURIComponent(q)}`);
      const data = await response.json();
      renderCustomerResults(Array.isArray(data) ? data.slice(0, 5) : [], q);
    } catch (_) {
      hideCustomerList();
    }
  }

  function renderCustomerResults(items, query) {
    state.customerItems = [...items, { __new__: true, ad_soyad: query }];
    state.customerActiveIndex = 0;
    el.customerResults.innerHTML = "";

    items.forEach((item, index) => {
      const row = document.createElement("div");
      row.className = "sales-autocomplete-item" + (index === state.customerActiveIndex ? " is-active" : "");
      row.innerHTML = `
        <div class="sales-autocomplete-title">${escapeHtml(item.ad_soyad || "")}</div>
        <div class="sales-autocomplete-sub">${escapeHtml(item.telefon || "Kayıtlı müşteri")}</div>
      `;
      row.addEventListener("click", () => selectExistingCustomer(item));
      el.customerResults.appendChild(row);
    });

    const newIndex = items.length;
    const newRow = document.createElement("div");
    newRow.className = "sales-autocomplete-item sales-new-option" + (newIndex === state.customerActiveIndex ? " is-active" : "");
    newRow.innerHTML = `
      <div class="sales-autocomplete-title">+ Yeni Müşteri</div>
      <div class="sales-autocomplete-sub">${escapeHtml(query)}</div>
    `;
    newRow.addEventListener("click", () => selectNewCustomer(query));
    el.customerResults.appendChild(newRow);

    showList(el.customerResults);
  }

  function onCustomerKeydown(event) {
    if (!isListVisible(el.customerResults)) return;

    if (event.key === "ArrowDown") {
      event.preventDefault();
      state.customerActiveIndex = Math.min(state.customerActiveIndex + 1, state.customerItems.length - 1);
      refreshActiveState(el.customerResults, state.customerActiveIndex);
      return;
    }

    if (event.key === "ArrowUp") {
      event.preventDefault();
      state.customerActiveIndex = Math.max(state.customerActiveIndex - 1, 0);
      refreshActiveState(el.customerResults, state.customerActiveIndex);
      return;
    }

    if (event.key === "Enter") {
      event.preventDefault();
      const item = state.customerItems[state.customerActiveIndex] || state.customerItems[0];
      if (!item) return;

      if (item.__new__) {
        selectNewCustomer(item.ad_soyad || el.customerName.value.trim());
      } else {
        selectExistingCustomer(item);
      }
    }
  }

  function selectExistingCustomer(item) {
    state.selectedCustomer = item;

    el.customerId.value = item.id || "";
    el.customerName.value = item.ad_soyad || "";
    el.customerPhone.value = item.telefon || "";
    el.customerTc.value = item.tc_no || "";
    el.customerType.value = "existing";

    setCustomerEditable(false);
    hideCustomerList();
  }

  function selectNewCustomer(name) {
    state.selectedCustomer = null;

    el.customerId.value = "";
    el.customerName.value = name || "";
    el.customerPhone.value = "";
    el.customerTc.value = "";
    el.customerType.value = "new";

    setCustomerEditable(true);
    hideCustomerList();
  }

  function setCustomerEditable(editable) {
    el.customerPhone.readOnly = !editable;
    el.customerTc.readOnly = !editable;

    el.customerPhone.classList.toggle("sales-readonly", !editable);
    el.customerTc.classList.toggle("sales-readonly", !editable);
  }

  async function onProductInput() {
    const q = (el.productSearch.value || "").trim();

    state.selectedProduct = null;
    el.productId.value = "";
    el.productName.value = "";
    el.defaultPrice.value = "";
    el.stockInfo.value = "";

    if (!q) {
      hideProductList();
      return;
    }

    try {
      const response = await fetch(`/api/urunler/ara?q=${encodeURIComponent(q)}&stokta_olan=1`);
      const data = await response.json();
      renderProductResults(Array.isArray(data) ? data : []);
    } catch (_) {
      hideProductList();
    }
  }

  function renderProductResults(items) {
    state.productItems = [...items];
    state.productActiveIndex = 0;
    el.productResults.innerHTML = "";

    if (!items.length) {
      const empty = document.createElement("div");
      empty.className = "sales-autocomplete-item";
      empty.innerHTML = `
        <div class="sales-autocomplete-title">Uygun ürün bulunamadı</div>
        <div class="sales-autocomplete-sub">Sadece stokta olan ürünler gösterilir</div>
      `;
      el.productResults.appendChild(empty);
      showList(el.productResults);
      return;
    }

    items.forEach((item, index) => {
      const row = document.createElement("div");
      row.className = "sales-autocomplete-item" + (index === state.productActiveIndex ? " is-active" : "");
      row.innerHTML = `
        <div class="sales-autocomplete-title">${escapeHtml(item.ad || "")}</div>
        <div class="sales-autocomplete-sub">Stok: ${Number(item.stok || 0)} • ₺${formatMoney(item.fiyat || 0)}</div>
      `;
      row.addEventListener("click", () => selectProduct(item));
      el.productResults.appendChild(row);
    });

    showList(el.productResults);
  }

  function onProductKeydown(event) {
    if (!isListVisible(el.productResults)) return;

    if (!state.productItems.length) {
      if (event.key === "Enter") event.preventDefault();
      return;
    }

    if (event.key === "ArrowDown") {
      event.preventDefault();
      state.productActiveIndex = Math.min(state.productActiveIndex + 1, state.productItems.length - 1);
      refreshActiveState(el.productResults, state.productActiveIndex);
      return;
    }

    if (event.key === "ArrowUp") {
      event.preventDefault();
      state.productActiveIndex = Math.max(state.productActiveIndex - 1, 0);
      refreshActiveState(el.productResults, state.productActiveIndex);
      return;
    }

    if (event.key === "Enter") {
      event.preventDefault();
      const item = state.productItems[state.productActiveIndex] || state.productItems[0];
      if (item) selectProduct(item);
    }
  }

  function selectProduct(item) {
    state.selectedProduct = item;

    el.productId.value = item.id || "";
    el.productName.value = item.ad || "";
    el.productSearch.value = item.ad || "";
    el.defaultPrice.value = "₺" + formatMoney(item.fiyat || 0);
    el.stockInfo.value = `${Number(item.stok || 0)} adet`;
    el.price.value = Number(item.fiyat || 0);

    calculateKalan();
    hideProductList();
  }

  function calculateKalan() {
    const price = Number(el.price.value || 0);
    const pesinat = Number(el.pesinat.value || 0);
    const kalan = Math.max(0, price - pesinat);
    el.kalan.value = "₺" + formatMoney(kalan);
  }

  function clearForm() {
    state.selectedCustomer = null;
    state.selectedProduct = null;
    state.customerItems = [];
    state.productItems = [];
    state.customerActiveIndex = -1;
    state.productActiveIndex = -1;

    el.form.reset();

    el.customerId.value = "";
    el.customerType.value = "";
    el.customerPhone.value = "";
    el.customerTc.value = "";

    el.productId.value = "";
    el.productName.value = "";
    el.defaultPrice.value = "";
    el.stockInfo.value = "";

    setCustomerEditable(true);
    hideCustomerList();
    hideProductList();
    calculateKalan();
  }

  async function submitForm(event) {
    event.preventDefault();

    const customerName = (el.customerName.value || "").trim();
    const customerPhone = (el.customerPhone.value || "").trim();
    const customerTc = (el.customerTc.value || "").trim();
    const productId = el.productId.value;
    const productName = (el.productName.value || "").trim();
    const satisFiyati = Number(el.price.value || 0);
    const pesinat = Number(el.pesinat.value || 0);
    const notlar = (el.note.value || "").trim();

    if (!customerName) {
      window.showToast("Müşteri gerekli", "err");
      return;
    }

    if (!productId) {
      window.showToast("Ürün seçmelisin", "err");
      return;
    }

    if (satisFiyati <= 0) {
      window.showToast("Satış fiyatı 0'dan büyük olmalı", "err");
      return;
    }

    if (pesinat < 0) {
      window.showToast("Peşinat negatif olamaz", "err");
      return;
    }

    if (pesinat > satisFiyati) {
      window.showToast("Peşinat satış fiyatını geçemez", "err");
      return;
    }

    let customerId = el.customerId.value;

    if (!customerId) {
      try {
        const customerResponse = await fetch("/api/musteriler", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            ad_soyad: customerName,
            telefon: customerPhone,
            tc_no: customerTc
          })
        });

        const customerData = await customerResponse.json();

        if (!customerResponse.ok || !customerData.ok) {
          window.showToast(customerData.hata || "Müşteri oluşturulamadı", "err");
          return;
        }

        if (customerData.id) {
          customerId = customerData.id;
        }
      } catch (_) {
        window.showToast("Müşteri oluşturulamadı", "err");
        return;
      }
    }

    try {
      const salesResponse = await fetch("/api/satislar", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          musteri_id: customerId || null,
          musteri_ad: customerName,
          urun_id: Number(productId),
          urun_ad: productName,
          satis_fiyati: satisFiyati,
          pesinat: pesinat,
          notlar: notlar
        })
      });

      const salesData = await salesResponse.json();

      if (!salesResponse.ok || !salesData.ok) {
        window.showToast(salesData.hata || "Satış kaydedilemedi", "err");
        return;
      }

      window.showToast("Satış kaydedildi", "ok");
      clearForm();
      if (typeof window.loadDashboard === "function") window.loadDashboard();
    } catch (_) {
      window.showToast("Satış kaydedilemedi", "err");
    }
  }

  function refreshActiveState(listEl, activeIndex) {
    const items = listEl.querySelectorAll(".sales-autocomplete-item");
    items.forEach((item, index) => {
      item.classList.toggle("is-active", index === activeIndex);
    });
  }

  function isListVisible(listEl) {
    return !!listEl && listEl.style.display !== "none" && listEl.innerHTML.trim() !== "";
  }

  function showList(listEl) {
    listEl.style.display = "block";
  }

  function hideCustomerList() {
    state.customerItems = [];
    state.customerActiveIndex = -1;
    el.customerResults.style.display = "none";
    el.customerResults.innerHTML = "";
  }

  function hideProductList() {
    state.productItems = [];
    state.productActiveIndex = -1;
    el.productResults.style.display = "none";
    el.productResults.innerHTML = "";
  }

  function formatMoney(value) {
    return Number(value || 0).toLocaleString("tr-TR", {
      minimumFractionDigits: 0,
      maximumFractionDigits: 2
    });
  }

  function escapeHtml(value) {
    return String(value || "")
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#39;");
  }

  // --- GEÇMİŞ MODAL ---

  function openGecmisModal() {
    // Bugünü default tarih olarak set et
    const today = new Date().toISOString().split("T")[0];
    if (el.gTarih) el.gTarih.value = today;
    if (el.gecmisModal) el.gecmisModal.style.display = "flex";
  }

  function closeGecmisModal() {
    if (el.gecmisModal) el.gecmisModal.style.display = "none";
    if (el.gecmisForm) el.gecmisForm.reset();
    if (el.gKalan) el.gKalan.value = "₺0";
  }

  function calcGecmisKalan() {
    const fiyat = Number(el.gFiyat?.value || 0);
    const pesinat = Number(el.gPesinat?.value || 0);
    const kalan = Math.max(0, fiyat - pesinat);
    if (el.gKalan) el.gKalan.value = "₺" + formatMoney(kalan);
  }

  function onGPhoneFocus() {
    if (!el.gTelefon.value) el.gTelefon.value = "+90";
  }

  function onGPhoneInput() {
    let val = el.gTelefon.value;
    if (!val.startsWith("+90")) val = "+90";
    const digits = val.slice(3).replace(/\D/g, "").slice(0, 10);
    el.gTelefon.value = "+90" + digits;
  }

  function onGTcInput() {
    const digits = el.gTc.value.replace(/\D/g, "").slice(0, 11);
    el.gTc.value = digits;
  }

  async function submitGecmis(event) {
    event.preventDefault();

    const musteri_ad = (el.gMusteri?.value || "").trim();
    const urun_ad = (el.gUrun?.value || "").trim();
    const satis_fiyati = Number(el.gFiyat?.value || 0);
    const pesinat = Number(el.gPesinat?.value || 0);
    const tarih = el.gTarih?.value || "";
    const musteri_telefon = (el.gTelefon?.value || "").trim();
    const musteri_tc = (el.gTc?.value || "").trim();
    const notlar = (el.gNot?.value || "").trim();

    if (!musteri_ad) { window.showToast("Müşteri adı gerekli", "err"); return; }
    if (!urun_ad) { window.showToast("Ürün adı gerekli", "err"); return; }
    if (satis_fiyati <= 0) { window.showToast("Satış fiyatı 0'dan büyük olmalı", "err"); return; }
    if (pesinat < 0) { window.showToast("Peşinat negatif olamaz", "err"); return; }
    if (pesinat > satis_fiyati) { window.showToast("Peşinat satış fiyatını geçemez", "err"); return; }

    try {
      const res = await fetch("/api/satislar/gecmis", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ musteri_ad, musteri_telefon, musteri_tc, urun_ad, satis_fiyati, pesinat, tarih, notlar })
      });
      const data = await res.json();
      if (!res.ok || !data.ok) { window.showToast(data.hata || "Kaydedilemedi", "err"); return; }
      window.showToast("Geçmiş işlem kaydedildi", "ok");
      closeGecmisModal();
      if (typeof window.loadDashboard === "function") window.loadDashboard();
    } catch (_) {
      window.showToast("Kaydedilemedi", "err");
    }
  }
}