/* ============ BADEM — Build Your Box ============ */
const {useState, useEffect, useRef, useMemo} = React;
const C = window.BademChoco;
const Cat = window.BademCatalog;

const ARR=<svg className="arr" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M5 12h14M13 6l6 6-6 6"/></svg>;

const SIZES=[
  {n:4,  cols:2, fee:40,  label:'Klasik'},
  {n:9,  cols:3, fee:60,  label:'İkram'},
  {n:16, cols:4, fee:90,  label:'Hediye'},
  {n:21, cols:5, fee:85,  label:'Küçük Kutu', layout:'draje-1'},
  {n:25, cols:5, fee:130, label:'Şölen'}
];
const VELVETS=[
  {id:'cocoa', c:'#3B2418', tr:'Kakao'},
  {id:'bordo', c:'#5C2230', tr:'Bordo'},
  {id:'ink',   c:'#1C2230', tr:'Gece'},
  {id:'forest',c:'#1F3326', tr:'Zümrüt'}
];
const SIGNATURE_FALLBACK=[
  {name:'Antep Fıstıklı Pralin', ds:'Sütlü · fıstık', price:72, st:{shape:'square',type:'milk',filling:'pistachio',decorations:['pistachio_p']}},
  {name:'Dubai Çikolatası',      ds:'Bitter · kadayıf', price:85, st:{shape:'rectangle',type:'dark',filling:'pistachio',decorations:['drizzle']}},
  {name:'Ruby Ahududu',          ds:'Ruby · ahududu', price:78, st:{shape:'heart',type:'ruby',filling:'raspberry',decorations:[]}},
  {name:'Badem Pralin',          ds:'Sütlü · badem', price:68, st:{shape:'oval',type:'milk',filling:'praline',decorations:['almond']}},
  {name:'Tuzlu Karamel',         ds:'Karamel · tuz', price:68, st:{shape:'round',type:'caramel',filling:'caramel',decorations:['gold']}},
  {name:'Bitter Ganaj',          ds:'%70 bitter', price:64, st:{shape:'square',type:'dark',filling:'ganache',decorations:['nibs']}},
  {name:'Beyaz Fıstık',          ds:'Beyaz · fıstık', price:70, st:{shape:'round',type:'white',filling:'pistachio',decorations:['pistachio_p']}},
  {name:'Altın Bitter',          ds:'Bitter · altın', price:92, st:{shape:'square',type:'dark',filling:'ganache',decorations:['gold']}}
];

function Choco({state, size}){
  const ref=useRef();
  useEffect(()=>{ if(ref.current) C.render(ref.current, state); },
    [state.shape,state.type,state.filling,(state.decorations||[]).join(','),state.view]);
  return <div className="choco-wrap" style={{'--size':size}}><div ref={ref}></div></div>;
}

// Slot fotoğı varsa göster, yoksa SVG renderer'a düş
function SlotChoco({item, size, fillColumn=false}){
  const photo = String(item.img_box || item.img_front || '').trim();
  if(photo){
    return fillColumn
      ? <img src={photo} alt={item.name} style={{width:'100%', height:'100%', objectFit:'cover', borderRadius:'inherit', display:'block'}}/>
      : <img src={photo} alt={item.name} style={{width:size, height:size, objectFit:'cover', borderRadius:'6px', display:'block'}}/>;
  }
  return <Choco state={item.st} size={size}/>;
}

function App(){
  const [viewportW,setViewportW]=useState(()=>window.innerWidth||1200);
  const [size,setSize]=useState(9);
  const [slots,setSlots]=useState(()=>{
    const isMock = new URLSearchParams(window.location.search).get('mock')==='true';
    if(isMock){
      try{
        const mockData = JSON.parse(localStorage.getItem('badem_box_mock')||'{}');
        if(mockData.slots && Array.isArray(mockData.slots)){
          localStorage.removeItem('badem_box_mock');
          return mockData.slots;
        }
      }catch(e){}
    }
    return Array(9).fill(null);
  });
  const [velvet,setVelvet]=useState(()=>{
    const isMock = new URLSearchParams(window.location.search).get('mock')==='true';
    if(isMock){
      try{
        const mockData = JSON.parse(localStorage.getItem('badem_box_mock')||'{}');
        if(mockData.velvet) return mockData.velvet;
      }catch(e){}
    }
    return 'cocoa';
  });
  const [boxView,setBoxView]=useState(()=>{
    const isMock = new URLSearchParams(window.location.search).get('mock')==='true';
    return isMock ? 'open' : 'open';
  });
  const [cartN,setCartN]=useState(window.BademCart?window.BademCart.lines():0);
  const [tab,setTab]=useState('choc');
  const [msg,setMsg]=useState('');
  const [from,setFrom]=useState('');
  const [toast,setToast]=useState('');
  const fillCounter=useRef(0);
  const [signatureProducts,setSignatureProducts]=useState(SIGNATURE_FALLBACK);

  useEffect(()=>{
    const onResize=()=>setViewportW(window.innerWidth||1200);
    window.addEventListener('resize', onResize);
    if(window.BademTrack) window.BademTrack('design_start',{mode:'box'});
    return ()=>window.removeEventListener('resize', onResize);
  },[]);

  useEffect(()=>{
    const isMock = new URLSearchParams(window.location.search).get('mock')==='true';
    if(isMock){
      try{
        const mockData = JSON.parse(localStorage.getItem('badem_box_mock')||'{}');
        if(mockData.size && mockData.slots){
          setSize(mockData.size);
          fillCounter.current = Math.max(0, ...(mockData.slots||[]).map((s,i)=>s?i+1:0));
        }
      }catch(e){}
    }
  },[]);

  useEffect(()=>{
    if(!Cat || typeof Cat.onReady !== 'function') return;
    Cat.onReady((all)=>{
      const rows = (Array.isArray(all)?all:[])
        .filter(p => p && p.st && String(p.product_group || 'artisan_chocolate') === 'artisan_chocolate')
        .map(p => ({
          name: p.name,
          ds: p.tag || 'Atölye seçkisi',
          price: Number(p.price || 0),
          st: p.st,
          img_box: p.img_box || '',
          img_front: p.img_front || '',
        }))
        .filter(p => p.price > 0);
      if(rows.length) setSignatureProducts(rows);
    });
  },[]);

  const sz=SIZES.find(s=>s.n===size);
  const cols=sz.cols;
  const isDrajeLayout = sz.layout === 'draje-1';
  // Draje layout: sol 10 slot | tek bütün draje sütunu (index 10) | sağ 10 slot

  // custom designs from configurator cart
  const custom=useMemo(()=>{ try{ return JSON.parse(localStorage.getItem('badem_box')||'[]').filter(x=>x.st && x.kind==='design'); }catch(e){return [];} },[]);

  const changeSize=(n)=>{
    setSize(n);
    setSlots(prev=>{ const a=Array(n).fill(null); for(let i=0;i<Math.min(prev.length,n);i++) a[i]=prev[i]; return a; });
  };

  const nextEmpty = slots.indexOf(null);
  const filledCount = slots.filter(Boolean).length;

  const addItem=(item)=>{
    setSlots(prev=>{ const i=prev.indexOf(null); if(i<0){ setToast('Kutu dolu'); setTimeout(()=>setToast(''),1600); return prev; }
      const a=[...prev]; a[i]={...item, key:++fillCounter.current}; return a; });
  };
  const removeAt=(i)=> setSlots(prev=>{ const a=[...prev]; a[i]=null; return a; });
  const clearAll=()=> setSlots(Array(size).fill(null));
  const chefPool = signatureProducts.length ? signatureProducts : SIGNATURE_FALLBACK;
  const chefPick=()=> setSlots(prev=> prev.map(s=> s || ({...chefPool[Math.floor(Math.random()*chefPool.length)], key:++fillCounter.current}) ));

  const piecesTotal = slots.reduce((a,s)=>a+(s?s.price:0),0);
  const total = piecesTotal + (filledCount>0?sz.fee:0);
  const pct = Math.round(filledCount/size*100);

  const boxW = useMemo(()=>{
    // Future-proof base width: scales with column count instead of fixed presets.
    const target = Math.round(248 + (46 * cols));
    // box-outer width is rendered as boxW+40; keep horizontal safety margin on narrow screens
    const maxFit = Math.max(300, viewportW - 28 - 40);
    return Math.min(target, maxFit);
  },[cols, viewportW]);
  const stageFitW = Math.max(280, viewportW - 28);
  const boxOuterRawW = boxW + 40;
  const boxScale = Math.min(1, stageFitW / boxOuterRawW);
  const slotPx = useMemo(()=>{
    const innerW = boxW - 32;
    if(isDrajeLayout){ return (innerW - 4*10)/4.5; }
    return (innerW - (cols-1)*10)/cols;
  },[boxW, cols, isDrajeLayout]);
  const chocoSize = Math.round(slotPx*0.82)+'px';
  const drajeSize  = Math.round(slotPx*0.5*0.82)+'px';

  const checkout=()=>{
    if(filledCount===0){ setToast('Önce çikolata ekle'); setTimeout(()=>setToast(''),1600); return; }
    if(window.BademCart) {
      window.BademCart.add({
        kind:'box',
        name:`${sz.label} Kutu · ${size}'lı`,
        sub:`${filledCount} parça${msg?' · notlu':''}`,
        unit:total,
        qty:1,
        slots:slots.map(s=>s?s.st:null),
        velvet:velvetColor,
        msg,
        from,
        vat_rate:1,
        product_group:'artisan_chocolate',
      });
    }
    setCartN(window.BademCart?window.BademCart.lines():0);
    if(window.BademTrack) window.BademTrack('design_complete',{mode:'box',pieces:filledCount});
    setToast(`${filledCount} parçalı kutu sepete eklendi`); setTimeout(()=>setToast(''),2400);
  };

  const velvetColor = VELVETS.find(v=>v.id===velvet).c;

  const renderSlot = (s, i, isDraje) => {
    const itemSize = isDraje ? drajeSize : chocoSize;
    return s ? (
      <div key={s.key} className={"slot filled"+(isDraje?' draje':'')} title={s.name}>
        <button className="rm" onClick={()=>removeAt(i)} aria-label="Çıkar">✕</button>
        <SlotChoco item={s} size={itemSize} fillColumn={isDraje}/>
      </div>
    ) : (
      <div key={'e'+i} className={"slot empty"+(isDraje?' draje':'')+(i===nextEmpty?' next':'')} onClick={()=>setTab('choc')}></div>
    );
  };

  return (
    <React.Fragment>
      <div className="cfgbar">
        <a href="index.html" aria-label="Ana sayfaya dön" style={{display:'flex',alignItems:'center',gap:'12px'}}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M15 5l-7 7 7 7"/></svg>
          <img src="assets/badem-logo.png" className="cfgbar__logo" alt="Badem"/>
        </a>
        <div className="cfgbar__steps">Kutunu Hazırla · {sz.label} {size}'lı</div>
        <div className="cfgbar__right" style={{gap:'14px'}}>
          <div className="cfgbar__modes" role="tablist" aria-label="Tasarım modu">
            <a href="configurator.html" className="cfgbar__mode">Tasarla</a>
            <a href="build-your-box.html" className="cfgbar__mode on" aria-current="page">Kutunu Hazırla</a>
          </div>
          <a href="collections.html" className="link-underline cfgbar__link-hide" style={{color:'var(--muted)'}}>Koleksiyonlar</a>
          <a href={localStorage.getItem('badem_customer_token')?'account.html':'login.html'} className="cfgbar__icon" aria-label="Hesabım">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="8" r="4"/><path d="M5 21c0-4 3.5-6 7-6s7 2 7 6"/></svg>
          </a>
          <a href="cart.html" className="btn btn--sm" style={{borderRadius:'100px'}}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M6 8h12l-1 12H7L6 8z"/><path d="M9 8V6.5a3 3 0 0 1 6 0V8"/></svg>
            Sepet{cartN>0?` · ${cartN}`:''}
          </a>
        </div>
      </div>

      <div className="bx">
        {/* ===== STAGE ===== */}
        <div className="bx-stage">
          <div className="bx-head">
            <h1>Kutunu Hazırla</h1>
            <p>Boyutunu seç, her gözü kendin doldur, hediye notunu ekle.</p>
          </div>

          <div className="sizes">
            {SIZES.map(s=>(
              <button key={s.n} className={"size-opt"+(size===s.n?" on":"")} onClick={()=>changeSize(s.n)}>
                <span className="n">{s.n}</span><span className="l">{s.label}</span><span className="pr">+₺{s.fee} kutu</span>
              </button>
            ))}
          </div>

          <div className="boxview-tog">
            <button className={boxView==='open'?'on':''} onClick={()=>setBoxView('open')}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="8" width="18" height="12" rx="2"/><path d="M3 8l3-4h12l3 4"/></svg>Açık Tepsi
            </button>
            <button className={boxView==='closed'?'on':''} onClick={()=>setBoxView('closed')}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="4" y="7" width="16" height="13" rx="2"/><path d="M4 11h16"/></svg>Kapalı Kutu
            </button>
          </div>

          {boxView==='open' ? (
          <div style={{width:boxOuterRawW*boxScale, display:'flex', justifyContent:'center'}}>
            <div style={{width:boxOuterRawW, transform:`scale(${boxScale})`, transformOrigin:'top center'}}>
              {isDrajeLayout ? (
              <div className="box-outer" style={{width:boxW+40}}>
                <div className="box-lid"></div>
                <div className="box-inner box-inner--draje" style={{'--velvet':velvetColor}}>
                  <div className="draje-half">
                    {slots.slice(0,10).map((s,i)=>renderSlot(s,i,false))}
                  </div>
                  <div className="draje-col" style={{width:Math.round(slotPx*0.5)+'px'}}>
                    {renderSlot(slots[10], 10, true)}
                  </div>
                  <div className="draje-half">
                    {slots.slice(11).map((s,i)=>renderSlot(s,i+11,false))}
                  </div>
                </div>
                <span className="box-brand">Badem</span>
              </div>
              ) : (
              <div className="box-outer" style={{width:boxW+40}}>
                <div className="box-lid"></div>
                <div className="box-inner" style={{gridTemplateColumns:`repeat(${cols},1fr)`, '--velvet':velvetColor}}>
                  {slots.map((s,i)=> s ? (
                    <div key={s.key} className="slot filled" title={s.name}>
                      <button className="rm" onClick={()=>removeAt(i)} aria-label="Çıkar">✕</button>
                      <SlotChoco item={s} size={chocoSize}/>
                    </div>
                  ) : (
                    <div key={'e'+i} className={"slot empty"+(i===nextEmpty?" next":"")} onClick={()=>setTab('choc')}></div>
                  ))}
                </div>
                <span className="box-brand">Badem</span>
              </div>
              )}
            </div>
          </div>
          ) : (
          <div className="box-closed" style={{width:boxW+40, height:Math.round((boxW+40)*0.74), '--velvet':velvetColor}}>
            <div className="box-closed__frame"></div>
            <div className="box-closed__seal"><span></span></div>
            <img src="assets/badem-logo.png" className="box-closed__logo" alt="Badem"/>
            <div className="box-closed__kick">Çikolata Atölyesi</div>
            <div className="box-closed__band"><span>{sz.label} Kutu · {size}'lı</span><span><b>{filledCount}</b> parça</span></div>
          </div>
          )}

          <div className="box-actions">
            <button className="ghostbtn" onClick={chefPick}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 3l2.5 5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-1z"/></svg>
              Şefin Seçimi
            </button>
            <button className="ghostbtn" onClick={clearAll}>Temizle</button>
          </div>

          <div className="prog">
            <div className="prog__bar"><div className="prog__fill" style={{width:pct+'%'}}></div></div>
            <div className="prog__lbl"><span>{filledCount} / {size} dolu</span><span>{pct}%</span></div>
          </div>
        </div>

        {/* ===== SIDEBAR ===== */}
        <div className="bx-side">
          <div className="bx-tabs">
            <button className={tab==='choc'?"on":""} onClick={()=>setTab('choc')}>Çikolatalar</button>
            <button className={tab==='gift'?"on":""} onClick={()=>setTab('gift')}>Hediye Notu</button>
          </div>

          {tab==='choc' ? (
            <div className="palette">
              {custom.length>0 && <>
                <p style={{fontFamily:'var(--mono)',fontSize:'11px',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--gold-deep)',margin:'2px 0 12px'}}>Tasarladıkların</p>
                {custom.map((c,idx)=>(
                  <div className="pal-item" key={'c'+idx} onClick={()=>addItem({name:c.name,ds:c.sub||'Özel tasarım',price:(c.unit!=null?c.unit:(parseInt(String(c.price||'').replace(/\D/g,''))||60)),st:c.st})}>
                    <Choco state={c.st} size="46px"/>
                    <div className="info"><div className="nm">{c.name}</div><div className="ds">{c.sub||'Özel tasarım'}</div></div>
                    <span className="pr">{c.price||''}</span>
                    <span className="plus">+</span>
                  </div>
                ))}
                <p style={{fontFamily:'var(--mono)',fontSize:'11px',letterSpacing:'.14em',textTransform:'uppercase',color:'var(--muted)',margin:'18px 0 12px'}}>İmza Çikolatalar</p>
              </>}
              {chefPool.map((p,idx)=>(
                <div className="pal-item" key={idx} onClick={()=>addItem(p)}>
                  <SlotChoco item={p} size="46px"/>
                  <div className="info"><div className="nm">{p.name}</div><div className="ds">{p.ds}</div></div>
                  <span className="pr">₺{p.price}</span>
                  <span className="plus">+</span>
                </div>
              ))}
            </div>
          ) : (
            <div className="gift">
              <label>Kutu Kadifesi</label>
              <div className="velvets">
                {VELVETS.map(v=>(
                  <button key={v.id} className={"velvet-sw"+(velvet===v.id?" on":"")} style={{background:v.c}} onClick={()=>setVelvet(v.id)} title={v.tr}></button>
                ))}
              </div>
              <label>Hediye Notu</label>
              <textarea maxLength={160} value={msg} onChange={e=>setMsg(e.target.value)} placeholder="Sevdiklerine birkaç kelime yaz…"></textarea>
              <div className="cc">{msg.length}/160</div>
              <input style={{width:'100%',marginTop:'14px',border:'1px solid var(--line-2)',borderRadius:'100px',padding:'12px 18px',fontFamily:'var(--sans)',fontSize:'13.5px',outline:'none',background:'var(--cream)'}}
                placeholder="Gönderen (opsiyonel)" value={from} onChange={e=>setFrom(e.target.value)} maxLength={40}/>
              <div className="cardprev">
                <div className="msg">{msg||<span style={{color:'var(--muted-2)'}}>Notun burada görünecek…</span>}</div>
                {from && <div className="from">— {from}</div>}
              </div>
            </div>
          )}

          <div className="bx-foot">
            <div className="bx-foot__row">
              <span className="l">Kutu ({sz.label} · {size})<br/><span className="sm">{filledCount} parça {filledCount>0?`· +₺${sz.fee} kutu`:''}</span></span>
              <span className="total">₺{total.toLocaleString('tr-TR')}</span>
            </div>
            <button className="btn btn--lg btn--block" onClick={checkout}>Sepete Ekle {ARR}</button>
          </div>
        </div>
      </div>

      <div className={"app-toast"+(toast?" show":"")}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12l5 5L20 7"/></svg>
        {toast}
      </div>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App/>);
