/** Shopify CDN: Minification failed

Line 20:0 Unexpected "'use strict'"
Line 24:5 Expected ":"
Line 25:5 Unexpected "("
Line 26:8 Expected ":"
Line 27:8 Expected ":"
Line 28:8 Expected ":"
Line 29:12 Expected ":"
Line 31:15 Unexpected "="
Line 32:15 Unexpected "="
Line 33:7 Expected ":"
... and 232 more hidden warnings

**/
/**
 * KAHVE KAVURMA MERKEZİ — Sipariş Wizard v6
 * Adım sırası: 1:TÜR → 2:HARMAN → 3:ÇEKİRDEK → 4:KAVURMA → 5:MİKTAR → 6:AMBALAJ
 */
'use strict';

/* ── Toast bildirimleri ── */
function kwToast(msg, type='info', duration=3500) {
  let wrap = document.getElementById('kw-toast-wrap');
  if (!wrap) {
    wrap = document.createElement('div');
    wrap.id = 'kw-toast-wrap';
    wrap.style.cssText = 'position:fixed;top:20px;right:20px;z-index:99999;display:flex;flex-direction:column;gap:8px;pointer-events:none;';
    document.body.appendChild(wrap);
  }
  const colors = { info:'#1a1208', success:'#27ae60', error:'#c0392b', warning:'#e67e22' };
  const icons  = { info:'ℹ', success:'✓', error:'✕', warning:'⚠' };
  const t = document.createElement('div');
  t.style.cssText = `background:${colors[type]};color:#fff;padding:12px 18px;border-radius:10px;font-family:'Poppins',sans-serif;font-size:13px;font-weight:500;max-width:320px;box-shadow:0 4px 20px rgba(0,0,0,.18);display:flex;align-items:center;gap:9px;pointer-events:auto;animation:kwSlideIn .2s ease;`;
  t.innerHTML = `<span style="font-size:15px;flex-shrink:0;">${icons[type]}</span><span>${msg}</span>`;
  wrap.appendChild(t);
  setTimeout(() => { t.style.animation='kwSlideOut .2s ease forwards'; setTimeout(()=>t.remove(), 200); }, duration);
}

/* ── Toast için CSS animasyonları (bir kez eklenir) ── */
if (!document.getElementById('kw-toast-style')) {
  const s = document.createElement('style');
  s.id = 'kw-toast-style';
  s.textContent = '@keyframes kwSlideIn{from{opacity:0;transform:translateX(20px)}to{opacity:1;transform:translateX(0)}}@keyframes kwSlideOut{from{opacity:1;transform:translateX(0)}to{opacity:0;transform:translateX(20px)}}';
  document.head.appendChild(s);
}

/* ── Onay dialog (confirm yerine) ── */
function kwConfirm(msg) {
  return new Promise(resolve => {
    let wrap = document.getElementById('kw-confirm-wrap');
    if (wrap) wrap.remove();
    wrap = document.createElement('div');
    wrap.id = 'kw-confirm-wrap';
    wrap.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:99998;display:flex;align-items:center;justify-content:center;';
    wrap.innerHTML = `<div style="background:#fff;border-radius:14px;padding:28px 24px;max-width:380px;width:90%;font-family:'Poppins',sans-serif;box-shadow:0 8px 40px rgba(0,0,0,.18);">
      <p style="font-size:14px;color:#1a1208;margin:0 0 20px;line-height:1.6;">${msg}</p>
      <div style="display:flex;gap:10px;justify-content:flex-end;">
        <button id="kw-confirm-no"  style="padding:9px 18px;border-radius:8px;border:1px solid #d4cfc8;background:#f5f5f5;font-family:'Poppins',sans-serif;font-size:13px;cursor:pointer;">İptal</button>
        <button id="kw-confirm-yes" style="padding:9px 18px;border-radius:8px;border:none;background:#1a1208;color:#fff;font-family:'Poppins',sans-serif;font-size:13px;cursor:pointer;">Tamam</button>
      </div>
    </div>`;
    document.body.appendChild(wrap);
    wrap.querySelector('#kw-confirm-yes').onclick = () => { wrap.remove(); resolve(true); };
    wrap.querySelector('#kw-confirm-no').onclick  = () => { wrap.remove(); resolve(false); };
  });
}

const KW_MIN = 10, KW_MAX = 100;
const KW_PKG = {
  250:  { short:'250 gr', label:'250 gr', gr:250  },
  1000: { short:'1 kg',   label:'1 kg',            gr:1000 },
  2500: { short:'2,5 kg', label:'2,5 kg',           gr:2500 },
  5000: { short:'5 kg',   label:'5 kg',             gr:5000 },
};
const KW_PKG_SIZES = [250, 1000, 2500, 5000]; // aktif paket boyutları
const KW_QTY_PRESETS = [10,20,25,40,50,60,75,80,100];

class KahveWizard {
  constructor(cfg) {
    this.cfg = cfg;
    this._s = {
      step:0, type:null, character:null,
      beans:[], roast:null, grind:null, quantityKg:10,
      pkgDesigns:{}, // {sizeGr: productTitle}
      packages:[], designType:null, logoFile:null, logoUrl:null,
    };
    this.catalog = { cekirdekler:[], ambalajlar:[] };
    this.presets = [];
    this._adv = false; this._advT = null;
    this._init();
  }

  /* ══════════════════════════════════════
     INIT
  ══════════════════════════════════════ */
  async _init() {
    // Demo ürünler kaldırıldı — Shopify'dan gerçek veriler beklenir
    document.addEventListener('click', e => this._click(e));
    document.getElementById('kw-logo-file')?.addEventListener('change', e => this._logoUpload(e));
    document.addEventListener('keydown', e => { if (this._s.step && e.key==='Escape') this._confirmClose(); });
    window.addEventListener('popstate', () => { if (this._s.step>1) { this.back(); history.pushState(null,'',''); } });
    // Sayfa kapatılırken/navigasyonda uyar — yenilemeye izin ver
    window.addEventListener('beforeunload', e => {
      if (this._s.step > 0 && !this._skipBeforeUnload) {
        // Yenileme (performanceNavigation type=1) ise uyarma
        const navType = performance?.navigation?.type;
        if (navType === 1) return; // reload
        e.preventDefault();
        e.returnValue = 'Sipariş oluşturma işleminiz kaybolacak. Çıkmak istiyor musunuz?';
      }
    });
    this._restoreState();
    // KW_PRESETS global değişkeninden tarifleri yükle (kahve-presets.js)
    if (window.KW_PRESETS?.length) this.presets = window.KW_PRESETS;
    this._loadBg();
    if (this.cfg.customerId) this._loadSavedBlends();
  }

  async _loadBg() {
    try {
      const ctrl = new AbortController();
      setTimeout(()=>ctrl.abort(), 6000);
      // Önce koleksiyon bazlı, olmadıysa tag bazlı dene
      const tryFetch = async (urls) => {
        for (const url of urls) {
          try {
            const r = await fetch(url, {signal:ctrl.signal});
            if (r.ok) { const d=await r.json(); if(d.products?.length) return d.products; }
          } catch {}
        }
        return null;
      };
      const [cData, aData] = await Promise.all([
        tryFetch([
          '/collections/yesil-cekirdekler/products.json?limit=50',
          '/collections/green-beans/products.json?limit=50',
          '/products.json?limit=50&product_type=Yeşil+Çekirdek',
        ]),
        tryFetch([
          '/collections/kahve-ambalajlari/products.json?limit=50',
          '/collections/packaging/products.json?limit=50',
          '/collections/ambalaj/products.json?limit=50',
        ]),
      ]);
      if (cData?.length) this.catalog.cekirdekler = cData.map(p=>this._mapC(p));
      if (aData?.length) this.catalog.ambalajlar  = aData.flatMap(p=>this._mapA(p));
    } catch {}
    try {
      const r=await fetch('/pages/kahve-tarifleri.json');
      if (r.ok) { const d=await r.json(); const m=d.page?.body_html?.match(/```json([\s\S]*?)```/); if(m){this.presets=JSON.parse(m[1]);} }
    } catch {}
    try {
      const r=await fetch('/apps/kahve-blend-api/presets');
      if (r.ok) { const d=await r.json(); if(d?.length) this.presets=d; }
    } catch {}
    // URL'de ?blend=ID varsa o harmanı yükle (hesap sayfasından gelinme)
    const urlBlendId = new URLSearchParams(window.location.search).get('blend');
    if (urlBlendId) {
      this._loadBlendById(parseInt(urlBlendId));
    } else if (this._doRestore()) {
      this._goStep(this._s.step);
    } else {
      this._goStep(1);
    }

    if (!this.catalog.cekirdekler.length) {
      const g = document.getElementById('kw-beans-grid');
      if (g) g.innerHTML = '<p class="kw-empty" style="grid-column:1/-1;padding:16px;">Yeşil çekirdek koleksiyonuna ulaşılamıyor. Lütfen daha sonra deneyin.</p>';
    }
    // Ambalaj stok kontrolü — her unique variant için stok çek
    this._refreshAmbalajStock();
  }

  async _refreshAmbalajStock() {
    // Her ambalaj productId için /products/{id}.json çek
    const productIds = [...new Set(this.catalog.ambalajlar.map(a => a.productId).filter(Boolean))];
    for (const pid of productIds) {
      try {
        const r = await fetch(`/products/${pid}.js`, { cache: 'no-store' });
        if (!r.ok) continue;
        const p = await r.json();
        p.variants?.forEach(v => {
          const a = this.catalog.ambalajlar.find(x => x.variantId === String(v.id));
          if (a) a.stock = v.inventory_quantity != null ? v.inventory_quantity : 9999;
        });
      } catch {}
    }
    // Ambalaj adımındaysa yenile
    if (this._s.step === 6) this._renderPkgTypeGrid();
  }

  _mapC(p) {
    const v = p.variants[0];
    // Ürün ID bazlı sabit veri tablosu (kahve-cekirdek-data.js'den gelir)
    const extra = (window.KW_CEKIRDEK_DATA || {})[String(p.id)] || {};

    // tags fallback (ileride tag eklenirse çalışır)
    const tagsRaw = Array.isArray(p.tags) ? p.tags
      : (p.tags ? String(p.tags).split(',').map(t=>t.trim()) : []);
    const tag = key => {
      const t = tagsRaw.find(x => typeof x === 'string' && x.startsWith(key+':'));
      return t ? t.slice(key.length+1).trim() : '';
    };

    const kavurmaTipi = extra.kavurmaTipi
      || (tag('kavurma') ? tag('kavurma').split(/[,;]/).map(x=>x.trim()).filter(Boolean) : null)
      || ['filtre','turk','espresso'];

    const stock = (v.inventory_quantity != null && v.inventory_quantity >= 0) ? v.inventory_quantity : 9999;

    return {
      id:         String(p.id),
      variantId:  String(v.id),
      title:      p.title,
      color:      extra.renk   || tag('renk')   || '#7D4A2A',
      tatNotlari: extra.tat    || tag('tat')    || '',
      mensei:     extra.mensei || tag('mensei') || '',
      rakim:      extra.rakim  || tag('rakim')  || '',
      proses:     extra.proses || tag('proses') || '',
      kavurmaTipi,
      stockGr:    stock * 1000,
      price:      parseFloat(v.price) || 1000,
      _isDemo:    false,
    };
  }
  _mapA(p) {
    const typeLabel = p.title;
    const img = p.images?.[0]?.src || null;
    return p.variants.map(v => {
      const sizeGr     = parseInt(v.option1) || 0;
      const designCode = (v.option2 || 'standard').toLowerCase().replace(/\s+/g,'-');
      const stock      = v.inventory_quantity != null ? v.inventory_quantity : 9999;
      return {
        variantId:    String(v.id),
        productId:    String(p.id),
        productTitle: typeLabel,
        sizeGr,
        designCode,
        img,
        stock,
        price: parseFloat(v.price) || 0,
        _isDemo: false,
      };
    });
  }

  _demoProducts() {
    this.catalog.cekirdekler=[
      {id:'eth',variantId:'eth-v',title:'Ethiopia Yirgacheffe',   color:'#7D4A2A',tatNotlari:'Bergamot · yasemin · limon',     mensei:'Gedeo Zone, Etiyopya',     rakim:'1900–2100 m',proses:'Washed',    kavurmaTipi:['filtre','espresso'],       stockGr:50*1000, price:1000,_isDemo:true}, // 50 kg stok
      {id:'col',variantId:'col-v',title:'Colombia Huila',         color:'#9B5B30',tatNotlari:'Karamel · portakal · fındık',    mensei:'Huila, Kolombiya',         rakim:'1600–1900 m',proses:'Washed',    kavurmaTipi:['filtre','turk','espresso'],stockGr:80000, price:1000,_isDemo:true},
      {id:'bra',variantId:'bra-v',title:'Brazil Cerrado',         color:'#6B3F22',tatNotlari:'Çikolata · badem · vanilya',     mensei:'Minas Gerais, Brezilya',   rakim:'1000–1250 m',proses:'Natural',   kavurmaTipi:['turk','espresso'],         stockGr:120000,price:1000,_isDemo:true},
      {id:'ken',variantId:'ken-v',title:'Kenya Nyeri AA',         color:'#8B2E0E',tatNotlari:'Frenk üzümü · domates · şarap', mensei:'Nyeri, Kenya',             rakim:'1700–2000 m',proses:'Washed',    kavurmaTipi:['filtre'],                  stockGr:30000, price:1000,_isDemo:true},
      {id:'gua',variantId:'gua-v',title:'Guatemala Huehuetenango',color:'#5C3217',tatNotlari:'Kakao · kırmızı elma · bal',     mensei:'Huehuetenango, Guatemala', rakim:'1500–2000 m',proses:'Washed',    kavurmaTipi:['filtre','turk','espresso'],stockGr:45000, price:1000,_isDemo:true},
      {id:'sum',variantId:'sum-v',title:'Sumatra Mandheling',     color:'#3A1D0C',tatNotlari:'Tütün · sedir · baharat',        mensei:'Aceh, Endonezya',          rakim:'1100–1300 m',proses:'Wet-hulled',kavurmaTipi:['turk','espresso'],         stockGr:70000, price:1000,_isDemo:true},
    ];
    this.catalog.ambalajlar=[
      {variantId:'51782248333608',productTitle:'Kraft Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950584118.png?v=1778306983',  sizeGr:250,  designCode:'siyah-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51782248366376',productTitle:'Kraft Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950584118.png?v=1778306983',  sizeGr:250,  designCode:'kraft-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51782248399144',productTitle:'Kraft Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950584118.png?v=1778306983',  sizeGr:250,  designCode:'renki',         stock:9999,price:0,_isDemo:false},
      {variantId:'51782248431912',productTitle:'Kraft Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950584118.png?v=1778306983',  sizeGr:1000, designCode:'siyah-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51782248464680',productTitle:'Kraft Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950584118.png?v=1778306983',  sizeGr:1000, designCode:'kraft-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51782248497448',productTitle:'Kraft Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950584118.png?v=1778306983',  sizeGr:1000, designCode:'renki',         stock:9999,price:0,_isDemo:false},
      {variantId:'51782248530216',productTitle:'Kraft Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950584118.png?v=1778306983',  sizeGr:2500, designCode:'siyah-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51782248562984',productTitle:'Kraft Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950584118.png?v=1778306983',  sizeGr:2500, designCode:'kraft-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51782248595752',productTitle:'Kraft Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950584118.png?v=1778306983',  sizeGr:2500, designCode:'renki',         stock:9999,price:0,_isDemo:false},
      {variantId:'51808659996968',productTitle:'Siyah Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950582632.png?v=1778307032',  sizeGr:250,  designCode:'siyah-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808660029736',productTitle:'Siyah Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950582632.png?v=1778307032',  sizeGr:250,  designCode:'kraft-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808660062504',productTitle:'Siyah Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950582632.png?v=1778307032',  sizeGr:250,  designCode:'renki',         stock:9999,price:0,_isDemo:false},
      {variantId:'51808660095272',productTitle:'Siyah Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950582632.png?v=1778307032',  sizeGr:1000, designCode:'siyah-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808660128040',productTitle:'Siyah Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950582632.png?v=1778307032',  sizeGr:1000, designCode:'kraft-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808660160808',productTitle:'Siyah Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950582632.png?v=1778307032',  sizeGr:1000, designCode:'renki',         stock:9999,price:0,_isDemo:false},
      {variantId:'51808660193576',productTitle:'Siyah Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950582632.png?v=1778307032',  sizeGr:2500, designCode:'siyah-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808660226344',productTitle:'Siyah Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950582632.png?v=1778307032',  sizeGr:2500, designCode:'kraft-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808660259112',productTitle:'Siyah Ambalaj',img:'/cdn/shop/files/magnific_create-a-photorealistic-c_2950582632.png?v=1778307032',  sizeGr:2500, designCode:'renki',         stock:9999,price:0,_isDemo:false},
      {variantId:'51808662585640',productTitle:'Renkli Ambalaj',img:'/cdn/shop/files/magnific_apply-the-uploaded-artwor_2950577584.png?v=1778307177', sizeGr:250,  designCode:'siyah-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808662618408',productTitle:'Renkli Ambalaj',img:'/cdn/shop/files/magnific_apply-the-uploaded-artwor_2950577584.png?v=1778307177', sizeGr:250,  designCode:'kraft-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808662651176',productTitle:'Renkli Ambalaj',img:'/cdn/shop/files/magnific_apply-the-uploaded-artwor_2950577584.png?v=1778307177', sizeGr:250,  designCode:'renki',         stock:9999,price:0,_isDemo:false},
      {variantId:'51808662683944',productTitle:'Renkli Ambalaj',img:'/cdn/shop/files/magnific_apply-the-uploaded-artwor_2950577584.png?v=1778307177', sizeGr:1000, designCode:'siyah-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808662716712',productTitle:'Renkli Ambalaj',img:'/cdn/shop/files/magnific_apply-the-uploaded-artwor_2950577584.png?v=1778307177', sizeGr:1000, designCode:'kraft-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808662749480',productTitle:'Renkli Ambalaj',img:'/cdn/shop/files/magnific_apply-the-uploaded-artwor_2950577584.png?v=1778307177', sizeGr:1000, designCode:'renki',         stock:9999,price:0,_isDemo:false},
      {variantId:'51808662782248',productTitle:'Renkli Ambalaj',img:'/cdn/shop/files/magnific_apply-the-uploaded-artwor_2950577584.png?v=1778307177', sizeGr:2500, designCode:'siyah-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808662815016',productTitle:'Renkli Ambalaj',img:'/cdn/shop/files/magnific_apply-the-uploaded-artwor_2950577584.png?v=1778307177', sizeGr:2500, designCode:'kraft-klasik',  stock:9999,price:0,_isDemo:false},
      {variantId:'51808662847784',productTitle:'Renkli Ambalaj',img:'/cdn/shop/files/magnific_apply-the-uploaded-artwor_2950577584.png?v=1778307177', sizeGr:2500, designCode:'renki',         stock:9999,price:0,_isDemo:false},
      {variantId:'51808664158504',productTitle:'Siyah Transparan',img:'/cdn/shop/files/magnific_minimal-studio-product-mo_2950648107.png?v=1778307954',sizeGr:250,  designCode:'siyah-klasik', stock:9999,price:0,_isDemo:false},
      {variantId:'51808664191272',productTitle:'Siyah Transparan',img:'/cdn/shop/files/magnific_minimal-studio-product-mo_2950648107.png?v=1778307954',sizeGr:250,  designCode:'kraft-klasik', stock:9999,price:0,_isDemo:false},
      {variantId:'51808664224040',productTitle:'Siyah Transparan',img:'/cdn/shop/files/magnific_minimal-studio-product-mo_2950648107.png?v=1778307954',sizeGr:250,  designCode:'renki',        stock:9999,price:0,_isDemo:false},
      {variantId:'51808664256808',productTitle:'Siyah Transparan',img:'/cdn/shop/files/magnific_minimal-studio-product-mo_2950648107.png?v=1778307954',sizeGr:1000, designCode:'siyah-klasik', stock:9999,price:0,_isDemo:false},
      {variantId:'51808664289576',productTitle:'Siyah Transparan',img:'/cdn/shop/files/magnific_minimal-studio-product-mo_2950648107.png?v=1778307954',sizeGr:1000, designCode:'kraft-klasik', stock:9999,price:0,_isDemo:false},
      {variantId:'51808664322344',productTitle:'Siyah Transparan',img:'/cdn/shop/files/magnific_minimal-studio-product-mo_2950648107.png?v=1778307954',sizeGr:1000, designCode:'renki',        stock:9999,price:0,_isDemo:false},
      {variantId:'51808664355112',productTitle:'Siyah Transparan',img:'/cdn/shop/files/magnific_minimal-studio-product-mo_2950648107.png?v=1778307954',sizeGr:2500, designCode:'siyah-klasik', stock:9999,price:0,_isDemo:false},
      {variantId:'51808664387880',productTitle:'Siyah Transparan',img:'/cdn/shop/files/magnific_minimal-studio-product-mo_2950648107.png?v=1778307954',sizeGr:2500, designCode:'kraft-klasik', stock:9999,price:0,_isDemo:false},
      {variantId:'51808664420648',productTitle:'Siyah Transparan',img:'/cdn/shop/files/magnific_minimal-studio-product-mo_2950648107.png?v=1778307954',sizeGr:2500, designCode:'renki',        stock:9999,price:0,_isDemo:false},
    ];
  }

  _demoPresets() {
    this.presets=[
      {id:'espresso-classic',title:'Espresso Classic',     desc:'Brazil %60 + Sumatra %40 · Full City',   type:'espresso',character:'blend', roast:'full-city',beans:[{id:'bra',ratio:60},{id:'sum',ratio:40}]},
      {id:'ethiopia-light',  title:'Ethiopia Light Filter',desc:'Ethiopia Yirgacheffe %100 · Light',        type:'filtre',  character:'single',roast:'light',    beans:[{id:'eth',ratio:100}]},
      {id:'turk-klasik',     title:'Türk Klasik',          desc:'Colombia %70 + Brazil %30 · Dark',         type:'turk',    character:'blend', roast:'dark',     beans:[{id:'col',ratio:70},{id:'bra',ratio:30}]},
      {id:'kenya-single',    title:'Kenya Nyeri Single',   desc:'Kenya Nyeri AA %100 · Medium',             type:'filtre',  character:'single',roast:'medium',   beans:[{id:'ken',ratio:100}]},
      {id:'guatemala-filter',title:'Guatemala Filtre',     desc:'Guatemala Huehuetenango %100 · Light',     type:'filtre',  character:'single',roast:'light',    beans:[{id:'gua',ratio:100}]},
      {id:'col-sum',         title:'Colombia & Sumatra',   desc:'Colombia %60 + Sumatra %40 · Full City',   type:'turk',    character:'blend', roast:'full-city',beans:[{id:'col',ratio:60},{id:'sum',ratio:40}]},
    ];
  }

  /* ══════════════════════════════════════
     STATE KAYDET/GERİ YÜKLEö
  ══════════════════════════════════════ */
  _save() {
    const s = this._s;
    try {
      sessionStorage.setItem('kw_state', JSON.stringify({
        step:       s.step,
        type:       s.type,
        character:  s.character,
        roast:      s.roast,
        quantityKg: s.quantityKg,
        packages:   s.packages,
        designType: s.designType,
        beans:      s.beans.map(b => ({ id: b.id, ratio: b.ratio })),
      }));
    } catch(e) {}
  }

  _restoreState() {
    // Catalog yüklenmeden restore etme — _loadBg biter sonra çağrılır
    // Eski key temizle
    sessionStorage.removeItem('kw_v6');
  }

  _doRestore() {
    try {
      const raw = sessionStorage.getItem('kw_state');
      if (!raw) return false;
      const sv = JSON.parse(raw);
      if (!sv || !sv.step || sv.step < 1) return false;

      // Beans'i catalog'dan yeniden eşle
      sv.beans = (sv.beans || []).map(b => {
        const f = this.catalog.cekirdekler.find(c => c.id === b.id);
        return f ? { ...f, ratio: b.ratio } : null;
      }).filter(Boolean);

      Object.assign(this._s, sv);
      return true;
    } catch(e) { return false; }
  }

  async _confirmClose() {
    if (this._s.step>1) { this.back(); return; }
    const ok = await kwConfirm('Sipariş oluşturmayı iptal etmek istiyor musunuz?<br><small>Yaptığınız seçimler kaybolacak.</small>');
    if (ok) this.close();
  }

  /* ══════════════════════════════════════
     WİZARD AKIŞI
  ══════════════════════════════════════ */
  start() {
    Object.assign(this._s,{step:0,type:null,character:null,beans:[],roast:null,quantityKg:10,packages:[],designType:null,logoFile:null,logoUrl:null});
    this._adv=false; clearTimeout(this._advT);
    document.getElementById('kw-overlay').style.display='block';
    document.getElementById('kw-close').style.display='flex';
    history.pushState(null,'','');
    this._goStep(1);
  }

  close() {
    document.getElementById('kw-overlay').style.display='none';
    document.getElementById('kw-close').style.display='none';

    this._adv=false; clearTimeout(this._advT);
  }

  async _resetAll() {
    const ok = await kwConfirm('Tüm seçimler silinecek ve 1. adıma döneceksiniz.<br>Emin misiniz?');
    if (!ok) return;
    sessionStorage.removeItem('kw_state');
    sessionStorage.removeItem('kw_v6');
    Object.assign(this._s, {
      step:0, type:null, character:null, beans:[], roast:null, grind:null,
      quantityKg:10, pkgDesigns:{}, packages:[], designType:null, logoFile:null, logoUrl:null
    });
    this._adv=false; clearTimeout(this._advT);
    this._clearLogo();
    this._goStep(1);
  }

  next() { if (this._valid()) this._goStep(this._s.step+1); }
  back() { this._s.step<=1?this._confirmClose():this._goStep(this._s.step-1); }

  _goStep(n) {
    if (n>this.cfg.totalSteps) return;
    this._adv=false; clearTimeout(this._advT);
    document.querySelectorAll('.kw-step').forEach(el=>{ el.style.display=el.dataset.stepPanel==n?'block':'none'; });
    document.getElementById('kw-progress-fill').style.width=((n-1)/this.cfg.totalSteps*100)+'%';
    document.querySelectorAll('.kw-step-nav__item').forEach(el=>{
      const s=parseInt(el.dataset.step);
      el.classList.toggle('active',s===n); el.classList.toggle('done',s<n); el.classList.toggle('pending',s>n);
      // Nav etiketleri Liquid'de statik — override yok
    });
    // Adım başlığını lang'dan güncelle
    const L = window.KW_LANG?.steps?.[n];
    if (L) {
      const panel = document.querySelector(`[data-step-panel="${n}"]`);
      if (panel) {
        const ey = panel.querySelector('.kw-step__eyebrow');
        const ti = panel.querySelector('.kw-step__title');
        const de = panel.querySelector('.kw-step__desc'); // tüm desc'ler
        if (ey) ey.textContent = L.eyebrow || ey.textContent;
        if (ti) ti.textContent = L.title   || ti.textContent;
        if (de) de.textContent = L.desc    || de.textContent;
      }
    }
    this._s.step=n; this._save();
    if (n===2) this._renderStep2();
    if (n===3) this._renderBeans();
    if (n===4) this._renderRoast();
    if (n===5) this._renderKg();
    if (n===6) this._renderPkgStep();
    if (n===7) this._renderAmbalajStep();
    if (n===8) this._renderPreview();
    this._navBtns(); this._summary();
    document.getElementById('kw-overlay').scrollTo({top:0,behavior:'smooth'});
  }

  _valid() {
    const s=this._s;
    switch(s.step){
      case 1: return !!s.type;
      case 2: return !!s.character;
      case 3: return this._beansOk();
      case 4: return !!s.roast && !!s.grind;
      case 5: return s.quantityKg>=KW_MIN&&s.quantityKg<=KW_MAX;
      case 6: return this._pkgsOk();
      case 7: return this._pkgDesignsOk();
      case 8: return !!this._s.designType;
      default: return true;
    }
  }

  _beansOk() {
    const s=this._s; if(!s.character) return false;
    if (s.character==='single') return s.beans.length===1;
    return s.beans.length>=2&&s.beans.length<=3&&s.beans.reduce((a,b)=>a+b.ratio,0)===100;
  }

  _pkgDesignsOk() {
    const s = this._s;
    const activeSizes = (s.packages||[]).filter(p=>p.count>0).map(p=>p.sizeGr);
    if (!activeSizes.length) return false;
    return activeSizes.every(sz => !!s.pkgDesigns[sz]);
  }

  _pkgsOk() {
    const s=this._s; if(!s.packages?.length) return false;
    const total=s.packages.reduce((a,p)=>a+p.sizeGr*p.count,0);
    return Math.abs(total-s.quantityKg*1000)<1;
  }

  /* Auto-advance 180ms */
  _advance(ms=180) {
    if (this._adv) return; clearTimeout(this._advT);
    if (!this._valid()) return;
    this._adv=true;
    this._advT=setTimeout(()=>{ if(this._valid()) this.next(); this._adv=false; },ms);
  }

  /* ══════════════════════════════════════
     CLICK ROUTER
  ══════════════════════════════════════ */
  _click(e) {
    const t=e.target;
    const card=t.closest('[data-group]');
    if (card) { this._cardClick(card); return; }
    if (t.closest('#kw-btn-next'))       { this.next();         return; }
    if (t.closest('#kw-btn-back'))       { this.back();         return; }
    if (t.closest('#kw-btn-cart'))        { this.addToCart(false);  return; }
    if (t.closest('#kw-btn-cart2'))       { this.addToCart(false);  return; }
    if (t.closest('#kw-btn-buynow'))      { this.addToCart(true);   return; }
    if (t.closest('#kw-btn-buynow2'))     { this.addToCart(true);   return; }
    // kw-btn-complete kaldırıldı, yerine kw-btn-buynow2 ve kw-btn-cart2
    if (t.closest('#kw-close'))          { this._confirmClose();return; }
    if (t.closest('.kw-btn--hero-start')){ this.start();        return; }
    // Nav dot tıklama: sadece tamamlanan adımlara git
    const navItem = t.closest('.kw-step-nav__item');
    if (navItem) {
      const targetStep = parseInt(navItem.dataset.step);
      if (!isNaN(targetStep) && targetStep < this._s.step) {
        this._goStep(targetStep); return;
      }
    }
    if (t.closest('.kw-btn--hero-how'))  { document.querySelector('.kw-steps-preview')?.scrollIntoView({behavior:'smooth'}); return; }
    if (t.closest('.kw-ratio-btn'))      { const b=t.closest('.kw-ratio-btn'); this._ratio(parseInt(b.dataset.idx),parseInt(b.dataset.delta)); return; }
    if (t.closest('.kw-pkg-design-btn')) {
      const b = t.closest('.kw-pkg-design-btn');
      this._pkgSelectDesign(parseInt(b.dataset.size), b.dataset.variant, b.dataset.design);
      return;
    }
    if (t.closest('.kw-pkg-add'))        { this._pkgAdd(parseInt(t.closest('.kw-pkg-add').dataset.size));    return; }
    if (t.closest('.kw-pkg-rem'))        { this._pkgRem(parseInt(t.closest('.kw-pkg-rem').dataset.size));    return; }
    if (t.closest('.kw-qty-preset')) {
      const btn = t.closest('.kw-qty-preset');
      const v = parseInt(btn.dataset.v);
      if (btn.classList.contains('kw-qty-preset--more') || v > KW_MAX || v > this._maxKgByStock()) {
        this._showContact(); return;
      }
      this._setQty(v); return;
    }
    if (t.closest('.kw-qty-btn'))        { this._changeQty(t.closest('.kw-qty-btn').dataset.dir==='up'?1:-1); return; }
    if (t.closest('.kw-saved-load'))     { this._loadBlend(parseInt(t.closest('.kw-saved-load').dataset.id));return; }
    if (t.closest('.kw-saved-del'))      { this._deleteBlend(t.closest('.kw-saved-del').dataset.id).catch(function(e){console.error(e);}); return; }
    if (t.closest('.kw-save-blend-btn')) { this.saveBlend();    return; }
    if (t.closest('#kw-btn-reset'))       { this._resetAll();   return; }
    if (t.closest('#kw-contact-submit')) { this._submitContact(); return; }
    if (t.closest('#kw-contact-cancel')) { document.getElementById('kw-contact-modal').classList.remove('open'); return; }
  }

  _cardClick(card) {
    const group=card.dataset.group; if(!group) return;
    if (group==='bean')   { this._toggleBean(card.dataset.value); return; }
    if (group==='preset') { this._applyPreset(card.dataset.value); return; }

    document.querySelectorAll(`[data-group="${group}"]`).forEach(c=>c.classList.remove('selected'));
    card.classList.add('selected');
    const v=card.dataset.value;

    switch(group){
      case 'step1-type':
        this._s.type=v; this._s.beans=[];
        this._summary(); this._navBtns(); this._advance();
        // Adım 2'ye geçince preseti güncelle (tür bazlı filtreleme için)
        break;
      case 'step2-character': this._s.character=v; this._s.beans=[]; this._summary(); this._navBtns(); this._advance(); break;
      case 'step4-roast':
        this._s.roast=v; this._suggestedRoast=null;
        this._summary(); this._navBtns();
        // Kavurma seçildi ama öğütme yoksa ilerletme
        if (this._s.grind) this._advance();
        break;
      case 'step4-grind':
        this._s.grind=v;
        this._summary(); this._navBtns();
        if (this._s.roast) this._advance();
        break;
      case 'step6-design':
        this._s.designType=v;
        document.getElementById('kw-logo-upload').style.display=v==='custom'?'block':'none';
        if (this._s.step===6) this._refreshPkgUI();
        this._summary(); this._navBtns(); break;
      case 'step8-design':
        this._s.designType=v;
        const logoEl7 = document.getElementById('kw-logo-upload-7');
        if (logoEl7) logoEl7.style.display=v==='custom'?'block':'none';
        this._renderOrderPreview(); this._summary(); this._navBtns(); this._save(); break;
    }
  }

  /* ══════════════════════════════════════
     ADIM 4: KAVURMA (önerilen vurgula)
  ══════════════════════════════════════ */
  _renderRoast() {
    const suggested = this._suggestedRoast;
    // Önceki seçimi yansıt
    document.querySelectorAll('[data-group="step4-roast"]').forEach(c => {
      c.classList.toggle('selected', c.dataset.value === this._s.roast);
    });
    // Önerilen roast'u vurgula (seçilmemişse)
    const hint = document.getElementById('kw-roast-hint');
    if (suggested && !this._s.roast) {
      const label = { light:'Light', medium:'Medium', 'full-city':'Full City', dark:'Dark' }[suggested] || suggested;
      if (hint) { hint.textContent = `Bu tarif için önerilen kavurma: ${label}`; hint.style.display = 'block'; }
      // Önerilen kartı hafifçe vurgula
      document.querySelectorAll('[data-group="step4-roast"]').forEach(c => {
        c.classList.toggle('kw-roast-suggested', c.dataset.value === suggested);
      });
    } else {
      if (hint) hint.style.display = 'none';
      document.querySelectorAll('[data-group="step4-roast"]').forEach(c => c.classList.remove('kw-roast-suggested'));
    }
  }

  /* ══════════════════════════════════════
     ADIM 2: HARMAN
  ══════════════════════════════════════ */
  _renderStep2() {
    this._renderPresetsGrid(); // tür bilgisine göre filtreli render
    if (this._s.character) {
      document.querySelector(`[data-group="step2-character"][data-value="${this._s.character}"]`)?.classList.add('selected');
    }
  }

  _renderPresetsGrid() {
    const g = document.getElementById('kw-presets-grid');
    if (!g) return;

    const typeNow    = this._s.type; // adım 1'de seçilen tür (null olabilir)
    const typeLabels = { filtre:'Filtre Kahve', turk:'Türk Kahvesi', espresso:'Espresso' };
    const typeOrder  = ['filtre','turk','espresso'];

    // Stokta olanları filtrele
    const available = this.presets.filter(p => this._presetInStock(p));
    const hiddenCnt = this.presets.length - available.length;

    if (!available.length) {
      g.innerHTML = '<p class="kw-empty" style="grid-column:1/-1;padding:8px 0;">Şu an stokta hazır tarif bulunmuyor.</p>';
      return;
    }

    // Tür seçilmişse: sadece o türü göster; seçilmemişse hepsini gruplu göster
    let html = '';

    if (typeNow) {
      // Seçili türe ait presetler
      const forType = available.filter(p => p.type === typeNow);
      if (forType.length) {
        html += forType.map(p => this._presetCardHTML(p)).join('');
      } else {
        html += `<p class="kw-empty" style="grid-column:1/-1;padding:8px 0;">${typeLabels[typeNow]} için tarif bulunamadı.</p>`;
      }
    } else {
      // Tür seçilmedi: gruplara ayır
      typeOrder.forEach(type => {
        const group = available.filter(p => p.type === type);
        if (!group.length) return;
        html += `<div class="kw-preset-group">
          <div class="kw-preset-group__label">${typeLabels[type]}</div>
          <div class="kw-preset-group__cards">${group.map(p => this._presetCardHTML(p)).join('')}</div>
        </div>`;
      });
    }

    if (hiddenCnt > 0) {
      html += `<p class="kw-presets-hidden-note" style="grid-column:1/-1;">${hiddenCnt} tarif stok yetersizliği nedeniyle gizlendi.</p>`;
    }

    g.innerHTML = html;
  }

  _presetCardHTML(p) {
    const roastLabel = { light:'Light', medium:'Medium', 'full-city':'Full City', dark:'Dark' }[p.suggestedRoast||p.roast] || '';
    const charLabel  = p.character === 'single' ? 'Single Origin' : 'Blend';
    // Renk barı: preset'teki çekirdeklerin renklerinden
    const barColors = p.beans.map(b => {
      const c = this.catalog.cekirdekler.find(x => x.id === b.id);
      return { color: c?.color || '#a2926a', ratio: b.ratio };
    });
    let cum = 0;
    const barGrad = barColors.length > 1
      ? barColors.map(b => { const s=`${b.color} ${cum}% ${cum+b.ratio}%`; cum+=b.ratio; return s; }).join(',')
      : barColors[0]?.color || '#a2926a';
    const barStyle = barColors.length > 1
      ? `background:linear-gradient(to right,${barGrad})`
      : `background:${barGrad}`;
    return `<div class="kw-preset-card" data-group="preset" data-value="${p.id}">
      <div class="kw-preset-color-bar" style="${barStyle};"></div>
      <div class="kw-preset-card__badges">
        <span class="kw-preset-badge kw-preset-badge--char">${charLabel}</span>
        ${roastLabel ? `<span class="kw-preset-badge kw-preset-badge--roast">Önerilen: ${roastLabel}</span>` : ''}
      </div>
      <strong>${p.title}</strong>
      <p>${p.desc}</p>
    </div>`;
  }

  /* Presetteki tüm çekirdeklerin stokta olup olmadığını kontrol et */
  _presetInStock(preset) {
    return preset.beans.every(pb => {
      const c = this.catalog.cekirdekler.find(x => x.id === pb.id);
      // Çekirdek bulunamazsa (demo vs gerçek ID uyuşmazsa) göster
      if (!c) return true;
      // Stok 0 ise gizle
      if (c.stockGr <= 0) return false;
      return true;
    });
  }

  _applyPreset(id) {
    const p = this.presets.find(x => x.id === id);
    if (!p) return;

    // Stok kontrolü
    if (!this._presetInStock(p)) {
      kwToast('Bu tarife ait çekirdeklerin stoğu yeterli değil.', 'error');
      return;
    }

    // Tür, harman karakteri ve çekirdekleri ata
    this._s.type      = p.type;
    this._s.character = p.character;
    this._s.roast     = null; // kavurma müşteri seçecek — sıfırla

    this._s.beans = p.beans.map(pb => {
      const f = this.catalog.cekirdekler.find(c => c.id === pb.id);
      return f ? { ...f, ratio: pb.ratio } : null;
    }).filter(Boolean);

    // Karakter kartını seçili göster
    document.querySelectorAll('[data-group="step2-character"]').forEach(c => {
      c.classList.toggle('selected', c.dataset.value === p.character);
    });

    // Önerilen kavurma varsa adım 4'te vurgula
    this._suggestedRoast = p.suggestedRoast || p.roast || null;

    // Kavurma adımına git (müşteri seçecek)
    this._goStep(4);
  }

  /* ══════════════════════════════════════
     ADIM 3: ÇEKİRDEK
  ══════════════════════════════════════ */

  _getFlag(mensei) {
    if (!mensei) return '';
    const KW_FLAGS = {
      'Etiyopya':'🇪🇹','Ethiopia':'🇪🇹','Lekempti':'🇪🇹','Limu':'🇪🇹','Gedeo':'🇪🇹',
      'Kolombiya':'🇨🇴','Colombia':'🇨🇴','Huila':'🇨🇴','Antioquia':'🇨🇴',
      'Brezilya':'🇧🇷','Brazil':'🇧🇷','Brasil':'🇧🇷','Minas Gerais':'🇧🇷',
      'Kenya':'🇰🇪','Nyeri':'🇰🇪','Kirinyaga':'🇰🇪',
      'Guatemala':'🇬🇹','Huehuetenango':'🇬🇹',
      'Endonezya':'🇮🇩','Indonesia':'🇮🇩','Aceh':'🇮🇩','Sumatra':'🇮🇩',
      'Uganda':'🇺🇬','Rwanda':'🇷🇼','Honduras':'🇭🇳',
      'El Salvador':'🇸🇻','Santa Ana':'🇸🇻',
    };
    for (const [key, flag] of Object.entries(KW_FLAGS)) {
      if (mensei.includes(key)) return flag;
    }
    return '';
  }

  _renderBeans() {
    const char=this._s.character;
    const desc=document.getElementById('kw-bean-desc');
    if(desc) desc.textContent=char==='single'
      ?'Bir çekirdek seçin.':'En az 2, en fazla 3 çekirdek seçin. Oranları ayarlayın ve toplamı %100 yapın.';

    const avail=this.catalog.cekirdekler.filter(c=>c.kavurmaTipi.includes(this._s.type) && c.stockGr > 0);
    const g=document.getElementById('kw-beans-grid');
    g.innerHTML=avail.map(c=>`
      <div class="kw-bean-card" data-group="bean" data-value="${c.id}">
        <div class="kw-bean-card__visual" style="background:${c.color};">
          <div class="kw-bean-bean-mark"></div>
        </div>
        <div class="kw-bean-card__body">
          <strong>${c.title}</strong>
          <span class="kw-bean-origin">${c.mensei}</span>
          <span class="kw-bean-notes">${c.tatNotlari}</span>
          <div class="kw-bean-tags">
            <span class="kw-tag">${c.rakim}</span>
            <span class="kw-tag">${c.proses}</span>

          </div>
        </div>
      </div>`).join('')||'<p class="kw-empty">Bu tür için çekirdek bulunamadı.</p>';

    this._s.beans.forEach(b=>document.querySelector(`[data-group="bean"][data-value="${b.id}"]`)?.classList.add('selected'));
    const rd=document.getElementById('kw-blend-ratios');
    if (char!=='single') {
      rd.style.display='block';
      if (this._s.beans.length>=2) {
        this._renderRatioCards();
      } else {
        // Henüz çekirdek seçilmedi — bar tamamen kırmızı, boş kart placeholder
        this._renderRatioEmpty();
      }
    } else {
      rd.style.display='none';
    }
    this._beanWarn();
  }

  _beanWarn() {
    const char=this._s.character, n=this._s.beans.length;
    let msg='';
    if (char==='blend') {
      if (n===0) msg=window.KW_LANG?.warnings?.beanSelectNone||'En az 2 çekirdek seçin.';
      else if (n===1) msg=window.KW_LANG?.warnings?.beanSelectOne||'Bir çekirdek daha seçin (min 2, maks 3).';
      else { const t=this._s.beans.reduce((a,b)=>a+b.ratio,0); if(t!==100) msg=`Oranların toplamı %${t} — devam etmek için %100 olmalı.`; }
    }
    const w=document.getElementById('kw-bean-warning');
    if(w){w.textContent=msg;w.style.display=msg?'block':'none';}
  }

  _toggleBean(id) {
    const char=this._s.character, MAX=char==='single'?1:3;
    const idx=this._s.beans.findIndex(b=>b.id===id);
    if (idx!==-1) {
      this._s.beans.splice(idx,1);
      document.querySelector(`[data-group="bean"][data-value="${id}"]`)?.classList.remove('selected');
    } else {
      if (this._s.beans.length>=MAX) {
        if (char==='single') { const r=this._s.beans.shift(); document.querySelector(`[data-group="bean"][data-value="${r.id}"]`)?.classList.remove('selected'); }
        else return;
      }
      const c=this.catalog.cekirdekler.find(x=>x.id===id); if(!c) return;
      this._s.beans.push({...c,ratio:0});
      document.querySelector(`[data-group="bean"][data-value="${id}"]`)?.classList.add('selected');
    }
    if (char!=='single') {
      if (this._s.beans.length===1) {
        // Tek çekirdek: %50 ata (2. çekirdek için yer bırak)
        this._s.beans[0].ratio = 50;
        this._renderRatioSingle();
      } else if (this._s.beans.length>=2) {
        this._distRatios();
        this._renderRatioCards();
      } else {
        this._renderRatioEmpty();
      }
    }
    if (char==='single'&&this._s.beans.length===1) this._advance();
    this._beanWarn(); this._navBtns(); this._summary(); this._save();
  }

  _distRatios() {
    const n=this._s.beans.length; if(!n) return;
    const base=Math.floor(100/n/10)*10; let sum=0;
    this._s.beans.forEach(b=>{b.ratio=base;sum+=base;});
    this._s.beans[0].ratio+=(100-sum);
  }

  /* ── Tek çekirdek seçildi, %100 dolu göster, 2. çekirdek daveti ── */
  _renderRatioSingle() {
    const b = this._s.beans[0];
    document.getElementById('kw-blend-count').textContent = '1';
    const bar = document.getElementById('kw-ratio-bar');
    if (bar) {
      bar.innerHTML = `<div style="width:50%;height:100%;background:${b.color};border-radius:8px 0 0 8px;display:flex;align-items:center;justify-content:center;"><span style="font-size:13px;color:#fff;font-weight:600;text-shadow:0 1px 3px rgba(0,0,0,.3);">%50</span></div><div style="width:50%;height:100%;background:#e74c3c;opacity:.4;border-radius:0 8px 8px 0;display:flex;align-items:center;justify-content:center;"><span style="font-size:11px;color:#c0392b;font-weight:600;">+2. çekirdek</span></div>`;
    }
    const cards = document.getElementById('kw-ratio-cards');
    if (cards) {
      cards.innerHTML = `<div class="kw-ratio-card" style="border-left:4px solid ${b.color};">
        <div class="kw-ratio-card__head">
          <span class="kw-rc-dot" style="background:${b.color};"></span>
          <div><strong>${b.title}</strong><small>${b.mensei}</small></div>
        </div>
        <div class="kw-ratio-card__ctrl">
          <span style="font-size:18px;font-weight:700;color:${b.color};padding:0 12px;">%50</span>
        </div>
      </div>
      <div style="grid-column:1/-1;font-size:12px;color:#a2926a;padding:6px 0;">
        İkinci bir çekirdek seçerek harman oranlarını ayarlayabilirsiniz.
      </div>`;
    }
    this._updateTotalBadge(50);
  }

  /* ── Oran barı: çekirdek seçilmeden önce tamamen kırmızı göster ── */
  _renderRatioEmpty() {
    document.getElementById('kw-blend-count').textContent = '0';
    // Bar tamamen kırmızı (henüz seçilmedi)
    const bar = document.getElementById('kw-ratio-bar');
    if (bar) {
      bar.innerHTML = '<div style="width:100%;height:100%;background:#e74c3c;opacity:.35;border-radius:8px;display:flex;align-items:center;justify-content:center;"><span style="font-size:12px;color:#c0392b;font-weight:600;">Çekirdek seçilmedi</span></div>';
    }
    // Kart alanı boş placeholder
    const cards = document.getElementById('kw-ratio-cards');
    if (cards) {
      cards.innerHTML = '<p style="font-size:12px;color:#c0392b;margin:0;padding:4px 0;">Aşağıdan en az 2 çekirdek seçin, oranlar burada görünecek.</p>';
    }
    // Toplam badge kırmızı
    this._updateTotalBadge(0);
  }

  /* ── Oran kartları: ekran görüntüsü gibi, bağımsız +/– ── */
  _renderRatioCards() {
    const beans=this._s.beans; if(beans.length<2) return;
    document.getElementById('kw-blend-count').textContent=beans.length;
    const total=beans.reduce((a,b)=>a+b.ratio,0);
    this._updateRatioBar(beans,total);
    const totalKgForPrice = this._s.quantityKg || 20;
    document.getElementById('kw-ratio-cards').innerHTML=beans.map((b,i)=>{
      const kgShare = totalKgForPrice * b.ratio / 100;
      const priceLabel = b.price && b.price < 9000
        ? `<span class="kw-rc-price">${new Intl.NumberFormat('tr-TR',{style:'currency',currency:'TRY',maximumFractionDigits:0}).format(b.price)}/kg</span>`
        : '';
      return `<div class="kw-ratio-card" style="border-left:4px solid ${b.color};">
        <div class="kw-ratio-card__head">
          <span class="kw-rc-dot" style="background:${b.color};"></span>
          <div>
            <strong>${b.title}</strong>
            <small>${b.mensei}</small>
          </div>
          ${priceLabel}
        </div>
        <div class="kw-ratio-card__ctrl">
          <button class="kw-ratio-btn" data-idx="${i}" data-delta="-10">−</button>
          <span class="kw-ratio-val" id="kw-rv-${i}">%${b.ratio}</span>
          <button class="kw-ratio-btn" data-idx="${i}" data-delta="10">+</button>
        </div>
      </div>`;
    }).join('');
    this._updateTotalBadge(total);
  }

  _updateRatioBar(beans,total) {
    const bar=document.getElementById('kw-ratio-bar');
    if (!bar) return;
    // Her dilimi ayrı div olarak göster
    let cum=0;
    bar.innerHTML=beans.map(b=>{
      // %100 değilse kalan kısmı kırmızı göster
      const isUnder = total < 100;
      const w=b.ratio;
      cum+=w;
      return `<div style="width:${w}%;height:100%;background:${b.color};display:inline-block;vertical-align:top;"></div>`;
    }).join('')+(total<100?`<div style="width:${100-total}%;height:100%;background:#e74c3c;display:inline-block;vertical-align:top;opacity:.7;"></div>`:'');
  }

  _updateTotalBadge(total) {
    const badge=document.getElementById('kw-total-pct');
    if(!badge) return;
    badge.textContent=`%${total}`;
    const ok=total===100;
    badge.style.color=ok?'':'#c0392b';
    const wrap=badge.closest('.kw-total-badge');
    if(wrap){wrap.style.background=ok?'':'#fdecea';wrap.style.color=ok?'':'#c0392b';}
  }

  _ratio(idx,delta) {
    const beans=this._s.beans;
    const target=beans[idx].ratio+delta;
    if (target<10||target>90) return;
    // Toplam 100'ü geçemez
    const currentTotal=beans.reduce((a,b)=>a+b.ratio,0);
    const projected=currentTotal-beans[idx].ratio+target;
    if (projected>100) return;
    beans[idx].ratio=target;
    const total=projected;
    this._updateRatioBar(beans,total);
    this._updateTotalBadge(total);
    const el=document.getElementById(`kw-rv-${idx}`); if(el) el.textContent=`%${target}`;
    // Uyarı
    const w=document.getElementById('kw-bean-warning');
    if(w){
      if(total!==100){w.textContent=`Oranların toplamı %${total} — devam etmek için %100 olmalı.`;w.style.display='block';}
      else{w.style.display='none';}
    }
    this._navBtns(); this._summary(); this._save();
  }

  /* ══════════════════════════════════════
     ADIM 5: MİKTAR
  ══════════════════════════════════════ */
  _renderKg() {
    const stockMax = this._maxKgByStock(); // ham stok limiti (sınırsız=9999)
    const hasStockLimit = stockMax < KW_MAX; // stok 100'den az mı?
    const displayMax = Math.min(KW_MAX, stockMax); // gösterilecek maks
    if (this._s.quantityKg > displayMax) this._s.quantityKg = displayMax;

    // Stok uyarı bandı
    const sw = document.getElementById('kw-stock-warning');
    if (sw) {
      if (hasStockLimit) {
        sw.style.display = 'block';
        sw.textContent = `Seçili çekirdek kombinasyonunda mevcut stok: ${stockMax} kg. ` +
          `Bu miktarın üzerinde sipariş için talep oluşturabilirsiniz.`;
      } else {
        sw.style.display = 'none';
      }
    }

    // Preset butonlar — stok limitine kadar, üstü popup
    const presets = document.getElementById('kw-qty-presets');
    if (presets) {
      const visible = KW_QTY_PRESETS.filter(v => v <= displayMax);
      const html = visible.map(v =>
        `<button class="kw-qty-preset ${this._s.quantityKg===v?'active':''}" data-v="${v}">${v} kg</button>`
      ).join('');
      // Stok limiti tam 100 değilse "Daha Fazla →" butonu ekle (popup açar)
      const extraBtn = `<button class="kw-qty-preset kw-qty-preset--more" data-v="${displayMax+1}">Daha fazla →</button>`;
      presets.innerHTML = html + extraBtn;
    }
    this._updateQtyDisplay();
  }

  _maxKgByStock() {
    const s = this._s;
    if (!s.beans.length) return KW_MAX;
    // stockGr = inventory_quantity * 1000 (gr). 9999 kg = bilinmiyor, sınırsız say.
    const UNKNOWN = 9999 * 1000;
    if (s.character === 'single') {
      const sg = s.beans[0].stockGr;
      return sg >= UNKNOWN ? KW_MAX : Math.min(KW_MAX, Math.floor(sg / 1000));
    }
    let minKg = Infinity;
    s.beans.forEach(b => {
      if (b.stockGr >= UNKNOWN) return; // bilinmeyen stok — atla
      const ratio = b.ratio > 0 ? b.ratio / 100 : 0.5;
      const kg = Math.floor(b.stockGr / 1000 / ratio);
      if (kg < minKg) minKg = kg;
    });
    return minKg === Infinity ? KW_MAX : Math.min(KW_MAX, minKg);
  }

  _changeQty(dir) {
    const stockMax = this._maxKgByStock(); // stok limiti
    const n = this._s.quantityKg + dir*5;
    if (n > KW_MAX) { this._showContact(); return; }     // 100 aşıldı → popup
    if (n > stockMax) { this._showContact(); return; }   // stok aşıldı → popup
    this._setQty(Math.max(KW_MIN, n));
  }

  _setQty(v) {
    const stockMax = this._maxKgByStock();
    if (v>KW_MAX || v>stockMax) { this._showContact(); return; }
    this._s.quantityKg=v; this._s.packages=[];
    this._updateQtyDisplay(); this._summary(); this._save();
    document.querySelectorAll('.kw-qty-preset').forEach(b=>b.classList.toggle('active',parseInt(b.dataset.v)===v));
  }

  _updateQtyDisplay() {
    const el=document.getElementById('kw-qty-number'); if(el) el.textContent=this._s.quantityKg;
  }

  _showContact() {
    document.getElementById('kw-contact-modal').classList.add('open');
  }

  async _submitContact() {
    const name  = document.getElementById('kw-contact-name').value.trim();
    const phone = document.getElementById('kw-contact-phone').value.trim();
    const kg    = document.getElementById('kw-contact-kg').value.trim();
    if (!name || !phone || !kg) { alert('Lutfen tum alanlari doldurun.'); return; }
    const note = [
      '=== BUYUK HACIMLI SIPARIS TALEBi ===',
      'Ad Soyad: ' + name,
      'Telefon: ' + phone,
      'Talep Miktari: ' + kg + ' kg',
      'Kahve Turu: ' + (this._typeL(this._s.type) || '-'),
      'Cekirdekler: ' + (this._s.beans.map(b=>b.title).join(', ') || '-'),
      'Tarih: ' + new Date().toLocaleString('tr-TR'),
    ].join('\n');
    try {
      await fetch('/cart/update.js', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ note }),
      });
    } catch(e) {}
    document.getElementById('kw-contact-modal').classList.remove('open');
    document.getElementById('kw-contact-name').value = '';
    document.getElementById('kw-contact-phone').value = '';
    document.getElementById('kw-contact-kg').value = '';
    kwToast('Teşekkürler ' + name + '! En kısa sürede ' + phone + ' numaranızdan sizi arayacağız.', 'success', 5000);
  }

  /* ══════════════════════════════════════
     ADIM 6: AMBALAJ — otomatik doldur, müşteri değiştirir
  ══════════════════════════════════════ */
  _renderPkgStep() {
    // Ambalaj tiplerini göster
    this._renderPkgTypeGrid();
    // Progress bar ve adet seçimi
    this._renderPkgBuilder();
  }

  _renderPkgTypeGrid() {
    const cont = document.getElementById('kw-pkg-type-grid');
    if (!cont) return;

    // Unique ambalaj tipleri — img'i ilk varyantten al
    const types = {};
    this.catalog.ambalajlar.forEach(a => {
      if (!types[a.productTitle]) {
        types[a.productTitle] = { variants: [], img: a.img || null };
      }
      types[a.productTitle].variants.push(a);
    });

    cont.innerHTML = Object.keys(types).map(title => {
      const data = types[title];
      const img  = data.img;

      // Stok: bu tipteki herhangi bir variant stokta var mı?
      const hasStock = data.variants.some(v => v.stock === 9999 || v.stock > 0);
      const shortName = title.replace(' Ambalaj','');

      const visual = img
        ? `<div class="kw-pkg-type-card__visual" style="background:#f4f1ec url('${img}') center/contain no-repeat;"></div>`
        : `<div class="kw-pkg-type-card__visual" style="background:#2C1A0E;display:flex;align-items:center;justify-content:center;">
             <span style="color:#fff;font-size:11px;font-weight:700;letter-spacing:.1em;">${shortName.toUpperCase()}</span>
           </div>`;

      return `<div class="kw-pkg-type-card${!hasStock?' kw-pkg-type-card--oos':''}" data-pkg-type="${title}">
        ${visual}
        <div class="kw-pkg-type-card__footer">
          <span class="kw-pkg-type-card__name">${shortName}</span>
          ${!hasStock ? '<span class="kw-pkg-type-card__oos">Stok yok</span>' : ''}
        </div>
      </div>`;
    }).join('');

    // Click handler (stokta yoksa tıklanamaz)
    cont.querySelectorAll('.kw-pkg-type-card:not(.kw-pkg-type-card--oos)').forEach(card => {
      card.addEventListener('click', () => {
        const title = card.dataset.pkgType;
        this._selectPkgType(title);
        cont.querySelectorAll('.kw-pkg-type-card').forEach(c => c.classList.remove('selected'));
        card.classList.add('selected');
      });
    });

    // Mevcut seçimi yansıt
    if (this._selectedPkgType) {
      cont.querySelector(`[data-pkg-type="${this._selectedPkgType}"]`)?.classList.add('selected');
    }
  }

  _selectPkgType(title) {
    this._selectedPkgType = title;
    // Mevcut paketlerin variantId'lerini bu tipe göre güncelle
    this._s.packages.forEach(pkg => {
      const v = this.catalog.ambalajlar.find(a =>
        a.sizeGr === pkg.sizeGr && a.productTitle === title
      );
      if (v) {
        pkg.variantId    = v.variantId;
        pkg.productTitle = v.productTitle;
        pkg.designCode   = v.designCode;
      }
    });
    this._refreshPkgUI();
    this._summary(); this._save();
  }

  _renderPkgBuilder() {
    if (!this._s.packages?.length) this._autoFillPackages();
    this._refreshPkgUI();
    // Tasarım seçimi ayrı bölüm — başta generic seçili gelsin
    if (!this._s.designType) {
      this._s.designType = 'generic';
      document.querySelector('[data-group="step6-design"][data-value="generic"]')?.classList.add('selected');
    } else {
      document.querySelector(`[data-group="step6-design"][data-value="${this._s.designType}"]`)?.classList.add('selected');
      if (this._s.designType==='custom') document.getElementById('kw-logo-upload').style.display='block';
    }
  }

  _autoFillPackages() {
    const totalGr = this._s.quantityKg * 1000;
    let remaining = totalGr;
    this._s.packages = [];
    const sizes = [2500, 1000, 250];
    const preferredType = this._selectedPkgType || 'Kraft Ambalaj';
    for (const sz of sizes) {
      if (remaining <= 0) break;
      const defaultV = this.catalog.ambalajlar.find(a => a.sizeGr === sz && a.productTitle === preferredType)
                    || this.catalog.ambalajlar.find(a => a.sizeGr === sz);
      if (!defaultV) continue;
      const maxCount = Math.min(Math.floor(remaining / sz), defaultV.stock ?? 9999);
      if (maxCount > 0) {
        this._s.packages.push({
          sizeGr: sz, count: maxCount,
          variantId: defaultV.variantId,
          productTitle: defaultV.productTitle,
          designCode: defaultV.designCode,
        });
        remaining -= sz * maxCount;
      }
    }
  }

  _refreshPkgUI() {
    const totalGr=this._s.quantityKg*1000;
    const usedGr=this._s.packages.reduce((a,p)=>a+p.sizeGr*p.count,0);
    const remGr=totalGr-usedGr;

    // Blend-stili gradient bar (kırmızı→dolu)
    const pct = Math.min(100, (usedGr / totalGr) * 100);
    const barWrap = document.getElementById('kw-pkg-bar-wrap');
    if (barWrap) {
      const filledColor = usedGr > totalGr ? '#c0392b' : usedGr === totalGr ? '#27ae60' : '#a2926a';
      const remaining = Math.max(0, 100 - pct);
      // Seçili paketleri renge göre böl
      let cum = 0;
      const segments = this._s.packages.filter(p=>p.count>0).map(p => {
        const w = (p.sizeGr * p.count / totalGr) * 100;
        const colors = { 250:'#9B5B30', 1000:'#7D4A2A', 2500:'#5C3217' };
        const c = colors[p.sizeGr] || filledColor;
        const seg = `<div style="width:${w}%;height:100%;background:${c};display:flex;align-items:center;justify-content:center;"><span style="font-size:10px;color:#fff;font-weight:600;white-space:nowrap;overflow:hidden;padding:0 4px;">${KW_PKG[p.sizeGr]?.short}</span></div>`;
        cum += w;
        return seg;
      }).join('');
      const redPart = remaining > 0 ? `<div style="width:${remaining}%;height:100%;background:#e74c3c;opacity:.35;border-radius:${pct===0?'8px':'0 8px 8px 0'};display:flex;align-items:center;justify-content:center;">${pct===0?'<span style="font-size:11px;color:#c0392b;font-weight:600;">Paket seçilmedi</span>':''}</div>` : '';
      barWrap.innerHTML = `<div style="display:flex;height:100%;border-radius:8px;overflow:hidden;">${segments}${redPart}</div>`;
    }
    const lbl = document.getElementById('kw-pkg-progress-label');
    if (lbl) lbl.textContent = `${this._grLbl(usedGr)} / ${this._s.quantityKg} kg`;
    const badge = document.getElementById('kw-pkg-badge');
    if (badge) {
      if (usedGr === totalGr) {
        badge.textContent = 'Tamamlandı ✓';
        badge.style.background = '#ebf5ee'; badge.style.color = '#27ae60';
      } else if (usedGr > totalGr) {
        badge.textContent = 'Fazla seçtiniz';
        badge.style.background = '#fdecea'; badge.style.color = '#c0392b';
      } else {
        badge.textContent = `${this._grLbl(totalGr - usedGr)} eksik`;
        badge.style.background = '#fdecea'; badge.style.color = '#c0392b';
      }
    }

    // Uyarı
    const warn=document.getElementById('kw-pkg-warning');
    if(warn){
      if(remGr===0){warn.style.display='none';}
      else if(remGr>0){warn.style.display='block';warn.textContent=`${this._grLbl(remGr)} daha eklemeniz gerekiyor.`;}
      else{warn.style.display='block';warn.textContent=`${this._grLbl(-remGr)} fazla seçtiniz, azaltın.`;}
    }

    // Satırlar
    const cont=document.getElementById('kw-pkg-rows'); if(!cont) return;
    cont.innerHTML=KW_PKG_SIZES.map(sz=>{
      sz=parseInt(sz);
      const ex=this._s.packages.find(p=>p.sizeGr===sz);
      const cnt=ex?.count||0;
      const sv=this.catalog.ambalajlar.find(a=>a.sizeGr===sz&&!a.logoOption);
      const stk=sv?.stock??9999;
      const canAdd=(remGr>=sz)&&cnt<stk;
      const logoUrl = this._s.designType==='custom' && this._s.logoUrl ? this._s.logoUrl : null;
      const isSelected = cnt > 0;
      return `<div class="kw-pkg-row${isSelected?' kw-pkg-row--selected':''}">
        <div class="kw-pkg-row__pkg-visual">
          <div class="kw-pkg-mini" style="${logoUrl&&isSelected?`background-image:url(${logoUrl});background-size:contain;background-repeat:no-repeat;background-position:center;`:''}">
            ${!(logoUrl&&isSelected)?`<span>${KW_PKG[sz].short.replace(' ','<br>')}</span>`:''}
          </div>
        </div>
        <div class="kw-pkg-row__info">
          <strong>${KW_PKG[sz].label}</strong>
          <small>${cnt>0?`${cnt} paket — ${this._grLbl(sz*cnt)}`:'Seçilmedi'}</small>
        </div>
        <div class="kw-pkg-row__ctrl">
          <button class="kw-pkg-rem" data-size="${sz}" ${cnt===0?'disabled':''}>−</button>
          <span class="kw-pkg-cnt">${cnt}</span>
          <button class="kw-pkg-add" data-size="${sz}" ${!canAdd?'disabled':''}>+</button>
        </div>
      </div>`;
    }).join('');

    this._navBtns(); this._summary(); this._save();
  }

  _grLbl(gr) { return gr>=1000?`${gr/1000} kg`:`${gr} gr`; }

  _pkgSelectDesign(sz, variantId, productTitle) {
    const ex = this._s.packages.find(p => p.sizeGr === sz);
    const v  = this.catalog.ambalajlar.find(a => a.variantId === variantId);
    if (!v) return;
    if (ex) {
      ex.variantId    = variantId;
      ex.productTitle = productTitle;
      ex.designCode   = v.designCode;
    } else {
      // Seçili değilse 0 adet olarak ekle (tasarım seçildi ama miktar yok)
      this._s.packages.push({ sizeGr: sz, count: 0, variantId, productTitle, designCode: v.designCode });
    }
    this._refreshPkgUI();
    this._summary(); this._save();
  }

  _pkgAdd(sz) {
    const totalGr = this._s.quantityKg * 1000;
    const used    = this._s.packages.reduce((a,p) => a+p.sizeGr*p.count, 0);
    if (used + sz > totalGr) return;
    const ex = this._s.packages.find(p => p.sizeGr === sz);
    if (ex) {
      ex.count++;
    } else {
      // Varsayilan tasarım
      const defV = this.catalog.ambalajlar.find(a => a.sizeGr === sz && a.designCode === 'siyah-klasik' && a.productTitle?.includes('Kraft'))
                || this.catalog.ambalajlar.find(a => a.sizeGr === sz);
      if (!defV) return;
      this._s.packages.push({ sizeGr: sz, count: 1, variantId: defV.variantId, productTitle: defV.productTitle, designCode: defV.designCode });
    }
    this._refreshPkgUI();
    this._navBtns(); this._summary(); this._save();
  }

  _pkgRem(sz) {
    const ex=this._s.packages.find(p=>p.sizeGr===sz); if(!ex||ex.count===0) return;
    ex.count--;
    if (ex.count===0) this._s.packages=this._s.packages.filter(p=>p.sizeGr!==sz);
    this._refreshPkgUI();
  }

  /* ══════════════════════════════════════
     ÖZET PANELİ
  ══════════════════════════════════════ */
  _summary() {
    const s=this._s;
    this._txt('kw-sum-type',  this._typeL(s.type));
    this._txt('kw-sum-char',  this._charL(s.character));
    this._txt('kw-sum-roast', this._roastL(s.roast));
    this._txt('kw-sum-grind', this._grindL(s.grind));
    this._txt('kw-sum-qty',   s.quantityKg?`${s.quantityKg} kg`:'—');
    const pkgTxt=s.packages?.filter(p=>p.count>0).map(p=>`${p.count}×${KW_PKG[p.sizeGr]?.short}`).join(', ')||'—';
    this._txt('kw-sum-pkg', pkgTxt);

    // Çekirdekler
    const bs=document.getElementById('kw-sum-beans');
    if(s.beans.length){
      bs.style.display='block';
      document.getElementById('kw-sum-bean-list').innerHTML=s.beans.map(b=>`
        <div class="kw-sum-bean-row">
          <span class="kw-sum-bean-dot" style="background:${b.color}"></span>
          <span>${b.title}</span>
          ${s.character!=='single'?`<span class="kw-sum-bean-ratio" style="color:${b.color}">%${b.ratio}</span>`:''}
        </div>`).join('');
      const bar=document.getElementById('kw-sum-bean-bar');
      if(s.character!=='single'&&s.beans.length>1){
        let cum=0;
        bar.style.background=`linear-gradient(to right,${s.beans.map(b=>{const p=`${b.color} ${cum}% ${cum+b.ratio}%`;cum+=b.ratio;return p;}).join(',')})`;
        bar.style.display='block';
      } else { bar.style.display='none'; }
    } else { bs.style.display='none'; }

    this._price();
    document.getElementById('kw-save-blend').style.display=s.beans.length?'block':'none';
    const all=s.type&&s.character&&this._beansOk()&&s.roast&&s.quantityKg>=KW_MIN&&this._pkgsOk();
    const btn=document.getElementById('kw-btn-complete'); if(btn) btn.disabled=!all;
  }

  _price() {
    const s=this._s; if(!s.quantityKg||!s.beans.length) return;
    let total=0;
    s.beans.forEach(b=>{const kg=s.character==='single'?s.quantityKg:s.quantityKg*b.ratio/100; total+=b.price*kg;});
    if (s.designType==='custom') {
      const pkgCount=s.packages?.reduce((a,p)=>a+p.count,0)||0;
      total+=pkgCount*35;
    }
    const pd=document.getElementById('kw-sum-price'); if(pd) pd.style.display=total>0?'block':'none';
    const te=document.getElementById('kw-sum-total');
    if(te) te.textContent=new Intl.NumberFormat('tr-TR',{style:'currency',currency:this.cfg.currency||'TRY',maximumFractionDigits:0}).format(total);
  }

  /* ══════════════════════════════════════
     SEPETE EKLE
  ══════════════════════════════════════ */
  async addToCart(buyNow) {
    const s=this._s;

    if (!s.beans?.length) { kwToast('Lütfen çekirdek seçin.', 'warning'); return; }
    if (!s.roast)          { kwToast('Lütfen kavurma derecesi seçin.', 'warning'); return; }
    if (!s.quantityKg)     { kwToast('Lütfen miktar girin.', 'warning'); return; }

    // Anlık stok kontrolü (Shopify'dan canlı çek)
    const stockErr = await this._checkStockLive();
    if (stockErr) {
      const canOrder = stockErr.maxKg;
      if (canOrder >= KW_MIN) {
        const ok = await kwConfirm(stockErr.msg + '<br><br>Mevcut stokla sipariş verebileceğiniz maksimum: <strong>' + canOrder + ' kg</strong>.<br>Tamam ile ' + canOrder + ' kg olarak devam edilir.');
        if (!ok) return;
        // Miktarı güncelle — items aşağıda yeniden hesaplanacak
        s.quantityKg = canOrder;
        s.packages = [];
        this._autoFillPackages();
        this._summary();
      } else {
        // Sipariş verilebilecek minimum yok — iletişim popup
        this._showContact();
        return;
      }
    }

    const group = 'KKM-' + Date.now();

    const beanDesc = s.beans.map(b =>
      s.character === 'single' ? b.title : (b.title + ' %' + b.ratio)
    ).join(' + ');

    const pkgDesc = (s.packages||[]).filter(p=>p.count>0).map(p=>
      p.count + 'x' + (KW_PKG[p.sizeGr]?.short||p.sizeGr+'gr') + ' ' + (p.productTitle||'').replace(' Ambalaj','')
    ).join(', ');

    const props = {
      '_group':      group,
      'Kahve Turu':  this._typeL(s.type),
      'Karakter':    this._charL(s.character),
      'Cekirdekler': beanDesc,
      'Kavurma':     this._roastL(s.roast),
      'Ogutme':      this._grindL(s.grind),
      'Miktar':      s.quantityKg + ' kg',
      'Paketleme':   pkgDesc || '-',
      'Tasarim':     s.designType === 'custom' ? 'Ozel Logo (+35 tl/paket)' : 'Standart',
    };
    if (s.logoUrl) props['Logo'] = s.logoUrl;

    const SIPARIS_VID = window.KW_CONFIG?.siparisVariantId || null;

    const items = [];
    if (SIPARIS_VID) {
      items.push({ id: parseInt(SIPARIS_VID), quantity: s.quantityKg, properties: props });
    } else {
      s.beans.forEach(b => {
        const vid = parseInt(b.variantId);
        if (!vid || isNaN(vid)) return;
        const qty = s.character==='single' ? s.quantityKg : Math.round(s.quantityKg*b.ratio/100);
        if (qty < 1) return;
        items.push({ id: vid, quantity: qty, properties: props });
      });
    }

    if (!items.length) { kwToast('Sepete eklenecek urun bulunamadi.', 'error'); return; }


    console.log('[KW] Sepete ekleniyor:', JSON.stringify(items, null, 2));
    try{
      // 1. Ürünleri sepete ekle
      const r=await fetch('/cart/add.js',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({items})});
      if(!r.ok) throw new Error(await r.text());

      // 2. Sipariş grubunu cart note_attributes'a yaz
      //    Böylece cart page'de hangi öğelerin birlikte olduğu bilinir
      const noteLines = [
        `Sipariş Grubu: ${group}`,
        `Tür: ${this._typeL(s.type)}`,
        `Karakter: ${this._charL(s.character)}`,
        `Kavurma: ${this._roastL(s.roast)}`,
        `Miktar: ${s.quantityKg} kg`,
        s.beans.map(b=>s.character==='single'?b.title:`${b.title} %${b.ratio}`).join(' + '),
      ].join(' | ');
      await fetch('/cart/update.js',{method:'POST',headers:{'Content-Type':'application/json'},
        body:JSON.stringify({
          note: noteLines,
          attributes: {
            'KKM_Grup':    group,
            'KKM_Tür':     this._typeL(s.type),
            'KKM_Kavurma': this._roastL(s.roast),
            'KKM_Miktar':  `${s.quantityKg} kg`,
          }
        })
      });

      if (this.cfg.customerId) this._saveBlendSilent();
      this._skipBeforeUnload = true;
      if (buyNow) {
        // Sepeti temizle, sonra checkout'a git
        await fetch('/cart/clear.js', { method: 'POST' });
        // Yeniden ekle (clear sonrası)
        const r2 = await fetch('/cart/add.js', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ items })
        });
        if (!r2.ok) throw new Error(await r2.text());
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '/checkout';
        document.body.appendChild(form);
        form.submit();
      } else {
        // Sepet drawer'ını aç
        await this._openCartDrawer();
      }
    } catch(err) {
      // Shopify stok hatası mı?
      let errBody = err.message || '';
      try { const parsed = JSON.parse(errBody); errBody = parsed.description || parsed.message || errBody; } catch {}

      const isStockErr = errBody.includes('Stok') || errBody.includes('stock') ||
                         errBody.includes('yalnızca') || errBody.includes('only') ||
                         (err.status === 422);

      if (isStockErr) {
        // Anlık stok çekip max miktarı hesapla
        const stockErr = await this._checkStockLive();
        const canOrder = stockErr?.maxKg ?? 0;
        if (canOrder >= KW_MIN) {
          const ok = await kwConfirm('Stok yetersizliği nedeniyle sipariş tamamlanamadı.<br><br>Sipariş verebileceğiniz maksimum: <strong>' + canOrder + ' kg</strong>.<br>Tamam ile tekrar denenecek.');
          if (ok) {
            s.quantityKg = canOrder;
            s.packages = [];
            this._autoFillPackages();
            this._summary();
            // Kısa gecikme sonra tekrar dene
            setTimeout(() => this.addToCart(buyNow), 300);
          }
        } else {
          this._showContact();
        }
      } else {
        kwToast('Hata: ' + errBody, 'error', 5000);
      }
    }
  }

  _checkStock() {
    // Senkron stok kontrolü (catalog'daki değerlerle)
    const s=this._s;
    for(const b of s.beans){
      const needKg = s.character==='single' ? s.quantityKg : s.quantityKg*b.ratio/100;
      const stockKg = Math.floor(b.stockGr/1000);
      if(stockKg < needKg) return `${b.title} için yeterli stok yok. Mevcut: ${stockKg} kg`;
    }
    return null;
  }

  async _checkStockLive() {
    // Shopify variants API'den anlık stok çek
    const s = this._s;
    let minMaxKg = KW_MAX;
    let problematicBean = null;

    for (const b of s.beans) {
      try {
        const r = await fetch(`/variants/${b.variantId}.js`);
        if (!r.ok) continue;
        const v = await r.json();
        const liveStockKg = v.inventory_quantity ?? 9999;

        // Bu çekirdekten kaç kg lazım?
        const needKg = s.character==='single'
          ? s.quantityKg
          : Math.round(s.quantityKg * b.ratio / 100);

        if (liveStockKg < needKg) {
          // Blend'de bu çekirdekle yapılabilecek max toplam kg
          const maxForThisBean = s.character==='single'
            ? liveStockKg
            : Math.floor(liveStockKg / (b.ratio / 100));

          if (maxForThisBean < minMaxKg) {
            minMaxKg = maxForThisBean;
            problematicBean = b;
          }
        }

        // Catalog'u da güncelle (sonraki kontroller için)
        b.stockGr = liveStockKg * 1000;
      } catch { /* ağ hatası — catalog değerine güven */ }
    }

    if (problematicBean) {
      // 5'in katına yuvarla (aşağı)
      const maxKg = Math.floor(minMaxKg / KW_STEP_KG) * KW_STEP_KG;
      return {
        msg: `${problematicBean.title} için yeterli stok bulunmuyor.`,
        maxKg: Math.max(0, maxKg),
      };
    }
    return null; // sorun yok
  }

  /* ══════════════════════════════════════
     BLEND KAYDETME
  ══════════════════════════════════════ */
  _openCartDrawer() {
    // Horizon temasının cart drawer'ını aç
    // Yöntem 1: cart-drawer custom element
    const drawer = document.querySelector('cart-drawer');
    if (drawer && typeof drawer.open === 'function') { drawer.open(); return; }
    // Yöntem 2: cart icon'a tıkla
    const cartBtn = document.querySelector(
      '[data-cart-toggle], [aria-label*="cart" i], [aria-label*="sepet" i], ' +
      '.cart-count-bubble, #cart-icon-bubble, header-drawer [href="/cart"]'
    );
    if (cartBtn) { cartBtn.click(); return; }
    // Fallback: cart event dispatch
    document.dispatchEvent(new CustomEvent('cart:open', { bubbles: true }));
    document.dispatchEvent(new CustomEvent('cart:refresh', { bubbles: true }));
  }

  _saveBlendSilent() {
    // Sepet akışı içinde sessiz kayıt — alert yok
    const s = this._s;
    if (!s.beans?.length || !this.cfg.customerId) return;
    const blend = {
      id: Date.now(),
      name: `${this._typeL(s.type)} · ${s.beans.map(x=>x.title).join(' + ')}`,
      type: s.type, character: s.character, roast: s.roast,
      beans: s.beans.map(x=>({id:x.id,title:x.title,ratio:x.ratio,color:x.color})),
      createdAt: new Date().toISOString(),
    };
    const key = 'kw_blends_' + this.cfg.customerId;
    const arr = JSON.parse(localStorage.getItem(key) || '[]');
    arr.push(blend);
    localStorage.setItem(key, JSON.stringify(arr));
    fetch('/apps/kahve-blend-api/save', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({ customerId: this.cfg.customerId, blend }),
    }).catch(()=>{});
  }

  async saveBlend() {
    if (!this.cfg.customerId) {
      kwToast('Harmanı kaydetmek için hesabınıza giriş yapmanız gerekmektedir.', 'warning');
      window.location.href = '/account/login?return_url=' + encodeURIComponent(window.location.pathname);
      return;
    }
    const s = this._s;
    if (!s.beans?.length) { kwToast('Kaydedilecek bir harman seçilmedi.', 'warning'); return; }

    const blend = {
      id:        Date.now(),
      name:      `${this._typeL(s.type)} · ${s.beans.map(x=>x.title).join(' + ')}`,
      type:      s.type,
      character: s.character,
      roast:     s.roast,
      beans:     s.beans.map(x => ({ id:x.id, title:x.title, ratio:x.ratio, color:x.color })),
      createdAt: new Date().toISOString(),
    };

    // localStorage'a kaydet (hızlı erişim)
    const key = 'kw_blends_' + this.cfg.customerId;
    const arr = JSON.parse(localStorage.getItem(key) || '[]');
    arr.push(blend);
    localStorage.setItem(key, JSON.stringify(arr));

    // Shopify App Proxy varsa oraya da gönder
    try {
      await fetch('/apps/kahve-blend-api/save', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify({ customerId: this.cfg.customerId, blend }),
      });
    } catch {}

    this._loadSavedBlends();
    kwToast('Harmanınız kaydedildi!', 'success');
  }

  _loadSavedBlends() {
    const key   = this.cfg.customerId ? 'kw_blends_' + this.cfg.customerId : 'kw_blends_guest';
    const saved = JSON.parse(localStorage.getItem(key) || '[]');
    const el    = document.getElementById('kw-saved-list');
    if (!el) return;
    if (!saved.length) {
      el.innerHTML = '<p class="kw-saved-empty">Henüz kayıtlı harmanınız bulunmuyor.</p>';
      return;
    }
    el.innerHTML = saved.slice().reverse().slice(0, 10).map(b => `
      <div class="kw-saved-item">
        <div>
          <strong>${b.name}</strong>
          <small>${this._roastL(b.roast)} · ${new Date(b.createdAt).toLocaleDateString('tr-TR')}</small>
        </div>
        <div style="display:flex;gap:6px;flex-shrink:0;">
          <button class="kw-btn kw-btn--ghost kw-btn--sm kw-saved-load" data-id="${b.id}">Yükle</button>
          <button class="kw-btn kw-btn--ghost kw-btn--sm kw-saved-del" data-id="${b.id}" style="color:#c0392b;">Sil</button>
        </div>
      </div>`).join('');
  }

  _loadBlendById(id) {
    const key  = this.cfg.customerId ? 'kw_blends_' + this.cfg.customerId : 'kw_blends_guest';
    const list = JSON.parse(localStorage.getItem(key) || '[]');
    const b    = list.find(x => String(x.id) === String(id));
    if (!b) { this._goStep(1); return; }
    this._s.type      = b.type;
    this._s.character = b.character;
    this._s.roast     = b.roast;
    this._s.beans     = b.beans.map(x => ({
      ...this.catalog.cekirdekler.find(c => c.id === x.id),
      ratio: x.ratio,
    })).filter(x => x && x.id);
    // URL'den gelen blend'de step 4'ten başla
    this._goStep(4);
  }

  _loadBlend(id) {
    const key  = this.cfg.customerId ? 'kw_blends_' + this.cfg.customerId : 'kw_blends_guest';
    const list = JSON.parse(localStorage.getItem(key) || '[]');
    const b    = list.find(x => String(x.id) === String(id));
    if (!b) return;
    this._s.type      = b.type;
    this._s.character = b.character;
    this._s.roast     = b.roast;
    this._s.beans     = b.beans.map(x => ({
      ...this.catalog.cekirdekler.find(c => c.id === x.id),
      ratio: x.ratio,
    })).filter(x => x && x.id);
    this._goStep(4); // kavurma adımına git (seçim gözden geçirilebilsin)
    kwToast(`"${b.name}" yüklendi.`, 'success');
  }

  async _deleteBlend(id) {
    const ok = await kwConfirm('Bu harman silinecek. Emin misiniz?');
    if (!ok) return;
    const key = this.cfg.customerId ? 'kw_blends_' + this.cfg.customerId : 'kw_blends_guest';
    try {
      const list = JSON.parse(localStorage.getItem(key) || '[]');
      const filtered = list.filter(x => String(x.id) !== String(id));
      localStorage.setItem(key, JSON.stringify(filtered));
    } catch(e) {}
    this._loadSavedBlends();
    kwToast('Harman silindi.', 'info');
  }

  _renderAmbalajStep() {
    const s    = this._s;
    const cont = document.getElementById('kw-ambalaj-step');
    if (!cont) return;

    const activePkgs = (s.packages||[]).filter(p=>p.count>0);
    if (!activePkgs.length) {
      cont.innerHTML = '<p class="kw-empty">Önce paket adedi seçin (Adım 6).</p>';
      return;
    }

    // Unique tipler
    const types = {};
    this.catalog.ambalajlar.forEach(a => {
      if (!types[a.productTitle]) types[a.productTitle] = { img: a.img, variants: [] };
      types[a.productTitle].variants.push(a);
    });

    cont.innerHTML = activePkgs.map(pkg => {
      const sizeLabel  = KW_PKG[pkg.sizeGr]?.label || pkg.sizeGr + 'gr';
      const currentType = s.pkgDesigns[pkg.sizeGr] || '';

      const typeCards = Object.keys(types).map(title => {
        const data = types[title];
        const v    = data.variants.find(a => a.sizeGr === pkg.sizeGr);
        if (!v) return '';
        const hasStock  = v.stock === 9999 || v.stock > 0;
        const isSelected = currentType === title;
        const shortName = title.replace(' Ambalaj','');
        const imgUrl    = data.img || '';

        return `<div class="kw-amb-card${isSelected?' kw-amb-card--selected':''}${!hasStock?' kw-amb-card--oos':''}"
          data-size="${pkg.sizeGr}" data-type="${title}">
          <div class="kw-amb-card__img" style="background:#f0ece4 ${imgUrl?`url('${imgUrl}') center/contain no-repeat`:''};">
            ${isSelected ? '<div class="kw-amb-card__check">✓</div>' : ''}
            ${!hasStock  ? '<div class="kw-amb-card__oos-badge">Stok Yok</div>' : ''}
          </div>
          <div class="kw-amb-card__body">
            <span class="kw-amb-card__name">${shortName}</span>
          </div>
        </div>`;
      }).filter(Boolean).join('');

      return `<div class="kw-ambalaj-section">
        <div class="kw-amb-section-header">
          <span class="kw-amb-size-badge">${sizeLabel}</span>
          <span class="kw-amb-count">${pkg.count} paket</span>
          ${currentType ? `<span class="kw-amb-selected-label">✓ ${currentType.replace(' Ambalaj','')}</span>` : '<span class="kw-amb-warn">Seçilmedi</span>'}
        </div>
        <div class="kw-amb-grid">${typeCards}</div>
      </div>`;
    }).join('');

    // Click
    cont.querySelectorAll('.kw-amb-card:not(.kw-amb-card--oos)').forEach(card => {
      card.addEventListener('click', () => {
        const sz   = parseInt(card.dataset.size);
        const type = card.dataset.type;
        this._selectPkgDesign(sz, type);
        this._renderAmbalajStep(); // yeniden render
      });
    });
  }

  _selectPkgDesign(sizeGr, productTitle) {
    this._s.pkgDesigns[sizeGr] = productTitle;
    // İlgili paketin variantId'sini güncelle
    const pkg = this._s.packages.find(p => p.sizeGr === sizeGr);
    const v   = this.catalog.ambalajlar.find(a => a.sizeGr === sizeGr && a.productTitle === productTitle);
    if (pkg && v) {
      pkg.variantId    = v.variantId;
      pkg.productTitle = v.productTitle;
      pkg.designCode   = v.designCode;
    }
    this._navBtns(); this._summary(); this._save();
  }

  _renderPreview() {
    // Tasarım seçimi daha önce yapıldıysa yansıt
    if (this._s.designType) {
      document.querySelector(`[data-group="step7-design"][data-value="${this._s.designType}"]`)?.classList.add('selected');
      if (this._s.designType==='custom') {
        document.getElementById('kw-logo-upload-7').style.display='block';
      }
    } else {
      // Varsayılan: standart seç
      this._s.designType = 'generic';
      document.querySelector('[data-group="step7-design"][data-value="generic"]')?.classList.add('selected');
    }
    this._renderOrderPreview();
  }

  _renderOrderPreview() {
    const s = this._s;
    const el = document.getElementById('kw-order-preview');
    if (!el) return;
    const totalPkgs = s.packages?.reduce((a,p)=>a+p.count,0)||0;
    const pkgList = s.packages?.filter(p=>p.count>0).map(p=>`${p.count} × ${KW_PKG[p.sizeGr]?.short}`).join(', ')||'—';
    const beanList = s.beans.map(b=>s.character==='single'?b.title:`${b.title} %${b.ratio}`).join(' + ');
    el.innerHTML = `
      <div class="kw-preview-card">
        <div class="kw-preview-row"><span>Kahve Türü</span><strong>${this._typeL(s.type)}</strong></div>
        <div class="kw-preview-row"><span>Karakter</span><strong>${this._charL(s.character)}</strong></div>
        <div class="kw-preview-row"><span>Çekirdekler</span><strong>${beanList}</strong></div>
        <div class="kw-preview-row"><span>Kavurma</span><strong>${this._roastL(s.roast)}</strong></div>
        <div class="kw-preview-row"><span>Toplam Miktar</span><strong>${s.quantityKg} kg</strong></div>
        <div class="kw-preview-row"><span>Ambalaj</span><strong>${pkgList}</strong></div>
        <div class="kw-preview-row"><span>Tasarım</span><strong>${s.designType==='custom'?'Özel Logo':'Standart'}</strong></div>
      </div>`;
    this._price();
  }

  _logoUpload(e) {
    const f=e.target.files[0]; if(!f) return;
    const maxSize=10*1024*1024;
    if(f.size>maxSize){ alert(window.KW_LANG?.warnings?.logoMaxSize||'Maks 10 MB'); return; }
    this._s.logoFile=f;
    const r=new FileReader();
    r.onload=ev=>{
      this._s.logoUrl=ev.target.result;
      this._renderLogoPreview(ev.target.result, f.name);
      setTimeout(()=>{ if(this._s.step===6) this._refreshPkgUI(); }, 80);
    };
    r.readAsDataURL(f);
    this._navBtns();
  }

  _renderLogoPreview(url, name) {
    const p=document.getElementById('kw-logo-preview');
    if(!p) return;
    p.style.display='flex';
    p.innerHTML=`
      <img src="${url}" alt="logo önizleme" style="height:48px;object-fit:contain;border-radius:4px;flex-shrink:0;">
      <div class="kw-logo-preview__info">
        <span class="kw-logo-name">${name}</span>
        <button class="kw-logo-del-btn" type="button">🗑 Logoyu Sil</button>
      </div>`;
    p.querySelector('.kw-logo-del-btn')?.addEventListener('click', ()=> this._clearLogo());
  }

  _clearLogo() {
    this._s.logoFile=null; this._s.logoUrl=null;
    const p=document.getElementById('kw-logo-preview');
    if(p){ p.style.display='none'; p.innerHTML=''; }
    const inp=document.getElementById('kw-logo-file');
    if(inp) inp.value='';
    if(this._s.step===6) this._refreshPkgUI();
  }

  _navBtns() {
    const nb   = document.getElementById('kw-btn-next');
    const cbtns= document.getElementById('kw-cart-btns');
    const last = this._s.step === this.cfg.totalSteps;
    const valid= this._valid();
    if (nb)    { nb.style.display = last ? 'none' : 'inline-flex'; nb.disabled = !valid; }
    if (cbtns) { cbtns.style.display = last ? 'flex' : 'none'; }
    // Son adımda cart butonları designType seçimine göre aktif/pasif
    if (last) {
      const cartDisabled = !this._s.designType;
      const bc = document.getElementById('kw-btn-cart');
      const bn = document.getElementById('kw-btn-buynow');
      if (bc) bc.disabled = cartDisabled;
      if (bn) bn.disabled = cartDisabled;
    }
    // Özet paneli butonları — tüm adımlar + designType
    const allDone = this._s.type && this._s.character && this._beansOk() &&
                    this._s.roast && this._s.quantityKg >= KW_MIN &&
                    this._pkgsOk() && !!this._s.designType;
    const b2 = document.getElementById('kw-btn-buynow2');
    const b3 = document.getElementById('kw-btn-cart2');
    if (b2) b2.disabled = !allDone;
    if (b3) b3.disabled = !allDone;
  }

  _grindL(v){return{cekirdek:'Çekirdek',filtre:'Filtre Kahve',turk:'Türk Kahvesi'}[v]||'—';}
  _txt(id,v){const e=document.getElementById(id);if(e)e.textContent=v||(window.KW_LANG?.misc?.empty||'—');}
  _typeL(v){const L=window.KW_LANG?.labels; return(L?{filtre:L.filtre,turk:L.turk,espresso:L.espresso}:{filtre:'Filtre Kahve',turk:'Türk Kahvesi',espresso:'Espresso'})[v]||'—';}
  _charL(v){const L=window.KW_LANG?.labels; return(L?{single:L.single,blend:L.blend}:{single:'Single Origin',blend:'Blend (Harman)'})[v]||'—';}
  _roastL(v){const L=window.KW_LANG?.labels; return(L?{light:L.light,medium:L.medium,'full-city':L.fullCity,dark:L.dark}:{light:'Light',medium:'Medium','full-city':'Full City',dark:'Dark'})[v]||'—';}
}

document.addEventListener('DOMContentLoaded',()=>{
  window.kahveWizard=new KahveWizard({
    totalSteps:8,
    currency:window.KW_CONFIG?.currency||'TRY',
    customerId:window.KW_CONFIG?.customerId||''
  });
  // Wizard direkt açık — hero yok
  const ov=document.getElementById('kw-overlay');
  const cl=document.getElementById('kw-close');
  if(ov) ov.style.display='flex';
  if(cl) cl.style.display='none'; // kapat butonu gizli (hero'ya dönüş yok)
  // _loadBg tamamlanınca restore veya adım 1 çalışacak
  // Overlay'i şimdiden göster
});