(()=>{'use strict';

/*
 * ZooLuck ReBet + Home control fix
 * UI/control layer only. No RNG, wheel, sound, bot, settlement or backend changes.
 */

const rebetBtn=document.getElementById('rebet');
const phaseEl=document.getElementById('phase');

function notify(msg){
  if(typeof window.toast==='function') window.toast(msg);
  else console.log('[ZooLuck]',msg);
}

function storageKey(){
  const token=String(localStorage.getItem('zoo_token')||'guest');
  return 'zooluck_rebet_'+token.slice(-24);
}

function readSaved(){
  try{
    const rows=JSON.parse(localStorage.getItem(storageKey())||'[]');
    return Array.isArray(rows)
      ? rows.filter(x=>x && x.area && Number(x.amount)>0)
      : [];
  }catch(e){
    return [];
  }
}

function saveCurrentPlayerBets(){
  const marks=[
    ...document.querySelectorAll(
      '#betMarks [data-bet-area], #betMarks .bet-mark, #betMarks .player-locked-amount'
    )
  ];

  const byArea=new Map();

  marks.forEach(mark=>{
    const area=String(mark.dataset.betArea||'').trim();
    if(!area)return;

    const amount=Number(
      mark.dataset.betTotal
      || String(mark.textContent||'').replace(/[^0-9.]/g,'')
      || 0
    );

    if(amount>0){
      byArea.set(area,Math.max(Number(byArea.get(area)||0),amount));
    }
  });

  const rows=[...byArea.entries()].map(([area,amount])=>({area,amount}));
  // Preserve the last real wager if a round had no player bets.
  if(rows.length){
    localStorage.setItem(storageKey(),JSON.stringify(rows));
  }
  return rows;
}

let lastPhase=String(phaseEl?.textContent||'').trim().toUpperCase();

function phaseChanged(){
  const now=String(phaseEl?.textContent||'').trim().toUpperCase();

  // Capture the player's own round totals BEFORE the next round clears #betMarks.
  if(lastPhase==='BETTING' && now!=='BETTING'){
    saveCurrentPlayerBets();
  }

  lastPhase=now;
}

if(phaseEl){
  new MutationObserver(phaseChanged).observe(
    phaseEl,
    {childList:true,subtree:true,characterData:true}
  );
}

/*
 * Replace the old ReBet handler. The original zoo.js clears lastRoundBets when a
 * fresh round loads, which is why its ReBet had no previous wager to replay.
 * We replay the saved per-candidate totals through the EXISTING place() function,
 * so all normal server validation, wallet debit, UI markers and chip sounds stay intact.
 */
if(rebetBtn){
  rebetBtn.onclick=async()=>{
    const p=String(phaseEl?.textContent||'').trim().toUpperCase();
    if(p!=='BETTING')return;

    const rows=readSaved();
    if(!rows.length){
      notify('No previous bets');
      return;
    }

    if(typeof window.place!=='function'){
      notify('ReBet is not ready');
      return;
    }

    rebetBtn.disabled=true;
    try{
      for(const row of rows){
        // Server accepts 10 or any higher multiple of 10, so one request per
        // candidate accurately repeats that candidate's previous total.
        await window.place(row.area,Number(row.amount));
      }
    }finally{
      // setPhase() remains the authority over normal button locking.
      if(String(phaseEl?.textContent||'').trim().toUpperCase()==='BETTING'){
        rebetBtn.disabled=false;
        rebetBtn.classList.remove('bet-locked');
      }
    }
  };
}

/* Both visible Home controls return to the existing ZooLuck lobby. */
function goLobby(){
  window.location.href='/lobby/';
}

const homeButtons=[
  document.querySelector('.home-round'),
  document.querySelector('.topbar nav button:first-child')
].filter(Boolean);

homeButtons.forEach(btn=>{
  btn.type='button';
  btn.onclick=goLobby;
  btn.style.cursor='pointer';
});

})();