(()=>{'use strict'; const $=id=>document.getElementById(id); const tiers=[['DAHU',1],['DAHU 2',5],['ZEBRA',10],['CROCODILE',25],['EAGLE',50],['WOLF',100],['BUFFALO',250],['CHEETAH',500],['RHINO',1000],['JAGUAR',2500],['LION',5000],['ELEPHANT',10000]]; let current=null,provider=null,signer=null,account=null,selectedMethod=0; const creditInfo={balance:null,checked:false}; function paintMethod(method){selectedMethod=method;$('seatBuy').classList.toggle('payment-selected',method===0);$('seatCredit').classList.toggle('payment-selected',method===1);} function showBalances(usdc){const credits=creditInfo.checked?(creditInfo.balance===null?'Unavailable':creditInfo.balance+' Credits'):'Sign in to check';$('seatBalances').textContent='Available Credits: '+credits+' · Wallet USDC: '+(usdc??'Connect wallet to check');} async function loadCredits(token){try{const r=await fetch('/.netlify/functions/flight-seat-balances',{headers:{Authorization:'Bearer '+token},cache:'no-store'});const j=await r.json();creditInfo.balance=r.ok?j.credits:null;}catch(_){creditInfo.balance=null;}creditInfo.checked=true;showBalances();} async function loadUsdc(){if(!account||!provider||!current?.usdc)return;try{const usdc=new ethers.Contract(current.usdc,['function balanceOf(address) view returns(uint256)'],provider);const b=await usdc.balanceOf(account);showBalances(ethers.formatUnits(b,6)+' USDC');}catch(_){showBalances('Unavailable');}} const out=(msg)=>{$('seatStatus').textContent=msg}; function choices(){const select=$('seatTier');const general=(location.pathname.includes('/tickets')||new URLSearchParams(location.search).get('view')==='general');tiers.forEach(([n,p],i)=>{if(general&&i<2)return;if(location.pathname.includes('/dahu')&&i>=2)return;const o=document.createElement('option');o.value=i;o.textContent=`${n} — $${p.toLocaleString()}`;select.append(o)});} async function refresh(){try{const dream=Number($('seatDream').value),cohort=Number($('seatCohort').value);const r=await fetch(`/.netlify/functions/flight-seat-status?dream=${dream}&cohort=${cohort}`,{cache:'no-store'});const j=await r.json();current=j;const grid=$('seatGrid');grid.replaceChildren();for(let i=0;i<12;i++){if((location.pathname.includes('/tickets')||new URLSearchParams(location.search).get('view')==='general')&&i<2)continue;if(location.pathname.includes('/dahu')&&i>=2)continue;const f=j.flights?.[i];const el=document.createElement('div');el.className='seat-card';const filled=f?.filled??0;el.innerHTML=`${tiers[i][0]}$${tiers[i][1].toLocaleString()} · ${filled}/111 seats
${f?(f.open?'OPEN':filled===111?'FULL':'CLOSED'):'NOT LIVE'}`;grid.append(el)}$('seatBuy').disabled=!j.configured||j.paused||!j.flights?.[Number($('seatTier').value)]?.open;$('seatCredit').disabled=$('seatBuy').disabled;$('seatLive').textContent=j.configured?(j.paused?'SEAT RESERVATIONS TEMPORARILY UNAVAILABLE':'LIVE SEAT AVAILABILITY'):'SEAT RESERVATIONS NOT YET AVAILABLE';if(!j.configured)out('Seat purchasing is not active. No payment will be requested until the contract and Circle authorization service are configured.');}catch(e){current=null;$('seatBuy').disabled=true;$('seatCredit').disabled=true;out('Seat availability could not be checked right now. Please try again later.');}} async function connect(){if(!window.ethereum)throw Error('Install or open an EVM wallet browser.');if(!window.ethers)throw Error('Wallet library unavailable.');provider=new ethers.BrowserProvider(window.ethereum);await provider.send('eth_requestAccounts',[]);signer=await provider.getSigner();account=await signer.getAddress();if(current?.chainId){const net=await provider.getNetwork();if(Number(net.chainId)!==current.chainId)throw Error(`Switch wallet to chain ${current.chainId}`);}out('Wallet connected: '+account);await loadUsdc();} async function purchase(method){paintMethod(method);try{if(!current?.configured||current.paused)throw Error('Purchasing is not enabled.');if(method===0&&!signer)await connect();const tier=Number($('seatTier').value),dream=Number($('seatDream').value),cohort=Number($('seatCohort').value);if(!current.flights[tier]?.open||current.flights[tier].available<1)throw Error('No available seats in this Flight.');const {magicClient,magicEmailLogin}=await import('/assets/js/dreamplay-magic-session.js');const cfgResponse=await fetch('/.netlify/functions/circle-config');if(!cfgResponse.ok)throw Error('Circle login is not configured');const cfg=await cfgResponse.json();const magic=await magicClient(cfg.magicPublishableKey);let token=await magic.user.isLoggedIn()?await magic.user.getIdToken():null;if(!token){const email=prompt('Enter your DreamPlay Circle email to receive a Magic login code:');if(!email)throw Error('Circle email required');token=await magicEmailLogin(magic,email);}await loadCredits(token);const ctxResponse=await fetch('/.netlify/functions/flight-seat-context',{headers:{Authorization:'Bearer '+token}});const ctx=await ctxResponse.json();if(!ctxResponse.ok)throw Error(ctx.error||'Circle identity unavailable');if(method===1){ const q=new URLSearchParams({dream,tier,cohort}); const sr=await fetch('/.netlify/functions/flight-seat-credit-status?'+q,{headers:{Authorization:'Bearer '+token},cache:'no-store'}); if(!sr.ok)throw Error('Unable to verify previous Credit purchase. No new transaction submitted.'); const prior=await sr.json(); if(prior.status!=='NONE'){ out(prior.status==='CONFIRMED'?'This Circle already has a confirmed Credit seat'+(prior.txHash?': '+prior.txHash:''): 'Existing Credit purchase '+prior.status+(prior.txHash?' · '+prior.txHash:'')+'. Do not purchase again; await reconciliation.');return; } out('Confirming wallet-free Credit purchase for Circle #'+ctx.circleNumber+'...');const cr=await fetch('/.netlify/functions/flight-seat-credit-purchase',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+token},body:JSON.stringify({dream,tier,cohort})});const result=await cr.json();if(!cr.ok)throw Error(result.error||'Credit purchase unavailable');if(result.confirmed){window.dispatchEvent(new CustomEvent('flight-confirmed',{detail:{dream,tier,cohort,circle:ctx.circleNumber,txHash:result.txHash,method:1}}));out('Credit seat confirmed on-chain: '+result.txHash);await refresh();return;}out('Credit purchase '+(result.status||'PENDING')+(result.txHash?' · Transaction: '+result.txHash:'')+'. Do not submit another payment; check status before retrying.');return;}const identity=ctx.circleNumber;const binding=`DreamPlay Power Flight seat authorization\nCircle: ${Number(identity)}\nWallet: ${account}\nDream: ${dream}\nClass: ${tier}\nCohort: ${cohort}\nMethod: ${method}`;out('Sign wallet proof (no gas), then request Circle authorization...');const walletSignature=await signer.signMessage(binding);const r=await fetch('/.netlify/functions/flight-seat-authorize',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+token},body:JSON.stringify({dream,tier,cohort,method,wallet:account,walletSignature})});const a=await r.json();if(!r.ok)throw Error(a.error||'Circle authorization failed');const seatAbi=['function buyWithUSDC(bytes32,uint8,uint8,uint32,bytes32,uint256,bytes)','function buyWithCredits(bytes32,uint8,uint8,uint32,bytes32,uint256,bytes)'];const seat=new ethers.Contract(current.contract,seatAbi,signer);if(method===0){const usdc=new ethers.Contract(current.usdc,['function allowance(address,address) view returns(uint256)','function approve(address,uint256) returns(bool)'],signer);const amount=BigInt(tiers[tier][1])*1000000n;if(await usdc.allowance(account,current.contract){choices();for(let i=1;i<=30;i++){const o=document.createElement('option');o.value=i;o.textContent='Dream '+String(i).padStart(2,'0');$('seatDream').append(o)}$('seatDream').addEventListener('change',refresh);$('seatCohort').addEventListener('change',refresh);$('seatTier').addEventListener('change',refresh);$('seatConnect').addEventListener('click',()=>connect().catch(e=>out(e.message)));$('seatBuy').addEventListener('click',()=>purchase(0));$('seatCredit').addEventListener('click',()=>purchase(1));paintMethod(0);showBalances();refresh();setInterval(refresh,30000);}); })();