/* ============================================================
   ui.jsx — общие компоненты: хедер, нав, валюта, карточка подарка,
   bottom-sheet, модалка, dev-пин.
   ============================================================ */
const { useState, useRef, useEffect } = React;

// мягкое радиальное свечение под эмодзи по редкости
function rarityGlow(rarityKey){
  const hex = RARITY[rarityKey].hex;
  return `radial-gradient(75% 75% at 50% 38%, ${hex}33 0%, ${hex}14 45%, rgba(0,0,0,0) 72%)`;
}
function rarityRing(rarityKey){ return RARITY[rarityKey].hex; }

// ---- денежные значения --------------------------------------------------
function Price({ value, currency='ton', size=15, bold=true }){
  const G = currency === 'star' ? StarGlyph : TonGlyph;
  return (
    <span className="cur" style={{fontSize:size, fontWeight:bold?700:600}}>
      <G size={size+3}/>{typeof value==='number' ? value.toLocaleString('ru-RU') : value}
    </span>
  );
}

// ---- Telegram header (мок-чрома мини-аппа) ------------------------------
/* DEV #3: баланс TON/Stars — из API, обновлять после операций. */
function TGHeader({ user, onWallet, onBalance, dev, devPin }){
  return (
    <div className="tg-head">
      {/* кошелёк + баланс TON (один чип, без обводки) */}
      <button className="bal-pill" onClick={onBalance} style={{paddingLeft:9,gap:8,position:'relative'}}>
        <IconWallet size={18}/>
        {dev && devPin(3, { left:-7, top:-9 })}
        <span style={{display:'inline-flex',alignItems:'center',gap:5}}>
          <TonGlyph size={18}/><span className="v">{user.balanceTon}</span>
        </span>
      </button>
      {/* баланс Stars (отдельный чип, без обводки) */}
      <button className="bal-pill" onClick={onBalance}>
        <StarGlyph size={17}/><span className="v">{user.balanceStar}</span>
      </button>
      <div style={{flex:1}}/>
      <button className="tg-pill icon" onClick={onBalance} aria-label="Пополнить">
        <IconPlus size={18}/>
      </button>
      <button className="tg-pill icon" aria-label="Ещё"><IconDots size={18}/></button>
    </div>
  );
}

// ---- нижнее меню --------------------------------------------------------
/* DEV: профиль (правый аватар) — из Telegram initData. */
function BottomNav({ tab, setTab, user, badges={} }){
  const items = [
    { key:'cases',     label:'Кейсы',     Icon:IconCases },
    { key:'inventory', label:'Инвентарь', Icon:IconInventory },
    { key:'upgrade',   label:'Апгрейдер', Icon:IconUpgrade },
    { key:'tasks',     label:'Задания',   Icon:IconTasks },
  ];
  return (
    <div className="nav-wrap">
      <div className="nav-pill">
        {items.map(({key,label,Icon}) => (
          <button key={key} className={'nav-item'+(tab===key?' active':'')}
            onClick={()=>setTab(key)}>
            <Icon/>
            {badges[key] ? <span className="nav-badge">{badges[key]}</span> : null}
            <span>{label}</span>
          </button>
        ))}
      </div>
      <button className={'nav-avatar'+(tab==='profile'?' active':'')}
        onClick={()=>setTab('profile')} aria-label="Профиль">
        <img src={user.avatar} alt="" referrerPolicy="no-referrer"/>
      </button>
    </div>
  );
}

// ---- редкость-метка -----------------------------------------------------
function RarityTag({ rarity, faded }){
  const r = RARITY[rarity];
  return (
    <span className="rarity-tag" style={{
      color:r.hex, background:`${r.hex}1f`,
      opacity:faded?.7:1,
    }}>{r.label}</span>
  );
}

// ---- крупная плитка-подарок (для инвентаря/рулетки) ---------------------
function GiftTile({ gift, size=86, selected, dimmed, onClick, showPrice=true, badge }){
  const r = rarityRing(gift.rarity);
  return (
    <button onClick={onClick} style={{
      position:'relative', border:'none', cursor:onClick?'pointer':'default',
      background:'var(--surface)', borderRadius:18, padding:'10px 8px 9px',
      display:'flex', flexDirection:'column', alignItems:'center', gap:5,
      outline: selected ? `2.5px solid ${r}` : '1px solid var(--hairline)',
      boxShadow: selected ? `0 0 22px ${r}55` : 'none',
      opacity: dimmed?.4:1, transition:'all .15s var(--ease)', width:'100%',
      fontFamily:'var(--font)',
    }}>
      <div style={{position:'absolute',top:0,left:0,right:0,height:size*0.7,borderRadius:'18px 18px 0 0',
        background:rarityGlow(gift.rarity),pointerEvents:'none'}}/>
      {badge}
      <div style={{height:4,width:26,borderRadius:3,background:r,opacity:.9,marginTop:1}}/>
      <div style={{fontSize:size*0.46,lineHeight:1,filter:'drop-shadow(0 6px 10px rgba(0,0,0,.5))',
        margin:'4px 0 2px'}}>{gift.emoji}</div>
      <div style={{fontSize:12.5,fontWeight:700,color:'var(--text)',textAlign:'center',
        whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',maxWidth:'100%'}}>{gift.title}</div>
      {showPrice && <Price value={gift.ton} currency="ton" size={12.5}/>}
    </button>
  );
}

// ---- bottom sheet -------------------------------------------------------
function Sheet({ open, onClose, children }){
  if(!open) return null;
  return (
    <div className="sheet-backdrop" onClick={onClose}>
      <div className="sheet" onClick={e=>e.stopPropagation()}>
        <div className="sheet-grip"/>
        {children}
      </div>
    </div>
  );
}
function CenterModal({ open, onClose, children, dismissable=true }){
  if(!open) return null;
  return (
    <div className="center-modal" onClick={dismissable?onClose:undefined}>
      <div onClick={e=>e.stopPropagation()} style={{width:'100%',maxWidth:330}}>{children}</div>
    </div>
  );
}

// ---- dev pin ------------------------------------------------------------
function makeDevPin(onOpen){
  return function devPin(n, style){
    return <span className="dev-pin" style={style} onClick={(e)=>{e.stopPropagation();onOpen(n);}}>{n}</span>;
  };
}

Object.assign(window, {
  rarityGlow, rarityRing, Price, TGHeader, BottomNav, RarityTag, GiftTile, Sheet, CenterModal, makeDevPin,
});
