/* ============================================================
   CHARACTER CREATION — players forge their own hero at the start
   20 points · max 5 per attribute · +1 Health costs 2 points
   ============================================================ */
const STAT_META = {
  STR:'Strength', ATH:'Athletics', MAG:'Magic', STH:'Stealth', SUR:'Survival',
  HIS:'History', INV:'Investigation', NAT:'Nature', MED:'Medicine', PRS:'Persuasion', PRT:'Protection',
};
window.STAT_META = STAT_META;
const CREATE_POOL = 20;

function AllocRow({ label, sub, value, suffix, onMinus, onPlus, minusDisabled, plusDisabled, big }){
  return (
    <div className={`alloc-row ${big?'hp':''}`}>
      <div className="alloc-label">
        <span className="al-k">{label}</span>
        {sub && <span className="al-sub">{sub}</span>}
      </div>
      <div className="alloc-ctrl">
        <button className="alloc-step" onClick={onMinus} disabled={minusDisabled}>−</button>
        <span className="alloc-val">{value}{suffix||''}</span>
        <button className="alloc-step plus" onClick={onPlus} disabled={plusDisabled}>+</button>
      </div>
    </div>
  );
}

/* ---------- the party gathered: a candlelit round table of claimed heroes ---------- */
function RoundTable(){
  const game = useGame();
  const players = game.players || [];
  const seats = Math.max(6, players.length + (players.length%2));   // even ring, min 6
  return (
    <div className={`round-table seats-${seats}`}>
      <div className="rt-tabletop">
        <div className="rt-grain"></div>
        <div className="rt-candle rt-candle-c"><span className="rt-flame"></span></div>
        <div className="rt-sigil display">⚔</div>
      </div>
      <div className="rt-ring">
        {Array.from({length:seats}).map((_,i)=>{
          const p = players[i];
          const ang = (i/seats)*360;
          return (
            <div key={i} className="rt-seat" style={{'--ang': ang+'deg'}}>
              <div className={`rt-chair ${p?'taken':'empty'}`}>
                {p ? (
                  <>
                    <div className="rt-portrait"><Icon name={CLASS_ICON[p.cls]||'shield'} size={20}/></div>
                    <div className="rt-name">{p.name.split(' ')[0]}</div>
                    <span className="rt-candle rt-candle-seat"><span className="rt-flame sm"></span></span>
                  </>
                ) : <div className="rt-empty-dot"></div>}
              </div>
            </div>
          );
        })}
      </div>
      <div className="rt-caption">{players.length? `${players.length} ${players.length>1?'heroes have':'hero has'} taken a seat` : 'The table is set — be the first to sit'}</div>
    </div>
  );
}

function CharacterCreate({ onCreate }){
  const [name,setName] = useState('');
  const [cls,setCls] = useState('');
  const [mastery,setMastery] = useState('');
  const [weakness,setWeakness] = useState('');
  const [backstory,setBackstory] = useState('');
  const [stats,setStats] = useState(()=>{ const o={}; STAT_KEYS.forEach(k=>o[k]=0); return o; });
  const [hpExtra,setHpExtra] = useState(0);

  const statSpent = Object.values(stats).reduce((a,b)=>a+b,0);
  const spent = statSpent + hpExtra*2;
  const remaining = CREATE_POOL - spent;
  const maxHp = 10 + hpExtra;

  const bumpStat = (k,d)=>{
    setStats(s=>{
      const v = Math.max(0, Math.min(5, s[k]+d));
      if(v===s[k]) return s;
      if(d>0 && remaining < 1) return s;
      audio.play(d>0?'card':'beat');
      return {...s,[k]:v};
    });
  };
  const bumpHp = (d)=>{
    if(d>0 && remaining < 2) return;
    if(d<0 && hpExtra<=0) return;
    audio.play(d>0?'heal':'beat');
    setHpExtra(h=>Math.max(0,h+d));
  };

  const canBegin = name.trim().length>0;
  const begin = ()=>{
    if(!canBegin) return;
    audio.play('revive');
    onCreate({ name:name.trim(), cls:cls.trim(), mastery:mastery.trim(),
      weakness:weakness.trim(), backstory:backstory.trim(), stats, maxHp });
  };

  return (
    <div className="create-screen vignette">
      <Embers count={16}/>
      <div className="create-inner">
        <div className="create-head animate-fade-rise">
          <div className="enter-flame" style={{marginBottom:'.9rem'}}></div>
          <h1 className="display">Forge your hero</h1>
          <p>Name them, shape them, and spend your gifts. The realm is waiting.</p>
        </div>

        <div className="animate-fade-rise" style={{animationDelay:'30ms'}}>
          <RoundTable/>
        </div>

        {/* identity */}
        <div className="create-card liquid-glass animate-fade-rise" style={{animationDelay:'60ms'}}>
          <div className="cc-section">Identity</div>
          <div className="cc-grid">
            <label className="cc-field full">
              <span>Name</span>
              <input className="tinput" value={name} maxLength={28} onChange={e=>setName(e.target.value)} placeholder="What are you called?"/>
            </label>
            <label className="cc-field">
              <span>Class</span>
              <input className="tinput" value={cls} maxLength={22} onChange={e=>setCls(e.target.value)} placeholder="Knight, Witch, Tinker…"/>
            </label>
            <label className="cc-field">
              <span>Mastery</span>
              <input className="tinput" value={mastery} maxLength={40} onChange={e=>setMastery(e.target.value)} placeholder="What you do best"/>
            </label>
            <label className="cc-field">
              <span>Weakness</span>
              <input className="tinput" value={weakness} maxLength={40} onChange={e=>setWeakness(e.target.value)} placeholder="What undoes you"/>
            </label>
            <label className="cc-field full">
              <span>Backstory</span>
              <textarea className="tinput" rows="3" value={backstory} maxLength={400} onChange={e=>setBackstory(e.target.value)} placeholder="Where do you come from? Why are you here?"></textarea>
            </label>
          </div>
        </div>

        {/* allocation */}
        <div className="create-card liquid-glass animate-fade-rise" style={{animationDelay:'120ms'}}>
          <div className="cc-section" style={{display:'flex',justifyContent:'space-between',alignItems:'baseline'}}>
            <span>Gifts</span>
            <span className={`cc-pool ${remaining===0?'done':''}`}>{remaining} <em>points left</em></span>
          </div>
          <div className="cc-pool-bar"><div className="cc-pool-fill" style={{width:(spent/CREATE_POOL*100)+'%'}}></div></div>

          <AllocRow big label="Health" sub="+1 costs 2 points · base 10"
            value={maxHp} onMinus={()=>bumpHp(-1)} onPlus={()=>bumpHp(1)}
            minusDisabled={hpExtra<=0} plusDisabled={remaining<2}/>

          <div className="cc-section sub">Attributes <span className="al-sub">max 5 each</span></div>
          <div className="alloc-grid">
            {STAT_KEYS.map(k=>(
              <AllocRow key={k} label={k} sub={STAT_META[k]}
                value={stats[k]>0?'+'+stats[k]:stats[k]}
                onMinus={()=>bumpStat(k,-1)} onPlus={()=>bumpStat(k,1)}
                minusDisabled={stats[k]<=0} plusDisabled={stats[k]>=5 || remaining<1}/>
            ))}
          </div>
        </div>

        <button className={`create-begin ${canBegin?'':'disabled'}`} onClick={begin} disabled={!canBegin}>
          {canBegin ? 'Step into the realm →' : 'Name your hero to begin'}
        </button>
        <div className="create-note">You can spend fewer points if you like — gifts are yours to keep.</div>
      </div>

      <button className="lock-corner glass-btn" title="Leave room" onClick={()=>{ try{ if(window.Room) Room.leave(); }catch(_){}; try{ if(window.clearRoom) clearRoom(); }catch(_){}; location.reload(); }}>
        <Icon name="key" size={16}/>
      </button>
    </div>
  );
}

window.CharacterCreate = CharacterCreate;
