/* ============================================================
   Nuad Now — วงล้อรายวัน 🎡 (หมุนได้วันละ 1 ครั้ง)  (JSX)
   สุ่มและให้รางวัลที่ฐานข้อมูล (nn_wheel_spin) — หน้านี้แค่หมุนไปจอดที่ช่องที่ฐานข้อมูลเลือกไว้แล้ว
   ============================================================ */

const WHEEL_SLICES = 10;
const WHEEL_DEG    = 360 / WHEEL_SLICES;
const WHEEL_COLORS = ['#FFE3EC','#FFF3C4','#DDF6E8','#DCEBFF','#FFE8CC','#EADCFF','#FFD6A5','#C9E4FF','#C8F2D2','url(#wheelGold)'];

/* ข้อความผลรางวัล: { big, title, sub } */
function wheelPrizeText(result, items, en){
  if(!result) return null;
  const it = result.item_id && (items||[]).find(i=>i.id===result.item_id);
  const coinsTxt = en ? `+${result.coins} coins` : `+${result.coins} เหรียญ`;
  if(result.converted){
    return { big:'🪙', title: coinsTxt,
      sub: result.kind==='freeze'
        ? (en?'You already hold 2 Streak Freezes — converted to coins':'ถือบัตรกันขาดครบ 2 ใบแล้ว — แปลงเป็นเหรียญให้')
        : (en?'You already own that item — converted to coins':'ได้ไอเท็มที่มีอยู่แล้ว — แปลงเป็นเหรียญให้') };
  }
  if(it) return { big: it.emoji||'🎁', title: en?it.name_en:it.name_th,
    sub: it.kind==='freeze' ? (en?'Added to your inventory':'เก็บเข้ากระเป๋าแล้ว') : (en?'Added to your wardrobe — wear it in the Shop':'เก็บเข้าตู้แล้ว — ไปใส่ได้ที่ร้านค้า') };
  return { big:'🪙', title: coinsTxt, sub: en?'Added to your wallet':'เพิ่มเข้ากระเป๋าเหรียญแล้ว' };
}

/* ท่อนของวงล้อ: มุมวัดตามเข็มนาฬิกาจากด้านบน */
function wheelSlicePath(i, R=100){
  const a1=(i*WHEEL_DEG)*Math.PI/180, a2=((i+1)*WHEEL_DEG)*Math.PI/180;
  const p=(a)=>[(R*Math.sin(a)).toFixed(2), (-R*Math.cos(a)).toFixed(2)];
  const [x1,y1]=p(a1), [x2,y2]=p(a2);
  return `M0,0 L${x1},${y1} A${R},${R} 0 0 1 ${x2},${y2} Z`;
}

/* มุมหมุนที่ทำให้ช่อง slot จอดใต้ลูกศรด้านบน (jitter = เบี่ยงในช่องให้ดูเป็นธรรมชาติ) */
function wheelRestAngle(slot, jitter=0){
  return ((360 - (slot*WHEEL_DEG + WHEEL_DEG/2 + jitter)) % 360 + 360) % 360;
}

function WheelModal({prizes=[], items=[], status, onSpin, onClose, onGoShop}){
  const en = window.NN_LANG==='en';
  const reduce = !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
  const spunAtOpen = !!(status && status.spun && status.result);
  const [rot,setRot]         = React.useState(()=> spunAtOpen ? wheelRestAngle(status.result.slot) : 0);
  const [anim,setAnim]       = React.useState(false);
  const [busy,setBusy]       = React.useState(false);
  const [result,setResult]   = React.useState(spunAtOpen ? status.result : null);
  const [fresh,setFresh]     = React.useState(false);    // เพิ่งหมุนในหน้านี้ (ไว้ยิงคอนเฟตตี)
  const [err,setErr]         = React.useState('');
  const [odds,setOdds]       = React.useState(false);
  const total = prizes.reduce((s,p)=>s+p.weight,0) || 1;
  const info  = wheelPrizeText(result, items, en);
  const confetti = React.useMemo(()=> fresh ? <Confetti show/> : null, [fresh]);

  const spin = async () => {
    if(busy || result) return;
    setBusy(true); setErr('');
    const {result:r, error} = await onSpin();
    if(error || !r){
      setErr(/ALREADY_SPUN/.test(error||'')
        ? (en?'You already spun today — come back tomorrow!':'วันนี้หมุนไปแล้ว พรุ่งนี้มาใหม่นะ!')
        : (en?'Something went wrong, please try again':'เกิดข้อผิดพลาด ลองใหม่อีกครั้ง'));
      setBusy(false);
      return;
    }
    const jitter  = (Math.random()*18) - 9;
    const desired = wheelRestAngle(r.slot, jitter);
    const delta   = ((desired - (rot % 360)) % 360 + 360) % 360;
    setAnim(!reduce);
    setRot(rot + (reduce ? 0 : 360*5) + delta);
    const done = () => { setResult(r); setFresh(true); setBusy(false); };
    if(reduce) done(); else setTimeout(done, 4700);
  };

  const jackpot = result && result.kind==='item_epic' && !result.converted;

  return ReactDOM.createPortal(
    <div className="overlay" onClick={()=>!busy&&onClose()}>
      {confetti}
      <div className="modal wheel-modal" onClick={e=>e.stopPropagation()} role="dialog" aria-label={en?'Daily wheel':'วงล้อรายวัน'}>
        <button onClick={()=>!busy&&onClose()} aria-label="close"
          style={{position:'absolute',top:12,right:12,border:'none',background:'rgba(255,255,255,.7)',borderRadius:'50%',width:30,height:30,cursor:'pointer',fontSize:'1rem'}}>✕</button>
        <div className="wheel-title">🎡 {en?'Daily Wheel':'วงล้อรายวัน'}</div>
        <div className="wheel-sub">
          {result ? (spunAtOpen && !fresh ? (en?'You already spun today':'วันนี้คุณหมุนไปแล้ว') : (en?'Your prize!':'รางวัลของคุณ!'))
                  : (en?'Spin once a day — free!':'หมุนฟรีวันละครั้ง!')}
        </div>

        <div className="wheel-box">
          <svg viewBox="-112 -120 224 232" className="wheel-svg" aria-hidden="true">
            <defs>
              <linearGradient id="wheelGold" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0" stopColor="#FFE066"/><stop offset=".5" stopColor="#FFB347"/><stop offset="1" stopColor="#FFE066"/>
              </linearGradient>
            </defs>
            <circle r="106" fill="#4A2B22"/>
            <g style={{transform:`rotate(${rot}deg)`, transition: anim ? 'transform 4.6s cubic-bezier(.12,.72,.08,1)' : 'none'}}>
              {Array.from({length:WHEEL_SLICES}).map((_,i)=>{
                const p = prizes.find(x=>x.slot===i);
                const c = i*WHEEL_DEG + WHEEL_DEG/2;
                return (
                  <g key={i}>
                    <path d={wheelSlicePath(i)} fill={WHEEL_COLORS[i]} stroke="#fff" strokeWidth="1.6"/>
                    {p && <g transform={`rotate(${c})`}>
                      {p.kind==='coins' && <text y="-58" textAnchor="middle" fontSize="13" fontWeight="800" fill="#4A2B22" fontFamily="sans-serif">+{p.coins}</text>}
                      <text y={p.kind==='coins' ? -78 : -66} textAnchor="middle" fontSize={p.kind==='coins'?14:20}>{p.emoji}</text>
                    </g>}
                  </g>
                );
              })}
            </g>
            <circle r="15" fill="#fff" stroke="#4A2B22" strokeWidth="3"/>
            <circle r="5" fill="#E74C3C"/>
            <polygon points="-10,-114 10,-114 0,-92" fill="#E74C3C" stroke="#fff" strokeWidth="2.5" strokeLinejoin="round"/>
          </svg>
        </div>

        {err && <div style={{color:'var(--bad)',fontSize:'.85rem',marginBottom:8}}>{err}</div>}

        {result && info && (
          <div className={`wheel-result ${jackpot?'jackpot':''}`}>
            {jackpot && <div className="wheel-jackpot">💎 {en?'JACKPOT!':'แจ็คพอต!'} 💎</div>}
            <div style={{fontSize:'2.2rem',lineHeight:1}}>{info.big}</div>
            <div style={{fontFamily:'var(--font-display)',fontWeight:800,fontSize:'1.25rem',marginTop:4}}>{info.title}</div>
            <div className="muted" style={{fontSize:'.82rem',marginTop:2}}>{info.sub}</div>
          </div>
        )}

        <div style={{display:'flex',flexDirection:'column',gap:8,marginTop:12}}>
          {!result
            ? <button className="btn lg block" disabled={busy} onClick={spin}>{busy ? (en?'Spinning…':'กำลังหมุน…') : (en?'SPIN! 🎡':'หมุนเลย! 🎡')}</button>
            : <>
                <button className="btn lg block" onClick={onClose}>{fresh ? (en?'Collect':'รับรางวัล') : (en?'Close':'ปิด')}</button>
                {result.item_id && !result.converted && onGoShop &&
                  <button className="btn ghost sm" onClick={onGoShop}>{en?'Go to the Shop':'ไปที่ร้านค้า'}</button>}
                {!fresh && <div className="muted" style={{fontSize:'.8rem'}}>{en?'Come back tomorrow for another spin!':'พรุ่งนี้มาหมุนใหม่ได้อีกนะ!'}</div>}
              </>}
          <button className="btn ghost sm" onClick={()=>setOdds(o=>!o)} style={{fontSize:'.78rem'}}>
            {odds ? (en?'Hide odds':'ซ่อนโอกาสได้รางวัล') : (en?'View prize odds':'ดูโอกาสได้รางวัล')}
          </button>
          {odds && (
            <div className="wheel-odds">
              {prizes.map(p=>(
                <div key={p.id} className="row" style={{gap:8,padding:'3px 0',fontSize:'.8rem'}}>
                  <span style={{width:22,textAlign:'center'}}>{p.emoji}</span>
                  <span style={{flex:1,textAlign:'left'}}>{en?p.label_en:p.label_th}</span>
                  <b style={{fontFamily:'var(--font-display)'}}>{(p.weight/total*100).toFixed(1)}%</b>
                </div>
              ))}
              <div className="muted" style={{fontSize:'.7rem',marginTop:4}}>
                {en?'Duplicate items and a full Streak Freeze slot are converted into coins.':'ถ้าได้ไอเท็มที่มีอยู่แล้ว หรือบัตรกันขาดเต็ม จะแปลงเป็นเหรียญให้'}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>,
    document.body
  );
}

/* การ์ดบนหน้าแรก: ยังไม่หมุน = เด่นชวนหมุน · หมุนแล้ว = แถบเล็กบอกผล */
function WheelCard({ready, spun, result, items, onOpen}){
  if(!ready) return null;
  const en = window.NN_LANG==='en';
  if(spun){
    const info = wheelPrizeText(result, items, en);
    return (
      <div className="card flat" style={{display:'flex',alignItems:'center',gap:10,padding:'10px 14px',marginBottom:18}}>
        <span style={{fontSize:'1.4rem'}}>🎡</span>
        <div style={{flex:1,minWidth:0,fontSize:'.88rem'}}>
          <b style={{fontFamily:'var(--font-display)'}}>{en?'Spun today':'หมุนวงล้อวันนี้แล้ว'}</b>
          {info && <span className="muted"> · {info.big} {info.title}</span>}
          <div className="muted" style={{fontSize:'.74rem'}}>{en?'Come back tomorrow for another spin':'พรุ่งนี้มาหมุนใหม่ได้อีก'}</div>
        </div>
      </div>
    );
  }
  return (
    <button className="card pad wheel-card fade-in" onClick={onOpen} style={{width:'100%',textAlign:'left',cursor:'pointer',marginBottom:18}}>
      <div className="row" style={{gap:14,alignItems:'center'}}>
        <span className="wheel-card-ic">🎡</span>
        <div style={{flex:1,minWidth:0}}>
          <div style={{fontFamily:'var(--font-display)',fontWeight:800,fontSize:'1.15rem'}}>{en?'Daily Wheel — spin for free!':'วงล้อรายวัน — หมุนฟรีวันนี้!'}</div>
          <div className="muted" style={{fontSize:'.85rem'}}>{en?'Win coins, avatar items or a Streak Freeze. One spin a day.':'ลุ้นเหรียญ ไอเท็มแต่ง avatar หรือบัตรกันขาด วันละ 1 ครั้ง'}</div>
        </div>
        <span className="btn gold sm" style={{flexShrink:0}}>{en?'Spin':'หมุนเลย'}</span>
      </div>
    </button>
  );
}

Object.assign(window, { WheelModal, WheelCard, wheelPrizeText });
