/* ============================================================
   Nuad Now — Shop (เหรียญ 🪙 / บัตรกันขาด / แต่ง avatar + ห้องลองชุด)  (JSX)
   ข้อมูลจาก schema-shop.sql + schema-shop2.sql — การซื้อ/ใส่ของตรวจกติกาในฐานข้อมูล (RPC)
   ภาพไอเท็มวาดเป็น SVG ใน app-avatar.jsx
   ============================================================ */

const COIN_RULES = [
  { ic:'☀️', th:'เช็คอินรายวัน',        en:'Daily check-in',     c:'+2',  noteTh:'วันละครั้ง',               noteEn:'once a day' },
  { ic:'💆', th:'นวดเสร็จ',             en:'Finish a massage',   c:'+10', noteTh:'เมื่อแอดมินเช็คชื่อ',       noteEn:'when checked in by admin' },
  { ic:'📝', th:'ทำแบบสอบถาม',          en:'Survey',             c:'+5',  noteTh:'ครั้งละ 1 การนวด',          noteEn:'per massage' },
  { ic:'🎡', th:'วงล้อรายวัน',           en:'Daily wheel',        c:'1-20', noteTh:'หมุนวันละครั้ง หรือลุ้นไอเท็ม', noteEn:'spin once a day, or win items' },
  { ic:'💗', th:'กดหัวใจโน้ต',           en:'Like a note',        c:'+1',  noteTh:'วันละครั้ง',               noteEn:'once a day' },
  { ic:'📌', th:'โพสต์โน้ตบนบอร์ด',      en:'Post a note',        c:'+3',  noteTh:'วันละ 1 โพสต์',            noteEn:'1 post a day' },
  { ic:'💬', th:'คอมเมนต์โพสต์เพื่อน',   en:'Comment on a note',  c:'+1',  noteTh:'สูงสุดวันละ 3 (ไม่นับโพสต์ตัวเอง)', noteEn:'max 3 a day (not your own notes)' },
];

const RARITY_LABEL = { rare:['หายาก','Rare'], epic:['พิเศษ','Epic'] };

function Shop({user, items=[], wallet, coins=0, season=null, onBuy, onEquip, onOutfit, onSell, onGift, people=[]}){
  const en = window.NN_LANG==='en';
  const [sellT,setSellT] = React.useState(null);   // ไอเท็มที่กำลังจะขายคืน
  const [giftT,setGiftT] = React.useState(null);   // { item, to:{id,name}|null, q:'' }
  const [cat,setCat]         = React.useState('all');
  const [tryOn,setTryOn]     = React.useState({});     // { slot: item_id | null(ถอด) } — ลองชุดโดยยังไม่ซื้อ
  const [confirm,setConfirm] = React.useState(null);   // { items:[...], outfit?:{slot:item|null} }
  const [busy,setBusy]       = React.useState(false);
  const [slotsOpen,setSlotsOpen] = React.useState(false);   // มือถือ: รายละเอียดชุดพับไว้
  const [mobile,setMobile]   = React.useState(()=> !!(window.matchMedia && window.matchMedia('(max-width:900px)').matches));
  React.useEffect(()=>{
    if(!window.matchMedia) return;
    const mq = window.matchMedia('(max-width:900px)');
    const on = () => setMobile(mq.matches);
    mq.addEventListener ? mq.addEventListener('change', on) : mq.addListener(on);
    window.addEventListener('resize', on);      // เผื่อเบราว์เซอร์/โหมดจำลองไม่ยิง change
    on();
    return ()=>{
      mq.removeEventListener ? mq.removeEventListener('change', on) : mq.removeListener(on);
      window.removeEventListener('resize', on);
    };
  },[]);

  const nm   = i => en ? i.name_en : i.name_th;
  const ds   = i => en ? i.desc_en : i.desc_th;
  const byId = {}; items.forEach(i=>{ byId[i.id]=i; });
  const inv  = {}; (wallet.inventory||[]).forEach(r=>{ inv[r.item_id]=r; });
  const seasonNo    = season?.no || 1;
  const seasonStart = season?.start;
  const myName = user.nickname||user.name;

  /* ── บัตรกันขาด ── */
  const freeze      = items.find(i=>i.kind==='freeze');
  const freezeHeld  = freeze ? (inv[freeze.id]?.qty||0) : 0;
  const freezeBuys  = freeze ? (wallet.events||[]).filter(e=>e.reason==='buy_'+freeze.id && (!seasonStart||e.event_date>=seasonStart)).length : 0;
  const freezeUsed  = (wallet.freezeUses||[]).length;
  // เหตุผลที่ซื้อไม่ได้ — แสดงเป็นข้อความใต้ปุ่ม ส่วนราคาแสดงตลอด
  const freezeBlock = !freeze ? null
    : freezeHeld>=2 ? (en?'You hold the max (2)':'ถือครบ 2 ใบแล้ว')
    : freezeBuys>=3 ? (en?'Season limit reached':'ซื้อครบโควตาซีซั่นแล้ว')
    : coins<freeze.price ? (en?`Need ${freeze.price-coins} more coins`:`ต้องการอีก ${freeze.price-coins} เหรียญ`)
    : null;

  /* ── ชุดที่ใส่อยู่ + ชุดที่กำลังลอง ── */
  const equipped = {};
  (wallet.inventory||[]).forEach(r=>{ const it=byId[r.item_id]; if(it && it.kind!=='freeze' && r.equipped) equipped[it.kind]=it.id; });
  const previewLook = {...equipped};
  Object.keys(tryOn).forEach(k=>{ if(tryOn[k]===null) delete previewLook[k]; else previewLook[k]=tryOn[k]; });

  const changedSlots = AV_SLOTS.map(s=>s.k).filter(k=>previewLook[k]!==equipped[k]);
  const needBuy      = changedSlots.map(k=>previewLook[k]).filter(id=>id && !inv[id]).map(id=>byId[id]).filter(Boolean);
  const needTotal    = needBuy.reduce((s,i)=>s+i.price,0);
  const outfitDiff   = {}; changedSlots.forEach(k=>{ outfitDiff[k]=previewLook[k]||null; });

  const toggleTry = i => {
    setTryOn(t=>{ const n={...t}; if(n[i.kind]===i.id) delete n[i.kind]; else n[i.kind]=i.id; return n; });
  };
  const clearSlot = k => setTryOn(t=>{ const n={...t}; delete n[k]; return n; });

  /* ── รายการสินค้าที่แสดง ── */
  const visible = items.filter(i=>i.kind!=='freeze' && (inv[i.id] || !i.season_no || i.season_no===seasonNo));
  const shown   = visible.filter(i=> cat==='all' ? true : cat==='owned' ? !!inv[i.id] : i.kind===cat);
  const cats = [{k:'all',th:'ทั้งหมด',en:'All'}, ...AV_SLOTS, {k:'owned',th:'ของฉัน',en:'Owned'}];

  const reasonLabel = r => {
    const m = {
      earn_login:   ['เช็คอินรายวัน','Daily check-in'],
      earn_like:    ['กดหัวใจโน้ต','Liked a note'],
      earn_survey:  ['ทำแบบสอบถาม','Survey'],
      earn_booking: ['นวดเสร็จ','Massage done'],
      earn_note:    ['โพสต์โน้ต','Posted a note'],
      earn_comment: ['คอมเมนต์','Comment'],
      earn_wheel:   ['วงล้อรายวัน','Daily wheel'],
    };
    if(m[r]) return m[r][en?1:0];
    if(r.startsWith('buy_')){
      const it = byId[r.slice(4)];
      return (en?'Bought ':'ซื้อ ') + (it ? nm(it) : r.slice(4));
    }
    if(r.startsWith('sell_')){
      const it = byId[r.slice(5)];
      return (en?'Sold ':'ขายคืน ') + (it ? nm(it) : r.slice(5));
    }
    if(r.startsWith('gift_')){
      const it = byId[r.slice(5)];
      return (en?'Gift: ':'ของขวัญ: ') + (it ? nm(it) : r.slice(5));
    }
    return r;
  };
  // ประวัติแสดงเฉพาะซีซั่นปัจจุบัน และไม่แสดงรายการปรับยอดรีเซตเหรียญ (ยอดรวมยังคิดครบ)
  const history = (wallet.events||[]).filter(e=>e.reason!=='reset_season1' && (!seasonStart || e.event_date>=seasonStart));

  const doConfirm = async () => {
    if(!confirm || busy) return;
    setBusy(true);
    let ok = true;
    for(let n=0; n<confirm.items.length; n++){
      ok = await onBuy(confirm.items[n], n < confirm.items.length-1);   // ชิ้นสุดท้ายเท่านั้นที่แจ้งเตือน
      if(!ok) break;
    }
    if(ok && confirm.outfit) await onOutfit(confirm.outfit);            // ซื้อแล้วใส่ตามชุดที่ลอง (รวมช่องที่ถอดออก)
    if(ok) setTryOn({});
    setBusy(false);
    setConfirm(null);
  };

  const applyOutfit = async () => {
    if(changedSlots.length===0 || busy) return;
    if(needBuy.length>0){ setConfirm({items:needBuy, outfit:outfitDiff}); return; }
    setBusy(true);
    const ok = await onOutfit(outfitDiff);
    if(ok) setTryOn({});
    setBusy(false);
  };

  const Art = ({it}) => {
    if(it.kind==='namecolor')
      return <span className={`nc-${it.id.replace('name_','')}`} style={{fontSize:'1.2rem'}}>{myName}</span>;
    if(it.kind==='title')
      return <span className="user-title" style={{margin:0,fontSize:'.8rem'}}>{nm(it)}</span>;
    return <GenderAvatar look={{[it.kind]:it.id}} gender={user.gender} name={myName} size={64}/>;
  };

  const h2 = {fontFamily:'var(--font-display)', fontWeight:700, fontSize:'1.05rem', marginBottom:10};
  const slotName = s => en ? s.en : s.th;

  return (
    <div className="fade-in">
      <div className="row" style={{justifyContent:'space-between', flexWrap:'wrap', gap:10, marginBottom:6}}>
        <div className="row" style={{gap:10}}>
          <span style={{color:'var(--gold-600)'}}><Icon name="bag" size={26}/></span>
          <h1 style={{fontSize:'1.7rem'}}>{en?'Shop':'ร้านค้า'}</h1>
        </div>
        <div className="chip gold" style={{fontSize:'1.1rem', padding:'.35em 1em', fontWeight:800}}>🪙 {coins}</div>
      </div>
      <p className="muted" style={{marginBottom:16, fontSize:'.9rem'}}>
        {en ? 'Earn coins from your activity and spend them on items. Coins never lower your ranking points and carry over between seasons.'
            : 'สะสมเหรียญจากกิจกรรมต่าง ๆ แล้วแลกไอเท็ม — เหรียญไม่ลดแต้มจัดอันดับ และสะสมข้ามซีซั่นได้'}
      </p>

      {/* ── บัตรกันขาด ── */}
      {freeze && (
        <div className="card pad shop-freeze" style={{marginBottom:16, borderColor:'var(--sage-600)'}}>
          <div className="shop-freeze-top">
            <div className="shop-freeze-ic">{freeze.emoji||'🛡️'}</div>
            <div style={{flex:1, minWidth:0}}>
              <div className="row" style={{gap:8, flexWrap:'wrap', alignItems:'baseline'}}>
                <span style={{fontFamily:'var(--font-display)', fontWeight:800, fontSize:'1.15rem'}}>{nm(freeze)}</span>
                <span className="chip gold" style={{fontSize:'.8rem', padding:'.1em .7em', fontWeight:800}}>🪙 {freeze.price} {en?'each':'/ ใบ'}</span>
              </div>
              <div className="muted" style={{fontSize:'.82rem', marginTop:3}}>{ds(freeze)}</div>
            </div>
          </div>
          <div className="shop-freeze-bottom">
            <div className="row" style={{gap:6, flexWrap:'wrap', flex:1}}>
              <span className="chip sage" style={{fontSize:'.74rem'}}>🛡️ {en?`Holding ${freezeHeld}/2`:`ถืออยู่ ${freezeHeld}/2 ใบ`}</span>
              <span className="chip ghost" style={{fontSize:'.74rem'}}>{en?`Bought ${freezeBuys}/3 this season`:`ซื้อแล้ว ${freezeBuys}/3 ในซีซั่นนี้`}</span>
              {freezeUsed>0 && <span className="chip ghost" style={{fontSize:'.74rem'}}>{en?`Saved your streak ${freezeUsed}×`:`ช่วย streak ไว้ ${freezeUsed} ครั้ง`}</span>}
            </div>
            <div className="shop-freeze-buy">
              <button className="btn sage" disabled={!!freezeBlock} onClick={()=>setConfirm({items:[freeze]})}>
                {en?'Buy':'ซื้อ'} 🪙 {freeze.price}
              </button>
              {freezeBlock && <div className="shop-freeze-note">{freezeBlock}</div>}
            </div>
          </div>
        </div>
      )}

      {/* ── แต่ง avatar: ห้องลองชุด + รายการสินค้า ── */}
      <div className="shop-layout" style={{marginBottom:16}}>
        <div className="card pad shop-preview">
          <div className="sp-title" style={h2}>🪞 {en?'Fitting room':'ห้องลองชุด'}</div>
          <div className="sp-main">
            <div className="sp-avatar"><GenderAvatar look={previewLook} gender={user.gender} name={myName} size={mobile?76:120}/></div>
            <div className="sp-info">
              <div className="sp-name"><ChampName look={previewLook} name={myName}/><UserTitle look={previewLook}/></div>
              <div className="sp-hint">
                {changedSlots.length>0
                  ? (en?`Trying ${changedSlots.length} change(s)`:`กำลังลอง ${changedSlots.length} รายการ`)
                  : (en?'Tap “Try” on any item to preview it here':'กด “ลอง” ที่ไอเท็มเพื่อดูบน avatar')}
              </div>
              <div className="sp-actions">
                <button className="btn gold block" disabled={changedSlots.length===0 || busy || (needBuy.length>0 && coins<needTotal)} onClick={applyOutfit}>
                  {changedSlots.length===0 ? (en?'Nothing to change':'ยังไม่มีการเปลี่ยนชุด')
                    : needBuy.length>0 ? (en?`Buy ${needBuy.length} & wear · 🪙 ${needTotal}`:`ซื้อ ${needBuy.length} ชิ้น แล้วใส่ · 🪙 ${needTotal}`)
                    : (en?'Wear this outfit':'ใส่ชุดนี้')}
                </button>
                {needBuy.length>0 && coins<needTotal && <div style={{fontSize:'.74rem', color:'var(--bad)'}}>{en?`Need ${needTotal-coins} more coins`:`ต้องการอีก ${needTotal-coins} เหรียญ`}</div>}
                {Object.keys(tryOn).length>0 && <button className="btn ghost sm" onClick={()=>setTryOn({})}>{en?'Clear try-ons':'ล้างการลอง'}</button>}
              </div>
            </div>
          </div>
          <button className="sp-toggle" onClick={()=>setSlotsOpen(o=>!o)}>
            {slotsOpen ? (en?'Hide outfit details':'ซ่อนรายละเอียดชุด') : (en?'Show outfit details':'ดูรายละเอียดชุด')}
          </button>
          <div className={`shop-slots ${slotsOpen?'open':''}`}>
            {AV_SLOTS.map(s=>{
              const id = previewLook[s.k]; const it = id && byId[id];
              const trying = Object.prototype.hasOwnProperty.call(tryOn, s.k);
              return (
                <div key={s.k} className="row" style={{gap:6, fontSize:'.78rem', minHeight:22}}>
                  <span className="muted" style={{width:62, flexShrink:0}}>{slotName(s)}</span>
                  <span style={{flex:1, minWidth:0, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', fontWeight:it?600:400, color:it?'var(--ink)':'var(--ink-300)'}}>
                    {it ? `${it.emoji||''} ${nm(it)}` : '—'}
                  </span>
                  {trying && <>
                    <span className="chip gold" style={{fontSize:'.62rem', padding:'0 .5em'}}>{en?'try':'ลอง'}</span>
                    <button onClick={()=>clearSlot(s.k)} title={en?'Undo':'ยกเลิกการลอง'}
                      style={{border:'none', background:'none', cursor:'pointer', color:'var(--ink-300)', fontSize:'.9rem', padding:0}}>✕</button>
                  </>}
                </div>
              );
            })}
          </div>
        </div>

        <div className="card pad">
          <div style={h2}>👗 {en?'Avatar items':'ไอเท็มแต่ง avatar'}</div>
          <div className="shop-cats">
            {cats.map(c=>(
              <button key={c.k} className={`chip ${cat===c.k?'plum':'ghost'}`} style={{cursor:'pointer', fontSize:'.8rem'}} onClick={()=>setCat(c.k)}>
                {en?c.en:c.th}
              </button>
            ))}
          </div>
          {shown.length===0
            ? <div className="muted" style={{fontSize:'.88rem', padding:'18px 0', textAlign:'center'}}>{en?'No items here yet':'ยังไม่มีไอเท็มในหมวดนี้'}</div>
            : <div className="shop-grid">
                {shown.map(i=>{
                  const own = inv[i.id];
                  const on  = !!own?.equipped;
                  const trying = tryOn[i.kind]===i.id;
                  return (
                    <div key={i.id} className="card flat shop-item"
                      style={{borderColor: trying ? 'var(--gold-600)' : on ? 'var(--accent)' : undefined}}>
                      <div className="shop-item-art"><Art it={i}/></div>
                      <div className="shop-item-name">{i.emoji} {nm(i)}</div>
                      <div className="row" style={{gap:4, justifyContent:'center', flexWrap:'wrap', minHeight:16}}>
                        {RARITY_LABEL[i.rarity] && <span className={`chip rarity-${i.rarity}`} style={{fontSize:'.62rem', padding:'0 .55em'}}>{RARITY_LABEL[i.rarity][en?1:0]}</span>}
                        {i.season_no && <span className="chip gold" style={{fontSize:'.62rem', padding:'0 .55em'}}>{NN.seasonLabel(i.season_no,en)} {en?'only':'เท่านั้น'}</span>}
                      </div>
                      <div className="shop-item-actions">
                        <button className={`btn sm ${trying?'secondary':'ghost'}`} onClick={()=>toggleTry(i)}>
                          {trying ? (en?'Undo':'เลิกลอง') : (en?'Try':'ลอง')}
                        </button>
                        {own
                          ? <button className={`btn sm ${on?'secondary':''}`} onClick={()=>onEquip(i,!on)}>{on?(en?'Remove':'ถอด'):(en?'Wear':'ใส่')}</button>
                          : <button className="btn sm gold" disabled={coins<i.price} onClick={()=>setConfirm({items:[i]})}>🪙 {i.price}</button>}
                      </div>
                      <div className="row" style={{gap:10, justifyContent:'center', marginTop:6, fontSize:'.74rem'}}>
                        {own && <button className="shop-link" onClick={()=>setSellT(i)}>{en?`Sell 🪙${Math.floor(i.price/2)}`:`ขายคืน 🪙${Math.floor(i.price/2)}`}</button>}
                        <button className="shop-link" onClick={()=>setGiftT({item:i, to:null, q:''})}>🎁 {en?'Gift':'ส่งของขวัญ'}</button>
                      </div>
                    </div>
                  );
                })}
              </div>}
          <div className="muted" style={{fontSize:'.74rem', marginTop:12}}>
            {en ? 'Champions get a default gold/silver/bronze ring, crown and gold name — any frame, hat or name color you wear replaces that slot. The medal at the corner always stays.'
                : 'แชมป์ซีซั่นที่ผ่านมามีกรอบ/มงกุฎ/ชื่อสีทองเป็นค่าเริ่มต้น — ถ้าใส่กรอบ หมวก หรือสีชื่อจากร้าน จะไปแทนที่ช่องนั้น ส่วนเหรียญที่มุมยังอยู่เสมอ'}
          </div>
        </div>
      </div>

      {/* ── วิธีได้เหรียญ (มือถือพับไว้) ── */}
      <details className="card pad shop-details" open={!mobile} style={{marginBottom:16}}>
        <summary>🪙 {en?'How to earn coins':'วิธีได้เหรียญ'}</summary>
        <div className="shop-rules">
          {COIN_RULES.map(r=>(
            <div key={r.th} className="row card flat" style={{gap:10, padding:'10px 12px', alignItems:'center'}}>
              <span style={{fontSize:'1.4rem'}}>{r.ic}</span>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontFamily:'var(--font-display)', fontWeight:600, fontSize:'.88rem'}}>{en?r.en:r.th}</div>
                <div className="muted" style={{fontSize:'.72rem'}}>{en?r.noteEn:r.noteTh}</div>
              </div>
              <span className="chip gold" style={{fontSize:'.78rem', padding:'.15em .6em'}}>{r.c} 🪙</span>
            </div>
          ))}
        </div>
      </details>

      {/* ── ประวัติเหรียญ (มือถือพับไว้) ── */}
      <details className="card pad shop-details" open={!mobile}>
        <summary>📜 {en?'Recent coin activity':'ประวัติเหรียญล่าสุด'}</summary>
        {history.length===0
          ? <div className="muted" style={{fontSize:'.85rem'}}>{en?'Nothing yet — check in to earn your first coins!':'ยังไม่มีรายการ — เช็คอินเพื่อรับเหรียญแรก!'}</div>
          : <div style={{display:'flex', flexDirection:'column'}}>
              {history.slice(0,mobile?5:8).map((e,i,a)=>(
                <div key={e.id} className="row" style={{gap:10, padding:'8px 2px', borderBottom:i<a.length-1?'1.5px solid var(--cream-200)':'none'}}>
                  <div style={{flex:1, fontSize:'.86rem'}}>{reasonLabel(e.reason)}</div>
                  <div className="muted" style={{fontSize:'.74rem'}}>{e.event_date}</div>
                  <div style={{fontFamily:'var(--font-display)', fontWeight:800, minWidth:44, textAlign:'right',
                    color:e.delta>0?'var(--sage-600)':'var(--bad)'}}>{e.delta>0?'+':''}{e.delta}</div>
                </div>
              ))}
            </div>}
      </details>

      {/* ── มือถือ: แถบลอยตอนกำลังลองชุด (ไม่ต้องเลื่อนกลับไปดู avatar) ── */}
      {mobile && Object.keys(tryOn).length>0 && ReactDOM.createPortal(
        <div className="sp-dock">
          <GenderAvatar look={previewLook} gender={user.gender} name={myName} size={46}/>
          <div style={{flex:1, minWidth:0}}>
            <div className="sp-dock-t">{en?`Trying ${Object.keys(tryOn).length}`:`กำลังลอง ${Object.keys(tryOn).length} รายการ`}</div>
            <div className="sp-dock-s">{needBuy.length>0 ? (en?`${needBuy.length} to buy · 🪙 ${needTotal}`:`ต้องซื้อ ${needBuy.length} ชิ้น · 🪙 ${needTotal}`) : (en?'Ready to wear':'ใส่ได้เลย')}</div>
          </div>
          <button className="btn sm gold" disabled={changedSlots.length===0 || busy || (needBuy.length>0 && coins<needTotal)} onClick={applyOutfit}>
            {needBuy.length>0 ? (en?'Buy & wear':'ซื้อ+ใส่') : (en?'Wear':'ใส่ชุดนี้')}
          </button>
          <button className="sp-dock-x" onClick={()=>setTryOn({})} aria-label={en?'Clear':'ล้าง'}>✕</button>
        </div>,
        document.body
      )}
      {mobile && Object.keys(tryOn).length>0 && <div style={{height:70}}/>}

      {/* ── ยืนยันการซื้อ ── */}
      {confirm && ReactDOM.createPortal(
        <div className="overlay" onClick={()=>!busy&&setConfirm(null)}>
          <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:380}}>
            {confirm.items.length===1
              ? <>
                  <div style={{fontSize:'2.4rem', lineHeight:1}}>{confirm.items[0].emoji}</div>
                  <h2 style={{fontSize:'1.3rem', margin:'8px 0 4px'}}>{en?'Buy ':'ซื้อ '}{nm(confirm.items[0])}?</h2>
                </>
              : <>
                  <h2 style={{fontSize:'1.3rem', margin:'0 0 8px'}}>{en?`Buy ${confirm.items.length} items?`:`ซื้อ ${confirm.items.length} ชิ้น?`}</h2>
                  <div style={{textAlign:'left', margin:'0 0 10px', fontSize:'.9rem'}}>
                    {confirm.items.map(i=>(
                      <div key={i.id} className="row" style={{gap:8, padding:'3px 0'}}>
                        <span>{i.emoji}</span><span style={{flex:1}}>{nm(i)}</span><span className="muted">🪙 {i.price}</span>
                      </div>
                    ))}
                  </div>
                </>}
            {(() => { const total = confirm.items.reduce((s,i)=>s+i.price,0); return (
              <p className="muted" style={{fontSize:'.9rem', margin:'0 0 16px'}}>
                {en ? `Costs 🪙 ${total} — you'll have 🪙 ${coins-total} left.`
                    : `ราคา 🪙 ${total} — เหลือ 🪙 ${coins-total}`}
              </p>); })()}
            <div className="row" style={{gap:10, justifyContent:'center'}}>
              <button className="btn secondary" disabled={busy} onClick={()=>setConfirm(null)}>{en?'Cancel':'ยกเลิก'}</button>
              <button className="btn gold" disabled={busy} onClick={doConfirm}>{busy?'...':(en?'Confirm':'ยืนยัน')}</button>
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* ── ยืนยันขายคืน ── */}
      {sellT && ReactDOM.createPortal(
        <div className="overlay" onClick={()=>!busy&&setSellT(null)}>
          <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:380}}>
            <div style={{fontSize:'2.4rem', lineHeight:1}}>{sellT.emoji}</div>
            <h2 style={{fontSize:'1.3rem', margin:'8px 0 4px'}}>{en?'Sell ':'ขายคืน '}{nm(sellT)}?</h2>
            <p className="muted" style={{fontSize:'.9rem', margin:'0 0 8px'}}>
              {en ? `You get 🪙 ${Math.floor(sellT.price/2)} (50% of 🪙 ${sellT.price}) and lose the item.`
                  : `ได้รับ 🪙 ${Math.floor(sellT.price/2)} (50% ของ 🪙 ${sellT.price}) และไอเท็มจะหายไปจากกระเป๋า`}
            </p>
            {sellT.season_no && sellT.season_no!==seasonNo &&
              <p style={{fontSize:'.82rem', color:'var(--bad)', margin:'0 0 8px'}}>
                {en?'This item is no longer on sale — you won\'t be able to buy it back.':'ไอเท็มนี้เลิกขายแล้ว ขายไปแล้วซื้อกลับไม่ได้'}
              </p>}
            <div className="row" style={{gap:10, justifyContent:'center', marginTop:12}}>
              <button className="btn secondary" disabled={busy} onClick={()=>setSellT(null)}>{en?'Cancel':'ยกเลิก'}</button>
              <button className="btn gold" disabled={busy} onClick={async()=>{ setBusy(true); await onSell(sellT); setBusy(false); setSellT(null); }}>{busy?'...':(en?'Sell':'ขายคืน')}</button>
            </div>
          </div>
        </div>,
        document.body
      )}

      {/* ── ส่งของขวัญ: เลือกเพื่อน → ยืนยัน ── */}
      {giftT && ReactDOM.createPortal(
        <div className="overlay" onClick={()=>!busy&&setGiftT(null)}>
          <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:400}}>
            <div style={{fontSize:'2.4rem', lineHeight:1}}>🎁</div>
            <h2 style={{fontSize:'1.3rem', margin:'8px 0 4px'}}>{en?'Gift ':'ส่ง '}{giftT.item.emoji} {nm(giftT.item)}</h2>
            <p className="muted" style={{fontSize:'.88rem', margin:'0 0 10px'}}>
              {en ? `Costs 🪙 ${giftT.item.price} — you'll have 🪙 ${coins-giftT.item.price} left.`
                  : `ราคา 🪙 ${giftT.item.price} — เหลือ 🪙 ${coins-giftT.item.price}`}
            </p>
            {giftT.to
              ? <div className="row card flat" style={{gap:10, padding:'8px 12px', justifyContent:'center', marginBottom:12}}>
                  <span>{en?'To':'ถึง'}</span><b>{giftT.to.name}</b>
                  <button className="shop-link" onClick={()=>setGiftT(g=>({...g,to:null}))}>{en?'change':'เปลี่ยน'}</button>
                </div>
              : (() => {
                  const q = giftT.q.trim().toLowerCase();
                  const list = people.filter(p=>p.id!==user.employee_id && (!q ||
                    [p.name,p.nickname,p.thai_firstname,p.thai_lastname,p.english_firstname,p.english_lastname].some(s=>s && String(s).toLowerCase().includes(q))
                  )).slice(0,8);
                  return <>
                    <input value={giftT.q} onChange={e=>setGiftT(g=>({...g,q:e.target.value}))} autoFocus
                      placeholder={en?'Search a friend…':'ค้นหาชื่อเพื่อน…'}
                      style={{width:'100%', boxSizing:'border-box', marginBottom:8}}/>
                    <div style={{display:'flex', flexDirection:'column', maxHeight:220, overflowY:'auto', textAlign:'left', marginBottom:12}}>
                      {list.length===0 && <div className="muted" style={{fontSize:'.85rem', padding:8, textAlign:'center'}}>{en?'No one found':'ไม่พบเพื่อน'}</div>}
                      {list.map(p=>(
                        <button key={p.id} className="row" onClick={()=>setGiftT(g=>({...g,to:{id:p.id,name:p.name}}))}
                          style={{gap:10, padding:'6px 4px', border:'none', background:'none', cursor:'pointer', textAlign:'left', alignItems:'center'}}>
                          <GenderAvatar empId={p.id} gender={p.gender} name={p.name} size={32}/>
                          <span style={{flex:1}}>{p.name}</span>
                          <span className="muted" style={{fontSize:'.74rem'}}>{p.dept}</span>
                        </button>
                      ))}
                    </div>
                  </>;
                })()}
            <div className="row" style={{gap:10, justifyContent:'center'}}>
              <button className="btn secondary" disabled={busy} onClick={()=>setGiftT(null)}>{en?'Cancel':'ยกเลิก'}</button>
              <button className="btn gold" disabled={busy || !giftT.to || coins<giftT.item.price}
                onClick={async()=>{ setBusy(true); const ok=await onGift(giftT.item, giftT.to); setBusy(false); if(ok) setGiftT(null); }}>
                {busy?'...':(coins<giftT.item.price ? (en?'Not enough coins':'เหรียญไม่พอ') : (en?'Send gift':'ส่งของขวัญ'))}
              </button>
            </div>
          </div>
        </div>,
        document.body
      )}
    </div>
  );
}

Object.assign(window, { Shop });
