$ Compramos sua Moto WhatsApp Instagram Localização

© 2026 QUIPAPA MULTIMARCAS

ESTOQUE

Modelo
Preço (R$)
Ano

Modelo
Ano
Quilometragem
Preço
WhatsApp
PAINEL ADMIN
Digite a senha para acessar
Senha incorreta
⚙ ADMIN
Adicionar Moto
⏳ Enviando fotos...
Motos Cadastradas
0
Visitas no período
0
Motos visitadas
Mais visitada
Menos visitada
Ranking
'; }).join('')+'
' +''; } function rmNewImg(i){newimgs.splice(i,1);renderNewGrid();} // ════ ADMIN LIST ════ function renderList(){ var el=document.getElementById('alist'); if(!MOTOS.length){el.innerHTML='
Nenhuma moto cadastrada.
';return;} var openIds=[]; document.querySelectorAll('.epan.open').forEach(function(p){openIds.push(p.id);}); el.innerHTML=MOTOS.map(function(m){ var sold=m.vendida?' ● VENDIDA':''; var imghtml=(m.imagens||[]).map(function(src,i){ return '
'; }).join('')+'
'; return '
' +'
' +'
'+m.nome+sold+'
' +'
'+m.ano+' • '+m.quilometragem+'
' +'
'+m.preco+'
' +'
' +'' +'' +'' +'
' +'
' +'
' +'
' +'
' +'
' +'
' +'
' +'
' +'
' +'
' +'
'+imghtml+'
' +'' +'
' +'' +'
'; }).join(''); openIds.forEach(function(pid){var p=document.getElementById(pid);if(p)p.classList.add('open');}); } function togEdit(id){document.getElementById('ep'+id).classList.toggle('open');} function saveMoto(id){ var n=document.getElementById('en'+id),a=document.getElementById('ea'+id); var k=document.getElementById('ek'+id),pr=document.getElementById('epr'+id); var de=document.getElementById('ed'+id); if(!n||!pr){toast('Erro: campos não encontrados');return;} var nome=n.value.trim(),preco=pr.value.trim(); if(!nome||!preco){toast('Preencha Nome e Preço');return;} var btn=document.getElementById('es'+id); if(btn){btn.disabled=true;btn.textContent='⏳ Salvando...';} db.collection('motos').doc(id).update({ nome:nome, ano:parseInt(a?a.value:0)||0, quilometragem:k?k.value.trim():'', preco:preco, precoNum:parseFloat(preco.replace(/[^0-9.]/g,''))||0, descricao:de?de.value.trim():'' }).then(function(){ toast('✓ Alterações salvas!'); if(btn){btn.disabled=false;btn.textContent='✓ Salvar';} }).catch(function(e){ toast('Erro: '+e.message); if(btn){btn.disabled=false;btn.textContent='✓ Salvar';} }); } function addEditImgs(input,id){ var btn=document.getElementById('es'+id); if(btn){btn.disabled=true;btn.textContent='⏳ Enviando...';} uploadFotos(Array.from(input.files),id).then(function(urls){ var m=null;for(var i=0;i 0) entries.push({ id: k, nome: v.nome || '—', count: count }); } } }); entries.sort(function(a,b){ return b.count - a.count; }); // Total geral do período var periodTotal = 0; if(anPeriod === 'hoje') periodTotal = data['_totd_' + today] || 0; if(anPeriod === 'semana') periodTotal = data['_tots_' + wk] || 0; if(anPeriod === 'mes') periodTotal = data['_totm_' + mo] || 0; if(anPeriod === 'tudo') periodTotal = entries.reduce(function(s,e){ return s + e.count; }, 0); document.getElementById('antotal').textContent = periodTotal; document.getElementById('anmotos').textContent = entries.length; document.getElementById('anhoje').textContent = entries[0] ? entries[0].nome.split(' ').slice(0,2).join(' ') : '—'; document.getElementById('antop').textContent = entries.length > 1 ? entries[entries.length-1].nome.split(' ').slice(0,2).join(' ') : '—'; if(!entries.length){ rank.innerHTML = '
Sem visitas neste período.
'; return; } var maxV = entries[0].count; var pc = ['gold','silver','bronze']; rank.innerHTML = entries.map(function(e, i){ var m = null; for(var j = 0; j < MOTOS.length; j++){ if(MOTOS[j].id === e.id){ m = MOTOS[j]; break; } } var meta = m ? (m.ano + ' • ' + m.quilometragem + ' • ' + m.preco) : 'Removida do estoque'; var pct = Math.round(e.count / maxV * 100); var dataId = m ? (e.id) : null; var divOpen = dataId ? '
' : '
'; return divOpen + '
' + (i+1) + '
' + '
' + '
' + e.nome + '
' + '
' + meta + '
' + '
' + '
' + '
' + e.count + 'visitas
' + '
'; }).join(''); }).catch(function(err){ rank.innerHTML = '
Erro ao carregar dados.
'; console.error('renderAn:', err); }); } function resetAn(){ if(!confirm('Zerar todos os dados de visitas?')) return; db.collection('analytics').doc('views').delete().then(function(){ renderAn(); toast('Dados zerados'); }); } // ════ CLOUDINARY ════ function uploadFotos(files,motoId){ var CL='dkjskbcvu', CP='quipapa_motos'; var promises=files.map(function(f){ var fd=new FormData(); fd.append('file',f);fd.append('upload_preset',CP);fd.append('folder','motos/'+motoId); return fetch('https://api.cloudinary.com/v1_1/'+CL+'/image/upload',{method:'POST',body:fd}) .then(function(r){retur.then(function(d){if(d.secure_url)return d.secure_url;throw new Error(d.error&&d.error.message||'Erro Cloudinary');}); }); return Promise.all(promises); } // ════ TOAST ════ function toast(msg){ var t=document.getElementById('toast'); t.textContent=msg;t.classList.add('show'); setTimeout(function(){t.classList.remove('show');},2500); } // ════ FIREBASE INIT ════ try{ firebase.initializeApp({ apiKey:"AIzaSyAps1xgMeQgLLrQKhw4oEuqTNErpvMX94", authDomain:"quipapa-multimarcas.firebaseapp.com", projectId:"quipapa-multimarcas", storageBucket:"quipapa-multimarcas.firebasestorage.app", messagingSenderId:"731303861629", appId:"1:731303861629:web:b544afef8515c3586ec014" }); db=firebase.firestore(); // Firestore offline cache - persiste dados entre sessões db.enablePersistence({synchronizeTabs:true}).catch(function(){}); // Carrega cache local imediatamente enquanto busca do servidor try { var cached = localStorage.getItem('qm_motos_cache'); if(cached){ MOTOS = JSON.parse(cached); renderCat(); popModelos(); document.getElementById('mgrid').querySelectorAll('.mcard').forEach(function(c,i){ c.style.animationDelay = (i*0.03)+'s'; }); } } catch(e){} db.collection('motos').orderBy('criadoEm','desc').onSnapshot(function(snap){ MOTOS = snap.docs.map(function(d){ return Object.assign({id:d.id}, d.data()); }); // Salva cache local (sem imagens base64 para não pesar) try { var lite = MOTOS.map(function(m){ return {id:m.id, nome:m.nome, ano:m.ano, quilometragem:m.quilometragem, preco:m.preco, vendida:m.vendida, imagens: m.imagens ? [m.imagens[0]] : [] }; // só primeira foto no cache }); localStorage.setItem('qm_motos_cache', JSON.stringify(lite)); } catch(e){} renderCat(); popModelos(); if(document.getElementById('pg-adm').classList.contains('active')) renderList(); }, function(err){ console.error('Firestore error:', err); if(!MOTOS.length) document.getElementById('mgrid').innerHTML='
Erro ao carregar. Verifique sua conexão.
'; }); }catch(e){ console.error('Firebase init error:',e); } // ════ EVENTOS ════ document.addEventListener('keydown',function(e){if(e.key==='Escape')closeLB();}); document.addEventListener('click',function(e){ var item = e.target.closest ? e.target.closest('[data-mid]') : null; if(item){ openDet(item.getAttribute('data-mid')); } }); var ltap=0,ltmr; document.getElementById('hlogo').addEventListener('click',function(){ ltap++;clearTimeout(ltmr);ltmr=setTimeout(function(){ltap=0;},1500); if(ltap>=5){ltap=0;goTo('login');} }); document.getElementById('caro').addEventListener('touchstart',function(e){tst=e.touches[0].clientX;}); .then(function(d){if(d.secure_url)return d.secure_url;throw new Error(d.error&&d.error.message||'Erro Cloudinary');}); }); return Promise.all(promises); } // ════ TOAST ════ function toast(msg){ var t=document.getElementById('toast'); t.textContent=msg;t.classList.add('show'); setTimeout(function(){t.classList.remove('show');},2500); } // ════ FIREBASE INIT ════ try{ firebase.initializeApp({ apiKey:"AIzaSyAps1xgMeQgLLrQKhw4oEuqTNErpvMX94", authDomain:"quipapa-multimarcas.firebaseapp.com", projectId:"quipapa-multimarcas", storageBucket:"quipapa-multimarcas.firebasestorage.app", messagingSenderId:"731303861629", appId:"1:731303861629:web:b544afef8515c3586ec014" }); db=firebase.firestore(); db.collection('motos').orderBy('criadoEm','desc').onSnapshot(function(snap){ MOTOS=snap.docs.map(function(d){return Object.assign({id:d.id},d.data());}); renderCat();popModelos(); if(document.getElementById('pg-adm').classList.contains('active'))renderList(); },function(err){ console.error('Firestore error:',err); document.getElementById('mgrid').innerHTML='
Erro ao carregar dados.
'; }); }catch(e){ console.error('Firebase init error:',e); } // ════ EVENTOS ════ document.addEventListener('keydown',function(e){if(e.key==='Escape')closeLB();}); document.addEventListener('click',function(e){ var item = e.target.closest ? e.target.closest('[data-mid]') : null; if(item){ openDet(item.getAttribute('data-mid')); } }); var ltap=0,ltmr; document.getElementById('hlogo').addEventListener('click',function(){ ltap++;clearTimeout(ltmr);ltmr=setTimeout(function(){ltap=0;},1500); if(ltap>=5){ltap=0;goTo('login');} }); document.getElementById('caro').addEventListener('touchstart',function(e){tst=e.touches[0].clientX;});