/* ============================================================
   3 · RITUAL INTERRUPT  +  4 · PHASE TOTEMS  (boss-phase takeovers)
   Two racing-bar / synchrony events that own the Main screen.
   ============================================================ */
const { useState: useS_rt, useEffect: useE_rt, useRef: useR_rt } = React;

/* ---------------- RITUAL INTERRUPT ---------------- */
function RitualMainView({ ritual }){
  const game = useGame();
  const r = ritual;
  const [castPct, setCastPct] = useS_rt(0);
  useGameEvents((ev)=>{
    if(ev.type==='ritual-contrib'){ try{ audio.play('beat'); }catch(_){} }
    else if(ev.type==='ritual-interrupt'){ try{ audio.play('gateOpen'); }catch(_){} }
    else if(ev.type==='ritual-cast'){ try{ audio.play('boom'); }catch(_){} }
  });
  useE_rt(()=>{
    if(r.status!=='live'){ return; }
    const tick=()=>{
      const p = Math.min(100, ((Date.now()-r.startAt)/r.castMs)*100);
      setCastPct(p);
      if(p>=100) Game.onRitualComplete();
    };
    tick(); const id=setInterval(tick, 100); return ()=>clearInterval(id);
  }, [r.status, r.startAt, r.castMs]);
  const intPct = Math.min(100, (r.interrupt/r.threshold)*100);
  const urgent = castPct>70 && r.status==='live';
  const ended = r.status!=='live';

  return (
    <div className={`ritual-stage ${urgent?'urgent':''} ${r.status}`}>
      <Embers count={18}/>
      <div className="ritual-boss">
        <div className="ritual-boss-glyph">☄</div>
        <div className="ritual-boss-aura"></div>
      </div>
      <div className="ritual-titlebar">
        <div className="ritual-eyebrow">{ended? (r.status==='interrupted'?'Interrupted':'Unleashed') : 'The boss is casting'}</div>
        <div className="ritual-spell display">{r.spell}</div>
      </div>

      <div className="ritual-bars">
        <div className="ritual-bar-row">
          <span className="ritual-bar-lbl cast">Cast</span>
          <div className="cast-bar"><div className="fill" style={{ width:castPct+'%' }}></div></div>
          <span className="ritual-bar-pct">{Math.round(castPct)}%</span>
        </div>
        <div className="ritual-vs">vs</div>
        <div className="ritual-bar-row">
          <span className="ritual-bar-lbl int">Interrupt</span>
          <div className="interrupt-bar"><div className="fill" style={{ width:intPct+'%' }}></div></div>
          <span className="ritual-bar-pct">{Math.round(intPct)}%</span>
        </div>
      </div>

      <div className="ritual-foot">
        {ended
          ? <div className={`ritual-end display ${r.status}`}>{r.status==='interrupted'?'RITUAL SHATTERED':'CATASTROPHE'}</div>
          : <span className="muted">Everyone act on your phone — fill the gold bar before the red one lands</span>}
      </div>
    </div>
  );
}
window.RitualMainView = RitualMainView;

function RitualPlayerOverlay({ player }){
  const game = useGame();
  const r = game.ritual;
  const [seq, setSeq] = useS_rt([]);
  const holdRef = useR_rt(null);
  useGameEvents((ev)=>{ if(ev.type==='ritual-interrupt') haptic(HAPTIC.premium); else if(ev.type==='ritual-cast') haptic(HAPTIC.death); });
  if(!r.active) return null;
  const task = r.tasks[player.id] || { kind:'tap' };
  const ended = r.status!=='live';

  const tap = ()=>{ if(ended) return; Game.contributeInterrupt(player.id, 3); haptic([8]); };
  const seqKeys = ['◆','▲','●','■'];
  const target = [0,2,1,3];
  const pressSeq = (i)=>{
    if(ended) return;
    const ns = [...seq, i];
    if(i===target[ns.length-1]){ if(ns.length===target.length){ Game.contributeInterrupt(player.id, 10); setSeq([]); haptic([8]); } else setSeq(ns); }
    else setSeq([]);
  };
  const holdStart = ()=>{ if(ended) return; holdRef.current = setInterval(()=>Game.contributeInterrupt(player.id, 2), 160); haptic([10]); };
  const holdEnd = ()=>{ if(holdRef.current){ clearInterval(holdRef.current); holdRef.current=null; } };

  return (
    <div className={`ritual-overlay ${r.status}`}>
      <div className="ritual-ov-inner animate-fade-rise">
        {ended ? (
          <div className="ritual-ov-end">
            <h2 className="display">{r.status==='interrupted'?'Shattered!':'It landed'}</h2>
            <p className="muted" style={{textTransform:'none'}}>{r.status==='interrupted'?'You broke the cast in time.':'The ritual completed — brace yourselves.'}</p>
          </div>
        ) : (
          <>
            <div className="ritual-ov-eyebrow">☄ Interrupt the cast</div>
            <h2 className="display">{task.kind==='hold'?'Channel to disrupt':task.kind==='seq'?'Trace the sigil':'Disrupt — mash!'}</h2>
            {task.kind==='tap' && <button className="ritual-tap glass-btn" onClick={tap}>STRIKE</button>}
            {task.kind==='hold' && (
              <button className="ritual-hold glass-btn" onPointerDown={holdStart} onPointerUp={holdEnd} onPointerLeave={holdEnd}>HOLD TO CHANNEL</button>
            )}
            {task.kind==='seq' && (
              <div className="ritual-seq">
                <div className="ritual-seq-target">{target.map((t,i)=>(<span key={i} className={`ritual-seq-ghost ${i<seq.length?'on':''}`}>{seqKeys[t]}</span>))}</div>
                <div className="ritual-seq-keys">{seqKeys.map((k,i)=>(<button key={i} className="ritual-seq-key" onClick={()=>pressSeq(i)}>{k}</button>))}</div>
              </div>
            )}
            <div className="ritual-ov-cue">Fill the party's gold bar on the main screen before the cast completes.</div>
          </>
        )}
      </div>
    </div>
  );
}
window.RitualPlayerOverlay = RitualPlayerOverlay;

/* ---------------- PHASE TOTEMS ---------------- */
function TotemsMainView({ totems }){
  const game = useGame();
  const t = totems;
  useGameEvents((ev)=>{
    if(ev.type==='totem-break'){ try{ audio.play('beat'); }catch(_){} }
    else if(ev.type==='totems-shield-down'){ try{ audio.play('gateOpen'); }catch(_){} }
    else if(ev.type==='totems-regen'){ try{ audio.play('miss'); }catch(_){} }
  });
  // drive the synchrony resolution clock
  useE_rt(()=>{
    if(!t.active || t.shieldDown) return;
    const id=setInterval(()=>{ if(store.getState().totems.items.some(x=>x.broken)) Game.checkSynchrony(); }, 250);
    return ()=>clearInterval(id);
  }, [t.active, t.shieldDown]);
  const brokenN = t.items.filter(x=>x.broken).length;

  return (
    <div className={`totems-stage ${t.shieldDown?'shield-down':''}`}>
      <Embers count={18}/>
      <div className="totems-titlebar">
        <div className="totems-eyebrow">{t.shieldDown?'The shield is down':'Break all four together'}</div>
        <div className="totems-title display">Phase Totems</div>
      </div>

      <div className="totems-arena">
        <div className={`boss ${t.shieldDown?'':'shielded'}`}>
          <div className="boss-core">☠</div>
          {!t.shieldDown && <div className="boss-shield"></div>}
          {t.shieldDown && <div className="shield shatter"></div>}
          <div className="boss-label">{t.shieldDown?'VULNERABLE':'INVULNERABLE'}</div>
        </div>
        <div className="totems-ring">
          {t.items.map((it,i)=>{
            const owner = game.players.find(p=>p.id===it.owner);
            const pct = (it.hp/it.maxHp)*100;
            const colors=['#f0a836','#5a8fd6','#52b07a','#d9534f'];
            return (
              <div key={it.id} className={`totem ${it.primed?'primed':''} ${it.broken?'broken':''}`} style={{ '--tc':colors[i%4], '--i':i }}>
                <div className="totem-body">{it.broken?'✶':'▲'}</div>
                <div className="totem-hp"><div className="totem-hp-fill" style={{ width:pct+'%' }}></div></div>
                <div className="totem-owner">{owner?owner.name.split(' ')[0]:'—'}</div>
                {it.primed && !it.broken && <div className="totem-primed-tag">PRIMED</div>}
              </div>
            );
          })}
        </div>
      </div>

      <div className="totems-foot">
        {t.shieldDown
          ? <div className="totems-done display">FOCUS FIRE</div>
          : <span className="muted">{brokenN}/4 down · all must break within {(t.window/1000).toFixed(1)}s or they surge back</span>}
      </div>
    </div>
  );
}
window.TotemsMainView = TotemsMainView;

function TotemsPlayerOverlay({ player }){
  const game = useGame();
  const t = game.totems;
  useGameEvents((ev)=>{ if(ev.type==='totems-shield-down') haptic(HAPTIC.premium); else if(ev.type==='totems-regen') haptic(HAPTIC.damage); });
  if(!t.active) return null;
  const mine = t.items.filter(it=>it.owner===player.id);

  return (
    <div className={`totems-overlay ${t.shieldDown?'down':''}`}>
      <div className="totems-ov-inner animate-fade-rise">
        {t.shieldDown ? (
          <div className="totems-ov-end">
            <h2 className="display gold">Shield down!</h2>
            <p className="muted" style={{textTransform:'none'}}>The totems fell as one. Pour on the damage.</p>
          </div>
        ) : mine.length===0 ? (
          <div className="totems-ov-idle">
            <h2 className="display">No totem is yours</h2>
            <p className="muted" style={{textTransform:'none'}}>Help the others time their break — call the countdown.</p>
          </div>
        ) : (
          <>
            <div className="totems-ov-eyebrow">▲ Your totem{mine.length>1?'s':''}</div>
            <h2 className="display">Prime, then BREAK together</h2>
            <p className="totems-ov-cue">Wear it down to PRIMED, then hold for the table's count — all four BREAKs must land within {(t.window/1000).toFixed(1)}s.</p>
            <div className="totems-ctrl-stack">
              {mine.map((it,k)=>{
                const colors=['#f0a836','#5a8fd6','#52b07a','#d9534f'];
                const idx = t.items.findIndex(x=>x.id===it.id);
                const pct=(it.hp/it.maxHp)*100;
                return (
                  <div key={it.id} className={`totems-ctrl ${it.primed?'primed':''} ${it.broken?'broken':''}`} style={{ '--tc':colors[idx%4] }}>
                    <div className="totems-ctrl-head">{k>0?'Also: ':''}Totem {idx+1}</div>
                    <div className="totems-ctrl-hp"><div className="totems-ctrl-hp-fill" style={{ width:pct+'%' }}></div></div>
                    {it.broken
                      ? <div className="totems-ctrl-broke">✶ broken — hold for it</div>
                      : it.primed
                        ? <button className="totems-break glass-btn" onClick={()=>{ Game.breakTotem(it.id); haptic([12]); }}>BREAK</button>
                        : <button className="totems-hit glass-btn" onClick={()=>{ Game.damageTotem(it.id,1); haptic([7]); }}>Strike ({it.hp})</button>}
                  </div>
                );
              })}
            </div>
          </>
        )}
      </div>
    </div>
  );
}
window.TotemsPlayerOverlay = TotemsPlayerOverlay;
