/* ============================================================
   9 · ALCHEMY SEQUENCE — order-matters brewing (takeover).
   Each player holds reagent(s) + a clue FRAGMENT; the party must
   talk to reconstruct the order before adding. Wrong add backfires.
   ============================================================ */
const { useState: useS_al, useEffect: useE_al } = React;

function AlchemyMainView({ alchemy }){
  const game = useGame();
  const al = alchemy;
  const done = al.status==='done';
  useGameEvents((ev)=>{
    if(ev.type==='brew-add'){ try{ audio.play('beat'); }catch(_){} }
    else if(ev.type==='brew-backfire'){ try{ audio.play('miss'); }catch(_){} }
    else if(ev.type==='brew-complete'){ try{ audio.play('gateOpen'); }catch(_){} }
  });
  const step = al.added.length;
  const total = al.recipe.length;

  return (
    <div className={`alch-stage ${done?'is-done':''}`}>
      <Embers count={16}/>
      <div key={'bf'+al.backfireId} className={al.backfireId?'alch-backfire-flash':''}></div>
      <div className="alch-titlebar">
        <div className="alch-title display">The Cauldron</div>
        <div className="alch-sub">{done ? 'The brew is perfected' : 'Reconstruct the recipe aloud — the order is split across your phones'}</div>
      </div>

      <div className="alch-main">
        <div className={`alch-cauldron step-${Math.min(step,5)} ${al.backfireId?'backfire':''} ${done?'done':''}`}>
          <div className="alch-cauldron-brew" style={{ '--brew': al.added.length? reagentById(al.added[al.added.length-1]).color : '#52708a' }}></div>
          <div className="alch-bubbles">
            {Array.from({length:6}).map((_,i)=><span key={i} className="alch-bubble" style={{ '--d':(i*0.4)+'s', '--x':(12+i*13)+'%' }}></span>)}
          </div>
          <div className="alch-cauldron-rim"></div>
        </div>

        <div className="alch-track">
          <div className="alch-track-label">Recipe · {step}/{total}</div>
          <div className="alch-slots">
            {al.recipe.map((rid,i)=>{
              const filled = i<step;
              const r = reagentById(al.added[i]||rid);
              return (
                <div key={i} className={`alch-slot ${filled?'filled':''}`}>
                  {filled ? <span className="alch-slot-glyph" style={{ color:r.color }}>{r.glyph}</span> : <span className="alch-slot-num">{i+1}</span>}
                </div>
              );
            })}
          </div>
          <div className="alch-pool">
            {al.pool.map(r=>{
              const used = al.added.includes(r.id);
              return (
                <div key={r.id} className={`alch-reagent ${used?'used':''}`} style={{ '--rc':r.color }}>
                  <span className="alch-reagent-glyph">{r.glyph}</span>
                  <span className="alch-reagent-name">{r.name}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div className="alch-foot">
        {done ? <div className="alch-done display">{al.resultItem.toUpperCase()}</div>
          : <span className="muted">Each hero sees only a fragment of the recipe — talk before you pour</span>}
      </div>
    </div>
  );
}
window.AlchemyMainView = AlchemyMainView;

function AlchemyPlayerOverlay({ player }){
  const game = useGame();
  const al = game.alchemy;
  useGameEvents((ev)=>{ if(ev.type==='brew-backfire' && ev.playerId===player.id) haptic(HAPTIC.damage); else if(ev.type==='brew-complete') haptic(HAPTIC.premium); });
  if(!al.open) return null;
  const done = al.status==='done';
  const myReagents = (al.holders[player.id]||[]).map(reagentById).filter(Boolean);
  const myClue = al.clues[player.id];

  const add = (rid)=>{ if(done) return; Game.addReagent(player.id, rid); haptic(HAPTIC.card); };

  return (
    <div className={`alch-overlay ${done?'is-done':''}`}>
      <Embers count={8}/>
      <div className="alch-ov-inner animate-fade-rise">
        {done ? (
          <div className="alch-ov-result">
            <div className="alch-ov-vial"></div>
            <h2 className="display gold">The brew is perfected</h2>
            <p className="muted" style={{textTransform:'none'}}>{al.resultItem} is shared among the party.</p>
          </div>
        ) : (
          <>
            <div className="alch-ov-eyebrow">⚗ Your part of the recipe</div>
            {myClue && (
              <div className="alch-clue">
                <span className="alch-clue-mark">“</span>{myClue}<span className="alch-clue-mark">”</span>
              </div>
            )}
            <p className="alch-ov-cue">Only you can see this clue. Say it aloud — no one has the whole recipe. Add only when the table agrees it's your reagent's turn.</p>
            <div className="alch-ov-label">Your reagents</div>
            {myReagents.length===0
              ? <div className="alch-ov-none">You hold no reagents — be the party's memory and call the order.</div>
              : <div className="alch-ov-reagents">
                  {myReagents.map(r=>{
                    const used = al.added.includes(r.id);
                    return (
                      <button key={r.id} className={`alch-add ${used?'used':''}`} style={{ '--rc':r.color }} disabled={used} onClick={()=>add(r.id)}>
                        <span className="alch-add-glyph">{r.glyph}</span>
                        <span className="alch-add-name">{r.name}</span>
                        <span className="alch-add-cta">{used?'added ✓':'Add to cauldron'}</span>
                      </button>
                    );
                  })}
                </div>}
            <div className="alch-progress">Added so far: {al.added.length}/{al.recipe.length}</div>
          </>
        )}
      </div>
    </div>
  );
}
window.AlchemyPlayerOverlay = AlchemyPlayerOverlay;
