document.addEventListener('DOMContentLoaded', () => {
  const chrome = document.querySelector('[data-app-chrome]');
  const drawer = document.querySelector('[data-drawer]');
  const backdrop = document.querySelector('[data-drawer-backdrop]');
  const openBtn = document.querySelector('[data-menu-open]');
  const closeBtn = document.querySelector('.app-menu-close[data-menu-close]');
  const appTop = document.querySelector('[data-app-top]');

  const syncMenuTop = () => {
    if (!drawer || !appTop) return;
    const h = Math.ceil(appTop.getBoundingClientRect().height);
    drawer.style.setProperty('--app-top-h', `${h}px`);
  };

  const setMenuOpen = (open) => {
    if (!drawer) return;
    syncMenuTop();
    if (open) {
      drawer.hidden = false;
      requestAnimationFrame(() => drawer.classList.add('is-open'));
    } else {
      drawer.classList.remove('is-open');
      window.setTimeout(() => {
        if (!drawer.classList.contains('is-open')) drawer.hidden = true;
      }, 220);
    }
    if (backdrop) backdrop.hidden = !open;
    if (chrome) chrome.classList.toggle('is-menu-open', open);
    document.body.classList.toggle('is-app-menu-open', open);
    if (openBtn) {
      openBtn.hidden = !!open;
      openBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
    }
    if (closeBtn) closeBtn.hidden = !open;
  };

  openBtn?.addEventListener('click', () => setMenuOpen(true));
  closeBtn?.addEventListener('click', () => setMenuOpen(false));
  backdrop?.addEventListener('click', () => setMenuOpen(false));
  drawer?.querySelectorAll('a').forEach((a) => {
    a.addEventListener('click', () => setMenuOpen(false));
  });
  window.addEventListener('resize', syncMenuTop);

  // Admin: mobil açılır sidebar
  const adminShell = document.querySelector('[data-admin-shell]');
  const adminBackdrop = document.querySelector('[data-admin-close]');
  const openAdminNav = () => {
    if (!adminShell) return;
    adminShell.classList.add('is-nav-open');
    document.body.classList.add('admin-nav-lock');
    adminShell.querySelectorAll('[data-admin-close]').forEach((el) => {
      if (el.classList.contains('admin-backdrop')) el.hidden = false;
    });
  };
  const closeAdminNav = () => {
    if (!adminShell) return;
    adminShell.classList.remove('is-nav-open');
    document.body.classList.remove('admin-nav-lock');
    adminShell.querySelectorAll('.admin-backdrop[data-admin-close]').forEach((el) => {
      el.hidden = true;
    });
  };
  document.querySelectorAll('[data-admin-open]').forEach((btn) => {
    btn.addEventListener('click', openAdminNav);
  });
  document.querySelectorAll('[data-admin-close]').forEach((btn) => {
    btn.addEventListener('click', closeAdminNav);
  });
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') closeAdminNav();
  });

  // Üst arama: tıklayınca genişler, doğrudan yazılır
  const searchOpen = document.querySelector('[data-search-open]');
  const searchClose = document.querySelector('[data-search-close]');
  const searchInput = document.querySelector('[data-search-input]');
  const openSearch = () => {
    if (!appTop) return;
    appTop.classList.add('is-searching');
    if (searchClose) searchClose.hidden = false;
    setTimeout(() => searchInput?.focus(), 10);
  };
  const closeSearch = () => {
    if (!appTop) return;
    appTop.classList.remove('is-searching');
    if (searchClose) searchClose.hidden = true;
  };
  searchOpen?.addEventListener('click', openSearch);
  searchClose?.addEventListener('click', closeSearch);
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') closeSearch();
  });
  if (searchInput && searchInput.value.trim() !== '') {
    openSearch();
  }

  // İl -> ilçe otomatik doldurma
  const citySelect = document.querySelector('#city');
  const districtSelect = document.querySelector('#district');
  const cities = window.TURKIYE_IL_ILCE || null;
  if (citySelect && districtSelect && cities) {
    const selectedCity = citySelect.getAttribute('data-selected') || '';
    const selectedDistrict = districtSelect.getAttribute('data-selected') || '';
    const cityNames = Object.keys(cities).sort((a, b) => a.localeCompare(b, 'tr'));

    citySelect.innerHTML = '<option value="">Seçiniz</option>';
    cityNames.forEach((name) => {
      const opt = document.createElement('option');
      opt.value = name;
      opt.textContent = name;
      if (name === selectedCity) opt.selected = true;
      citySelect.appendChild(opt);
    });

    const fillDistricts = (city, keep) => {
      const list = cities[city] || [];
      districtSelect.innerHTML = '<option value="">' + (city ? 'Seçiniz' : 'Önce il seçin') + '</option>';
      list.forEach((name) => {
        const opt = document.createElement('option');
        opt.value = name;
        opt.textContent = name;
        if (keep && name === keep) opt.selected = true;
        districtSelect.appendChild(opt);
      });
    };

    fillDistricts(selectedCity, selectedDistrict);
    citySelect.addEventListener('change', () => {
      fillDistricts(citySelect.value, '');
    });
  }

  // Telefon: 0 (544) 544 45 45
  const phoneInput = document.querySelector('#phone');
  if (phoneInput) {
    const formatPhone = (raw) => {
      let d = String(raw || '').replace(/\D+/g, '');
      if (d.startsWith('90') && d.length >= 12) d = '0' + d.slice(2);
      if (d.length && !d.startsWith('0')) d = '0' + d;
      d = d.slice(0, 11);

      let out = '';
      if (d.length > 0) out = d.slice(0, 1);
      if (d.length > 1) out += ' (' + d.slice(1, Math.min(4, d.length));
      if (d.length >= 4) out += ')';
      if (d.length > 4) out += ' ' + d.slice(4, Math.min(7, d.length));
      if (d.length > 7) out += ' ' + d.slice(7, Math.min(9, d.length));
      if (d.length > 9) out += ' ' + d.slice(9, 11);
      return out;
    };

    phoneInput.value = formatPhone(phoneInput.value);
    phoneInput.addEventListener('input', () => {
      const formatted = formatPhone(phoneInput.value);
      phoneInput.value = formatted;
    });
    phoneInput.addEventListener('blur', () => {
      phoneInput.value = formatPhone(phoneInput.value);
    });
  }

  // Teslimat sihirbazı: İletişim → Adres → Özet → ödeme
  const addressWizard = document.querySelector('[data-address-wizard]');
  if (addressWizard) {
    let panel = Number(addressWizard.getAttribute('data-start-panel') || 1) || 1;
    const val = (name) => {
      const el = addressWizard.querySelector(`[name="${name}"]`);
      return el ? String(el.value || '').trim() : '';
    };
    const setText = (sel, text) => {
      const el = addressWizard.querySelector(sel);
      if (el) el.textContent = text || '—';
    };

    const fillSummary = () => {
      const first = val('first_name');
      const last = val('last_name');
      setText('[data-sum-name]', [first, last].filter(Boolean).join(' '));
      setText('[data-sum-phone]', val('phone'));
      setText('[data-sum-tc]', val('tc').replace(/\D+/g, ''));

      const parts = [];
      const neighborhood = val('neighborhood');
      const street = val('street');
      const apartment = val('apartment');
      const door = val('door_no');
      const district = val('district');
      const city = val('city');
      if (neighborhood) parts.push(neighborhood + ' Mah.');
      if (street) parts.push(street + ' Sk.');
      if (apartment) parts.push('Apt: ' + apartment);
      if (door) parts.push('No: ' + door);
      if (district) parts.push(district);
      if (city) parts.push(city);
      setText('[data-sum-address]', parts.join(', '));

      const note = val('note');
      const noteRow = addressWizard.querySelector('[data-sum-note-row]');
      if (noteRow) {
        noteRow.hidden = !note;
        setText('[data-sum-note]', note);
      }

      const price = addressWizard.getAttribute('data-product-price') || '';
      const title = addressWizard.getAttribute('data-product-title') || '';
      if (title) setText('[data-sum-product]', title);
      if (price) {
        setText('[data-sum-price]', price);
        setText('[data-sum-total]', price);
      }
    };

    const showPanel = (n) => {
      panel = n;
      addressWizard.querySelectorAll('[data-wizard-panel]').forEach((el) => {
        el.hidden = Number(el.getAttribute('data-wizard-panel')) !== n;
      });
      addressWizard.querySelectorAll('[data-wizard-sub]').forEach((el) => {
        const i = Number(el.getAttribute('data-wizard-sub'));
        el.classList.remove('is-current', 'is-done', 'is-todo');
        if (i < n) el.classList.add('is-done');
        else if (i === n) el.classList.add('is-current');
        else el.classList.add('is-todo');
      });
      if (n === 3) fillSummary();
      window.scrollTo({ top: Math.max(0, addressWizard.getBoundingClientRect().top + window.scrollY - 72), behavior: 'smooth' });
    };

    const isValidTc = (raw) => {
      const digits = String(raw || '').replace(/\D+/g, '');
      if (!/^[1-9][0-9]{10}$/.test(digits)) return false;
      if (/^(\d)\1{10}$/.test(digits)) return false;
      const d = digits.split('').map((x) => Number(x));
      const odd = d[0] + d[2] + d[4] + d[6] + d[8];
      const even = d[1] + d[3] + d[5] + d[7];
      let d10 = ((odd * 7) - even) % 10;
      if (d10 < 0) d10 += 10;
      if (d[9] !== d10) return false;
      return d[10] === (d.slice(0, 10).reduce((a, b) => a + b, 0) % 10);
    };

    const validatePanel = (n) => {
      const box = addressWizard.querySelector(`[data-wizard-panel="${n}"]`);
      if (!box) return true;
      const fields = box.querySelectorAll('input, select, textarea');
      for (const field of fields) {
        if (typeof field.checkValidity === 'function' && !field.checkValidity()) {
          field.reportValidity();
          field.focus();
          return false;
        }
      }
      const tc = box.querySelector('#tc');
      if (tc) {
        const digits = String(tc.value || '').replace(/\D+/g, '');
        if (!isValidTc(digits)) {
          tc.setCustomValidity(
            digits.length !== 11
              ? 'TC Kimlik No 11 haneli olmalı'
              : 'TC Kimlik No geçersiz görünüyor'
          );
          tc.reportValidity();
          tc.setCustomValidity('');
          tc.focus();
          return false;
        }
      }
      const phone = box.querySelector('#phone');
      if (phone) {
        const digits = String(phone.value || '').replace(/\D+/g, '');
        if (digits.length < 11) {
          phone.setCustomValidity('Geçerli bir telefon numarası gir');
          phone.reportValidity();
          phone.setCustomValidity('');
          phone.focus();
          return false;
        }
      }
      return true;
    };

    addressWizard.querySelectorAll('[data-wizard-next]').forEach((btn) => {
      btn.addEventListener('click', () => {
        const to = Number(btn.getAttribute('data-wizard-next') || 0);
        const from = panel;
        if (!validatePanel(from)) return;
        if (to) showPanel(to);
      });
    });

    addressWizard.querySelectorAll('[data-wizard-goto]').forEach((btn) => {
      btn.addEventListener('click', () => {
        const to = Number(btn.getAttribute('data-wizard-goto') || 0);
        if (to) showPanel(to);
      });
    });

    addressWizard.addEventListener('submit', (e) => {
      if (panel !== 3) {
        e.preventDefault();
        if (panel === 1 && validatePanel(1)) showPanel(2);
        else if (panel === 2 && validatePanel(2)) showPanel(3);
        return;
      }
      if (!validatePanel(1) || !validatePanel(2)) {
        e.preventDefault();
        if (!validatePanel(1)) showPanel(1);
        else showPanel(2);
      }
    });

    addressWizard.querySelector('[data-wizard-panel="1"]')?.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        addressWizard.querySelector('[data-wizard-next="2"]')?.click();
      }
    });
    addressWizard.querySelector('[data-wizard-panel="2"]')?.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && e.target && e.target.tagName !== 'TEXTAREA') {
        e.preventDefault();
        addressWizard.querySelector('[data-wizard-next="3"]')?.click();
      }
    });

    // TC: yazarken sadece rakam; blur’da algoritma uyarısı
    const tcInput = addressWizard.querySelector('#tc');
    if (tcInput) {
      tcInput.addEventListener('input', () => {
        tcInput.value = String(tcInput.value || '').replace(/\D+/g, '').slice(0, 11);
        tcInput.setCustomValidity('');
      });
      tcInput.addEventListener('blur', () => {
        const digits = String(tcInput.value || '').replace(/\D+/g, '');
        if (!digits) return;
        if (digits.length !== 11) {
          tcInput.setCustomValidity('TC Kimlik No 11 haneli olmalı');
        } else if (!isValidTc(digits)) {
          tcInput.setCustomValidity('TC Kimlik No geçersiz görünüyor');
        } else {
          tcInput.setCustomValidity('');
        }
        tcInput.reportValidity();
        if (tcInput.validity.valid) tcInput.setCustomValidity('');
      });
    }

    showPanel(panel);
  }

  document.querySelectorAll('[data-copy-link]').forEach((btn) => {
    btn.addEventListener('click', async () => {
      const url = btn.getAttribute('data-url') || '';
      const box = btn.closest('[data-share], .iban-box, .order-card, .share-box') || document;
      const feedback = box.querySelector('[data-copy-feedback]');

      try {
        await navigator.clipboard.writeText(url);
      } catch (_) {
        const input = box.querySelector('.share-input') || document.createElement('input');
        if (!input.isConnected) {
          input.value = url;
          document.body.appendChild(input);
        }
        input.select();
        document.execCommand('copy');
        if (!box.contains(input) && input.parentNode === document.body) {
          input.remove();
        }
      }

      if (feedback) {
        feedback.hidden = false;
        setTimeout(() => {
          feedback.hidden = true;
        }, 1800);
      }
    });
  });

  document.querySelectorAll('[data-native-share]').forEach((btn) => {
    btn.addEventListener('click', async () => {
      const data = {
        title: btn.getAttribute('data-title') || document.title,
        text: btn.getAttribute('data-text') || '',
        url: btn.getAttribute('data-url') || window.location.href,
      };

      if (navigator.share) {
        try {
          await navigator.share(data);
          return;
        } catch (_) {
          /* user cancelled */
        }
      }

      const copyBtn = btn.parentElement?.querySelector('[data-copy-link]');
      if (copyBtn) {
        copyBtn.click();
      }
    });
  });

  // Sitede yorum yazma kapalı (sadece admin paneli üretir)
  const yorumYazBtn = document.querySelector('#yorum-yaz-btn');
  if (yorumYazBtn) {
    yorumYazBtn.disabled = true;
    yorumYazBtn.setAttribute('aria-disabled', 'true');
    yorumYazBtn.title = 'Yorumlar yönetim panelinden eklenir';
  }
  document.querySelectorAll('[data-reply-to]').forEach((btn) => {
    btn.disabled = true;
    btn.setAttribute('aria-disabled', 'true');
    btn.title = 'Yanıt kapalı';
  });

  // Ürün galeri kaydırma + küçük resimler
  const gallery = document.querySelector('[data-gallery]');
  const track = document.querySelector('[data-gallery-track]');
  const media = gallery?.querySelector('.pm-media');
  if (gallery && track) {
    const slides = Array.from(track.querySelectorAll('img'));
    const dots = Array.from(gallery.querySelectorAll('[data-gallery-dot]'));
    const thumbs = Array.from(gallery.querySelectorAll('[data-gallery-thumb]'));
    let index = 0;
    let startX = 0;
    let deltaX = 0;
    let dragging = false;

    const goTo = (i) => {
      if (!slides.length) return;
      index = (i + slides.length) % slides.length;
      track.style.transform = 'translateX(' + (-index * 100) + '%)';
      dots.forEach((d, di) => d.classList.toggle('on', di === index));
      thumbs.forEach((t, ti) => t.classList.toggle('on', ti === index));
    };

    gallery.querySelectorAll('[data-gallery-prev]').forEach((btn) => {
      btn.addEventListener('click', () => goTo(index - 1));
    });
    gallery.querySelectorAll('[data-gallery-next]').forEach((btn) => {
      btn.addEventListener('click', () => goTo(index + 1));
    });
    dots.forEach((d) => {
      d.addEventListener('click', () => goTo(Number(d.getAttribute('data-gallery-dot') || 0)));
    });
    thumbs.forEach((t) => {
      t.addEventListener('click', () => goTo(Number(t.getAttribute('data-gallery-thumb') || 0)));
    });

    const swipeTarget = media || gallery;
    swipeTarget.addEventListener('touchstart', (e) => {
      startX = e.touches[0].clientX;
      deltaX = 0;
      dragging = true;
      track.style.transition = 'none';
    }, { passive: true });

    swipeTarget.addEventListener('touchmove', (e) => {
      if (!dragging) return;
      deltaX = e.touches[0].clientX - startX;
      const pct = (deltaX / swipeTarget.clientWidth) * 100;
      track.style.transform = 'translateX(' + (-index * 100 + pct) + '%)';
    }, { passive: true });

    swipeTarget.addEventListener('touchend', () => {
      if (!dragging) return;
      dragging = false;
      track.style.transition = '';
      if (Math.abs(deltaX) > 40) {
        goTo(deltaX < 0 ? index + 1 : index - 1);
      } else {
        goTo(index);
      }
    });

    goTo(0);
  }

  // Admin: ana / alt kategori
  const catPicker = document.querySelector('[data-category-picker]');
  if (catPicker) {
    let tree = [];
    try {
      tree = JSON.parse(catPicker.getAttribute('data-cat-tree') || '[]') || [];
    } catch (e) {
      tree = [];
    }
    const parentSel = catPicker.querySelector('[data-cat-parent]');
    const childSel = document.querySelector('[data-cat-child]');
    const slugInp = document.querySelector('[data-cat-slug]');
    const treeInp = document.querySelector('[data-cat-tree-text]');
    let initialChild = catPicker.getAttribute('data-selected-child') || childSel?.getAttribute('data-selected') || '';
    let firstSync = true;

    const syncCats = () => {
      const pid = parentSel?.value || '';
      const parent = tree.find((t) => String(t.id) === String(pid));
      const kids = parent?.children || [];
      if (childSel) {
        const prev = firstSync ? initialChild : (childSel.value || '');
        childSel.innerHTML = '<option value="">Alt kategori (opsiyonel)</option>';
        kids.forEach((k) => {
          const opt = document.createElement('option');
          opt.value = k.id;
          opt.textContent = k.name;
          if (String(k.id) === String(prev)) opt.selected = true;
          childSel.appendChild(opt);
        });
      }
      firstSync = false;
      const child = kids.find((k) => String(k.id) === String(childSel?.value || ''));
      if (slugInp) slugInp.value = child?.slug || parent?.slug || '';
      if (treeInp) {
        const parts = [];
        if (parent?.name) parts.push(parent.name);
        if (child?.name) parts.push(child.name);
        treeInp.value = parts.join(' > ');
      }
    };
    parentSel?.addEventListener('change', () => {
      initialChild = '';
      if (childSel) childSel.value = '';
      syncCats();
    });
    childSel?.addEventListener('change', syncCats);
    syncCats();
  }

  // Admin: satıcı seçince otomatik doldur (telefon = site ayarı)
  const sellerSelect = document.querySelector('[data-seller-select]');
  if (sellerSelect) {
    const syncSeller = () => {
      const opt = sellerSelect.options[sellerSelect.selectedIndex];
      const box = document.querySelector('[data-seller-preview]');
      const name = opt?.getAttribute('data-name') || '—';
      const phone = (box?.getAttribute('data-site-phone') || opt?.getAttribute('data-phone') || '').trim() || '—';
      const year = opt?.getAttribute('data-year') || '1';
      const since = opt?.getAttribute('data-since') || '';
      const rating = opt?.getAttribute('data-rating') || '5';
      const reviews = opt?.getAttribute('data-reviews') || '0';
      const likes = opt?.getAttribute('data-likes') || '0';
      const avatar = opt?.getAttribute('data-avatar') || '';
      const username = opt?.getAttribute('data-username') || '';
      const set = (sel, val) => {
        const el = document.querySelector(sel);
        if (el) el.value = val;
      };
      set('[data-seller-name-input]', name === '—' ? '' : name);
      set('[data-seller-phone-input]', phone === '—' ? '' : phone);
      set('[data-seller-year-input]', year);
      set('[data-seller-since-input]', since);
      set('[data-seller-rating-input]', rating);
      set('[data-seller-reviews-input]', reviews);
      const avatarFile = opt?.getAttribute('data-avatar-file') || '';
      set('[data-seller-avatar-input]', avatar);
      set('[data-seller-avatar-file-input]', avatarFile);
      set('[data-seller-username-input]', username);
      if (box) {
        const n = box.querySelector('[data-seller-name]');
        const p = box.querySelector('[data-seller-phone]');
        const m = box.querySelector('[data-seller-meta]');
        if (n) n.textContent = name;
        if (p) p.textContent = phone;
        if (m) m.textContent = '★ ' + rating + ' · ♡ ' + likes + ' · ' + year + '. yıl' + (since ? ' · ' + since : '');
      }
    };
    sellerSelect.addEventListener('change', syncSeller);
    syncSeller();
  }

  const commentBox = document.querySelector('[data-seed-comments]');
  if (commentBox) {
    const rows = commentBox.querySelector('[data-comment-rows]');
    const addBtn = commentBox.querySelector('[data-comment-add]');
    const randomBtn = commentBox.querySelector('[data-comment-random]');
    const form = commentBox.closest('form');
    const apiUrl = commentBox.getAttribute('data-yorum-api') || 'api-yorum.php';
    const esc = (s) => String(s || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
    const makeThread = (c = {}) => {
      const wrap = document.createElement('div');
      wrap.className = 'admin-comment-thread';
      wrap.setAttribute('data-comment-thread', '');
      wrap.innerHTML =
        '<div class="admin-feature-row">' +
          '<input type="text" name="comment_name[]" value="' + esc(c.name || '') + '" placeholder="Müşteri adı">' +
          '<input type="text" name="comment_text[]" value="' + esc(c.text || '') + '" placeholder="Soru / yorum">' +
          '<button type="button" class="admin-btn danger sm" data-comment-remove>Sil</button>' +
        '</div>' +
        '<div class="admin-feature-row admin-reply-row">' +
          '<input type="text" name="reply_name[]" value="' + esc(c.reply_name || 'Satıcı') + '" placeholder="Cevaplayan">' +
          '<input type="text" name="reply_text[]" value="' + esc(c.reply_text || '') + '" placeholder="@isim cevap...">' +
          '<span class="admin-reply-tag">Cevap</span>' +
        '</div>' +
        '<div class="admin-feature-row admin-reply-row">' +
          '<input type="text" name="followup_text[]" value="' + esc(c.followup_text || '') + '" placeholder="2. soru (opsiyonel)">' +
          '<input type="text" name="followup_reply[]" value="' + esc(c.followup_reply || '') + '" placeholder="@isim 2. cevap...">' +
          '<span class="admin-reply-tag">Devam</span>' +
        '</div>';
      return wrap;
    };
    const appendComments = (list) => {
      if (!rows) return;
      // Boş tek satır varsa kaldır, yeniler alta eklensin
      const existing = Array.from(rows.querySelectorAll('[data-comment-thread]'));
      if (existing.length === 1) {
        const textInp = existing[0].querySelector('input[name="comment_text[]"]');
        if (textInp && !String(textInp.value || '').trim()) {
          existing[0].remove();
        }
      }
      (list || []).forEach((c) => rows.appendChild(makeThread(c)));
      if (!rows.querySelector('[data-comment-thread]')) {
        rows.appendChild(makeThread());
      }
    };
    addBtn?.addEventListener('click', () => rows?.appendChild(makeThread()));
    randomBtn?.addEventListener('click', async () => {
      const title = form?.querySelector('[name="title"]')?.value?.trim() || '';
      const category = form?.querySelector('[name="category"]')?.value || '';
      const description = form?.querySelector('[name="description"]')?.value || '';
      const seller = form?.querySelector('[name="seller_name"]')?.value?.trim() || 'Satıcı';
      const sellerUsername = form?.querySelector('[name="seller_username"]')?.value?.trim() || '';
      if (!title) {
        alert('Önce ürün adını yaz, sonra rastgele yorum üret.');
        return;
      }
      const old = randomBtn.textContent;
      randomBtn.disabled = true;
      randomBtn.textContent = 'Üretiliyor…';
      try {
        const res = await fetch(apiUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ title, category, description, seller_name: seller, seller_username: sellerUsername, count: 3 }),
        });
        const data = await res.json();
        if (!data.ok) {
          alert(data.error || 'Yorum üretilemedi');
          return;
        }
        appendComments(data.comments || []);
      } catch (err) {
        alert('Yorum isteği başarısız. Sayfayı yenileyip tekrar dene.');
      } finally {
        randomBtn.disabled = false;
        randomBtn.textContent = old;
      }
    });
    commentBox.addEventListener('click', (e) => {
      const btn = e.target.closest('[data-comment-remove]');
      if (!btn || !rows) return;
      const thread = btn.closest('[data-comment-thread]');
      if (!thread) return;
      if (rows.querySelectorAll('[data-comment-thread]').length <= 1) {
        thread.querySelectorAll('input').forEach((inp) => {
          if (inp.name === 'reply_name[]') inp.value = 'Satıcı';
          else inp.value = '';
        });
        return;
      }
      thread.remove();
    });
  }

  const imageInput = document.querySelector('input[data-max-files]');
  imageInput?.addEventListener('change', () => {
    const max = Number(imageInput.getAttribute('data-max-files') || 6);
    if (imageInput.files && imageInput.files.length > max) {
      alert('En fazla ' + max + ' resim seçebilirsin.');
      imageInput.value = '';
    }
  });

  // Dekont okuma — PDF (pdf.js) + görsel OCR (Tesseract.js)
  const dekontForm = document.querySelector('[data-dekont-ocr]');
  if (dekontForm) {
    const fileInp = dekontForm.querySelector('[data-ocr-file]');
    const textInp = dekontForm.querySelector('[data-ocr-text]');
    const statusEl = dekontForm.querySelector('[data-ocr-status]');
    const submitBtn = dekontForm.querySelector('[data-ocr-submit]');
    let ocrReady = null;
    let pdfReady = null;

    const setStatus = (msg, isErr) => {
      if (!statusEl) return;
      statusEl.hidden = !msg;
      statusEl.textContent = msg || '';
      statusEl.classList.toggle('is-err', !!isErr);
    };

    const isPdfFile = (file) => {
      if (!file) return false;
      const n = (file.name || '').toLowerCase();
      return file.type === 'application/pdf' || n.endsWith('.pdf');
    };

    const loadScript = (src) => new Promise((resolve, reject) => {
      const s = document.createElement('script');
      s.src = src;
      s.async = true;
      s.onload = () => resolve();
      s.onerror = () => reject(new Error('script'));
      document.head.appendChild(s);
    });

    const loadTesseract = () => {
      if (window.Tesseract) return Promise.resolve(window.Tesseract);
      if (ocrReady) return ocrReady;
      ocrReady = loadScript('https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js')
        .then(() => {
          if (!window.Tesseract) throw new Error('Tesseract yok');
          return window.Tesseract;
        });
      return ocrReady;
    };

    const loadPdfJs = () => {
      if (window.pdfjsLib) return Promise.resolve(window.pdfjsLib);
      if (pdfReady) return pdfReady;
      pdfReady = loadScript('https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js')
        .then(() => {
          const lib = window['pdfjs-dist/build/pdf'] || window.pdfjsLib;
          if (!lib) throw new Error('pdf.js yok');
          lib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
          window.pdfjsLib = lib;
          return lib;
        });
      return pdfReady;
    };

    const extractPdfText = async (file) => {
      const pdfjs = await loadPdfJs();
      const buf = await file.arrayBuffer();
      const pdf = await pdfjs.getDocument({ data: buf }).promise;
      let text = '';
      const max = Math.min(pdf.numPages, 3);
      for (let i = 1; i <= max; i++) {
        const page = await pdf.getPage(i);
        const content = await page.getTextContent();
        text += content.items.map((it) => it.str || '').join(' ') + '\n';
      }
      return text.trim();
    };

    const pdfFirstPageBlob = async (file) => {
      const pdfjs = await loadPdfJs();
      const buf = await file.arrayBuffer();
      const pdf = await pdfjs.getDocument({ data: buf }).promise;
      const page = await pdf.getPage(1);
      const viewport = page.getViewport({ scale: 2 });
      const canvas = document.createElement('canvas');
      canvas.width = viewport.width;
      canvas.height = viewport.height;
      const ctx = canvas.getContext('2d');
      await page.render({ canvasContext: ctx, viewport }).promise;
      return await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.92));
    };

    const ocrImage = async (source) => {
      const Tesseract = await loadTesseract();
      const result = await Tesseract.recognize(source, 'tur+eng', {
        logger: (m) => {
          if (m && m.status === 'recognizing text' && typeof m.progress === 'number') {
            setStatus('Dekont okunuyor… %' + Math.round(m.progress * 100), false);
          }
        },
      });
      return (result && result.data && result.data.text) ? String(result.data.text) : '';
    };

    const runOcr = async (file) => {
      if (!file || !textInp) return '';
      dekontForm.classList.add('is-reading');
      if (submitBtn) submitBtn.disabled = true;
      try {
        let text = '';
        if (isPdfFile(file)) {
          setStatus('PDF okunuyor…', false);
          try {
            text = await extractPdfText(file);
          } catch (e) {
            text = '';
          }
          if (text.trim().length < 12) {
            setStatus('PDF taranıyor…', false);
            const blob = await pdfFirstPageBlob(file);
            if (blob) text = await ocrImage(blob);
          }
        } else {
          setStatus('Dekont okunuyor…', false);
          text = await ocrImage(file);
        }
        textInp.value = text;
        if (text.trim().length < 12) {
          setStatus('Metin okunamadı. Daha net PDF veya ekran görüntüsü dene.', true);
        } else {
          setStatus('Okundu. Gönderebilirsin.', false);
        }
        return text;
      } catch (err) {
        textInp.value = '';
        setStatus('Otomatik okuma yapılamadı; yine de gönderebilirsin.', true);
        return '';
      } finally {
        dekontForm.classList.remove('is-reading');
        if (submitBtn) submitBtn.disabled = false;
      }
    };

    fileInp?.addEventListener('change', () => {
      const file = fileInp.files && fileInp.files[0];
      if (file) runOcr(file);
      else if (textInp) textInp.value = '';
    });

    dekontForm.addEventListener('submit', async (e) => {
      const file = fileInp?.files && fileInp.files[0];
      if (!file) return;
      if (textInp && textInp.value.trim().length >= 12) return;
      e.preventDefault();
      await runOcr(file);
      dekontForm.submit();
    });
  }

  // Ödeme süresi sayacı (yuvarlak halka)
  const payTimer = document.querySelector('[data-pay-timer]');
  if (payTimer) {
    const deadline = Number(payTimer.getAttribute('data-pay-deadline') || 0) * 1000;
    const totalSec = Math.max(1, Number(payTimer.getAttribute('data-pay-total') || 1800));
    const labelActive = payTimer.getAttribute('data-pay-label-active') || 'Bu sürede havale yapıp dekont yükle';
    const labelExpired = payTimer.getAttribute('data-pay-label-expired') || 'Süre doldu — dekont artık kabul edilmiyor';
    const circ = 2 * Math.PI * 52;
    const progress = payTimer.querySelector('[data-pay-progress]');
    const clock = payTimer.querySelector('[data-pay-clock]');
    const label = payTimer.querySelector('[data-pay-label]');
    if (progress) {
      progress.style.strokeDasharray = String(circ);
    }
    const fmt = (sec) => {
      const m = Math.floor(sec / 60);
      const s = sec % 60;
      return m + ':' + String(s).padStart(2, '0');
    };
    const escapeHtml = (s) => String(s)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
    const tick = () => {
      const leftMs = deadline - Date.now();
      const leftSec = Math.max(0, Math.ceil(leftMs / 1000));
      const ratio = Math.min(1, Math.max(0, leftSec / totalSec));
      if (clock) clock.textContent = fmt(leftSec);
      if (progress) {
        progress.style.strokeDashoffset = String(circ * (1 - ratio));
      }
      if (leftSec <= 0) {
        payTimer.classList.add('is-expired');
        if (label) label.textContent = labelExpired;
        const box = document.querySelector('.dekont-box');
        if (box && !box.dataset.expiredLocked) {
          box.dataset.expiredLocked = '1';
          const t = box.getAttribute('data-expired-title') || 'Dekont yükle';
          const h = box.getAttribute('data-expired-hint') || labelExpired;
          box.innerHTML = '<h2>' + escapeHtml(t) + '</h2><p class="hint">' + escapeHtml(h) + '</p>';
        }
        return;
      }
      payTimer.classList.remove('is-expired');
      if (label) label.textContent = labelActive;
      window.setTimeout(tick, 1000);
    };
    tick();
  }

});
