Carregando...
\n `);w.document.close()}; // Termos como texto no formulário de inscrição e snapshot do texto aceito. const oldChoose=window.pilotChooseEvent; if(oldChoose) window.pilotChooseEvent=async function(id){await oldChoose(id);setTimeout(()=>{const body=document.getElementById('pilotEventBody');if(!body||!currentPilotEvent?.event)return;const e=currentPilotEvent.event;const resp=document.getElementById('peResp');if(resp&&!document.getElementById('pt79ReadResp')){const a=document.createElement('button');a.type='button';a.id='pt79ReadResp';a.className='smallbtn';a.textContent='LER TERMO DE RESPONSABILIDADE';a.onclick=()=>showSignupTerm('responsabilidade');resp.closest('label').insertAdjacentElement('beforebegin',a)}const g=document.getElementById('peRespGuardian');if(g&&!document.getElementById('pt79ReadGuardian')){const a=document.createElement('button');a.type='button';a.id='pt79ReadGuardian';a.className='smallbtn';a.textContent='LER AUTORIZAÇÃO DO RESPONSÁVEL';a.onclick=()=>showSignupTerm('responsavel');g.closest('label').insertAdjacentElement('beforebegin',a)}},50)}; window.showSignupTerm=function(type){const m=ensureModal('pt79SignupTerm',type==='responsavel'?'Autorização do responsável legal':'Termo de responsabilidade'),b=document.getElementById('pt79SignupTermBody'),e=currentPilotEvent?.event||{},p=currentPilotEvent?.pilot||{},fake={nome:p.nome,cpf:p.cpf,responsavel_nome:document.getElementById('peGuardianName')?.value,responsavel_cpf:document.getElementById('peGuardianCpf')?.value,responsavel_parentesco:document.getElementById('peGuardianRelation')?.value,edicao:e.edicao};b.innerHTML=`
${esc(fillTerm(type==='responsavel'?(e.termo_responsavel_texto||TERM_GUARD):(e.termo_responsabilidade_texto||TERM_RESP),fake,e))}
`;m.classList.remove('hidden')}; const oldSubmit=window.submitPilotEvent;if(oldSubmit)window.submitPilotEvent=async function(){const e=currentPilotEvent?.event||{},uid=fbAuth.currentUser?.uid,eventId=String(e.id||'');await oldSubmit();try{if(uid&&eventId){const ref=fbDb.collection('inscricoes').doc(eventId+'_'+uid),s=await ref.get();if(s.exists)await ref.update({termo_responsabilidade_texto:e.termo_responsabilidade_texto||TERM_RESP,termo_responsavel_texto:e.termo_responsavel_texto||TERM_GUARD,termo_versao:e.termo_versao||'2026-10',termo_snapshot_at:firebase.firestore.FieldValue.serverTimestamp()})}}catch(x){console.warn('snapshot termo',x)}}; // Configuração: textos dos termos por edição. const oldCfg=window.openEventConfig;if(oldCfg)window.openEventConfig=async function(){await oldCfg();if(!document.getElementById('cfgTermRespText')){const err=document.getElementById('eventConfigErr'),wrap=document.createElement('div');wrap.innerHTML=`
TEXTOS DOS TERMOS DESTA EDIÇÃO
`;err.insertAdjacentElement('beforebegin',wrap)}const e=currentAdminEvent||{};document.getElementById('cfgTermRespText').value=e.termo_responsabilidade_texto||TERM_RESP;document.getElementById('cfgTermGuardianText').value=e.termo_responsavel_texto||TERM_GUARD}; const oldSaveCfg=window.saveEventConfig;if(oldSaveCfg)window.saveEventConfig=async function(){await oldSaveCfg();try{if(currentAdminEvent?.id&&document.getElementById('cfgTermRespText')){const x={termo_responsabilidade_texto:document.getElementById('cfgTermRespText').value.trim()||TERM_RESP,termo_responsavel_texto:document.getElementById('cfgTermGuardianText').value.trim()||TERM_GUARD,termo_versao:new Date().toISOString().slice(0,10)};await fbDb.collection('eventos').doc(String(currentAdminEvent.id)).update(x);Object.assign(currentAdminEvent,x)}}catch(e){document.getElementById('eventConfigErr').textContent=e.message}}; // Alterar a própria senha do administrador. window.openAdminPassword=function(){const m=ensureModal('pt79Password','Alterar minha senha');document.getElementById('pt79PasswordBody').innerHTML=`
Por segurança, confirme sua senha atual.
`;m.classList.remove('hidden')}; window.saveAdminPassword=async function(){const err=document.getElementById('pt79PassErr'),u=fbAuth.currentUser,cur=document.getElementById('pt79CurrentPass').value,n=document.getElementById('pt79NewPass').value,n2=document.getElementById('pt79NewPass2').value;err.textContent='';try{if(!u?.email)throw new Error('Administrador não autenticado.');if(n.length<8)throw new Error('A nova senha precisa ter pelo menos 8 caracteres.');if(n!==n2)throw new Error('As novas senhas não coincidem.');await u.reauthenticateWithCredential(firebase.auth.EmailAuthProvider.credential(u.email,cur));await u.updatePassword(n);document.getElementById('pt79Password').classList.add('hidden');alert('Senha alterada com sucesso.')}catch(e){err.textContent=(e.code==='auth/wrong-password'||e.code==='auth/invalid-credential')?'Senha atual incorreta.':(e.message||'Não foi possível alterar a senha.')}}; // Adicionar piloto existente manualmente à edição aberta (ideal para reconstrução histórica da 16ª). window.openAddExistingPilot=async function(){const m=ensureModal('pt79AddPilot','Adicionar piloto existente');const b=document.getElementById('pt79AddPilotBody');m.classList.remove('hidden');b.innerHTML=`
Pesquisa a base única de pilotos. Para edições antigas, o registro será marcado como participação histórica adicionada pelo administrador e não criará aceite de termos.
`;try{const q=await fbDb.collection('pilotos').get();window.pt79PilotCache=q.docs.map(d=>({id:d.id,...d.data()}));renderExistingPilotSearch()}catch(e){document.getElementById('pt79AddErr').textContent=e.message}}; window.renderExistingPilotSearch=function(){const box=document.getElementById('pt79PilotResults');if(!box)return;const t=(document.getElementById('pt79PilotSearch')?.value||'').toLowerCase().trim(),list=(window.pt79PilotCache||[]).filter(p=>!t||[p.nome,p.cpf,p.email].some(v=>String(v||'').toLowerCase().includes(t))).slice(0,20);box.innerHTML=list.map(p=>`
${esc(p.nome||'Sem nome')}
${esc(p.email||'')} • CPF ${esc(p.cpf||'—')}
`).join('')||'
Nenhum piloto encontrado.
'}; window.chooseExistingPilot=function(uid){const p=(window.pt79PilotCache||[]).find(x=>x.id===uid);if(!p)return;const box=document.getElementById('pt79PilotResults');box.innerHTML=`
${esc(p.nome)}
${esc(p.email||'')} • CPF ${esc(p.cpf||'—')}
`}; window.saveExistingPilotToEdition=async function(uid){const err=document.getElementById('pt79AddErr');err.textContent='';try{if(!currentAdminEvent?.id)throw new Error('Abra uma edição primeiro.');const p=(window.pt79PilotCache||[]).find(x=>x.id===uid);if(!p)throw new Error('Piloto não encontrado.');const numero=Number(document.getElementById('pt79AddNumber').value),modelo=document.getElementById('pt79AddModel').value.trim(),categoria=document.getElementById('pt79AddCategory').value.trim();if(!numero||!modelo)throw new Error('Informe número e veículo.');const eventId=String(currentAdminEvent.id),dup=await fbDb.collection('inscricoes').where('evento_id','==',eventId).where('piloto_id','==',uid).get();if(!dup.empty)throw new Error('Este piloto já está nesta edição.');const nr=fbDb.collection('numeros_evento').doc(eventId+'_'+numero),ns=await nr.get();if(ns.exists)throw new Error('Este número já está ocupado nesta edição.');const ref=fbDb.collection('inscricoes').doc(eventId+'_'+uid),payload={evento_id:eventId,edicao:Number(currentAdminEvent.edicao||0),piloto_id:uid,nome:p.nome||'',cpf:p.cpf||'',email:p.email||'',telefone:p.telefone||'',cidade:p.cidade||'',numero,modelo,categoria,status:'aprovada',historico_admin:true,origem:'adicionado_manualmente_admin',aceite_responsabilidade:false,aceite_imagem:false,aceite_responsavel:false,createdAt:firebase.firestore.FieldValue.serverTimestamp(),updatedAt:firebase.firestore.FieldValue.serverTimestamp()};const batch=fbDb.batch();batch.set(ref,payload);batch.set(nr,{evento_id:eventId,numero,piloto_id:uid,status:'reservado',tipo:'normal',createdAt:firebase.firestore.FieldValue.serverTimestamp()});batch.update(fbDb.collection('eventos').doc(eventId),{inscricoes_ocupadas:firebase.firestore.FieldValue.increment(1)});await batch.commit();document.getElementById('pt79AddPilot').classList.add('hidden');await openAdminEdition(eventId);alert('Piloto adicionado à edição sem criar aceite de termos.')}catch(e){err.textContent=e.message||'Não foi possível adicionar o piloto.'}}; // Todos os pilotos: cards clicáveis para ficha completa. const oldRenderGlobal=window.renderGlobalPilots;if(oldRenderGlobal)window.renderGlobalPilots=function(){const term=(document.getElementById('globalPilotSearch')?.value||'').toLowerCase(),list=(globalPilotsCache||[]).filter(p=>[p.nome,p.cpf,p.email,p.telefone].some(v=>String(v||'').toLowerCase().includes(term)));document.getElementById('globalPilotsList').innerHTML=list.length?list.map(p=>`

${esc(p.nome||'Sem nome')}

${esc(p.email||'')} • ${esc(p.telefone||'')}
CPF ${esc(p.cpf||'—')} • ${esc(p.cidade||'—')}
VER FICHA
`).join(''):'
Nenhum piloto encontrado.
'}; // Botões novos sem alterar o layout principal. document.addEventListener('DOMContentLoaded',()=>{setTimeout(()=>{const ah=document.querySelector('#adminHome .actions');if(ah&&!document.getElementById('pt79PassBtn')){const b=document.createElement('button');b.id='pt79PassBtn';b.className='btn secondary';b.textContent='🔐 ALTERAR MINHA SENHA';b.onclick=openAdminPassword;ah.appendChild(b)}const ea=document.querySelector('#editionAdmin .actions');if(ea&&!document.getElementById('pt79AddBtn')){const b=document.createElement('button');b.id='pt79AddBtn';b.className='btn secondary';b.textContent='+ ADICIONAR PILOTO EXISTENTE';b.onclick=openAddExistingPilot;ea.insertBefore(b,ea.firstChild)}},100)}); })(); `);w.document.close()}; })(); \n\n '; w.document.write(html);w.document.close();setTimeout(()=>w.print(),350); }catch(e){alert(e.message||'Não foi possível gerar a lista de inscritos.')}finally{if(btn){btn.disabled=false;btn.textContent='LISTA DE INSCRITOS – PDF'}} }; function addBtn(){const a=document.querySelector('#editionAdmin .actions');if(!a||document.getElementById('pt7911MedicalPdfBtn'))return;const b=document.createElement('button');b.id='pt7911MedicalPdfBtn';b.className='btn secondary';b.textContent='LISTA DE INSCRITOS – PDF';b.onclick=window.printRegisteredPilotsPdf;const r=[...a.querySelectorAll('button')].find(x=>/RELATÓRIO FINAL/i.test(x.textContent||''));r?a.insertBefore(b,r):a.appendChild(b)} document.addEventListener('DOMContentLoaded',()=>setTimeout(addBtn,150));setTimeout(addBtn,500); })();