/* Protótipo local: consulta a API pública existente; monta a imagem no navegador. */
$(function() {
const storefront = document.querySelector('[data-storefront-share]');
if (!storefront || typeof HTMLDialogElement === 'undefined') return;
const menu = storefront.querySelector('.storefront-share-options');
if (!menu) return;
const printButton = document.createElement('button');
printButton.type = 'button';
printButton.textContent = 'Gerar imagem';
menu.append(printButton);
const adsList = document.querySelector('#ads-list');
function syncPrintAvailability() {
printButton.hidden = !adsList?.querySelector('article.card');
}
syncPrintAvailability();
if (adsList) {
new MutationObserver(syncPrintAvailability).observe(adsList, {childList: true, subtree: true});
}
storefront.querySelector('.storefront-share-main').addEventListener('click', function(event) {
if (!isMobileStorefrontShare()) return;
event.stopImmediatePropagation();
toggleStorefrontShareMenu($(storefront));
});
let dialog, blobUrl, pendingRequest, filters, brandLogoPromise, filterDescription, shareFile;
let generation = 0, page = 0, total = null, currentCount = null, hasMore = false, busy = false;
function updateNavigation() {
dialog.querySelector('[data-print-prev]').disabled = busy || page === 0;
dialog.querySelector('[data-print-next]').disabled = busy || !hasMore;
dialog.querySelector('[data-print-prev]').hidden = page === 0;
dialog.querySelector('[data-print-next]').hidden = !hasMore;
const label = dialog.querySelector('[data-print-summary]');
const quantity = currentCount === null ? '' : currentCount + (total === null ? ' anúncios · ' : ' de ' + total + ' anúncios · ');
label.textContent = quantity + (total === null
? 'Print ' + (page + 1)
: 'Print ' + (total ? page + 1 : 0) + ' de ' + Math.ceil(total / 32));
}
printButton.addEventListener('click', function() {
closeStorefrontShareMenus();
filters = collectAdFilters();
filterDescription = describePrintFilters(filters);
page = 0;
total = null;
hasMore = false;
if (!dialog) {
dialog = document.createElement('dialog');
dialog.className = 'vitrine-print-dialog';
dialog.setAttribute('aria-labelledby', 'vitrine-print-title');
dialog.innerHTML = '
';
document.body.append(dialog);
dialog.querySelector('.vitrine-print-close').onclick = () => dialog.close();
dialog.addEventListener('click', e => {
const rect = dialog.getBoundingClientRect();
if (e.target === dialog && (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom)) dialog.close();
});
dialog.addEventListener('close', () => {
generation++;
if (pendingRequest) pendingRequest.abort();
if (blobUrl) URL.revokeObjectURL(blobUrl);
blobUrl = null;
shareFile = null;
printButton.focus();
});
dialog.querySelector('[data-print-prev]').onclick = () => { if (!busy && page > 0) renderPage(page - 1); };
dialog.querySelector('[data-print-next]').onclick = () => { if (!busy && hasMore) renderPage(page + 1); };
dialog.querySelector('[data-print-retry]').onclick = () => { if (!busy) renderPage(page); };
dialog.querySelector('[data-print-share]').onclick = async function() {
if (!shareFile || busy) return;
const run = generation;
busy = true;
this.disabled = true;
updateNavigation();
try {
await navigator.share({files: [shareFile]});
} catch (error) {
if (run === generation && error.name !== 'AbortError') {
dialog.querySelector('.vitrine-print-status').textContent = 'Não foi possível compartilhar. Você pode baixar a imagem.';
}
} finally {
if (run === generation) {
busy = false;
this.disabled = false;
updateNavigation();
}
}
};
dialog.querySelector('[data-print-download]').onclick = () => {
if (!blobUrl) return;
const link = document.createElement('a');
link.href = blobUrl;
link.download = 'anuncios-garagem164-print-' + (page + 1) + '.png';
document.body.append(link);
link.click();
link.remove();
};
}
dialog.showModal();
renderPage(0);
});
async function renderPage(targetPage) {
const run = ++generation;
page = targetPage;
currentCount = null;
busy = true;
hasMore = false;
updateNavigation();
const status = dialog.querySelector('.vitrine-print-status');
const download = dialog.querySelector('[data-print-download]');
const retry = dialog.querySelector('[data-print-retry]');
download.disabled = true;
shareFile = null;
const shareButton = dialog.querySelector('[data-print-share]');
shareButton.hidden = true;
shareButton.disabled = false;
retry.hidden = true;
if (blobUrl) URL.revokeObjectURL(blobUrl);
blobUrl = null;
status.textContent = 'Buscando anúncios…';
const canvas = dialog.querySelector('canvas');
canvas.width = 1920;
canvas.height = 1080;
try {
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('canvas');
const result = await loadPrintAds(filters, options => {
pendingRequest = $.ajax(options);
return pendingRequest;
}, () => run === generation, page * 32, total === null);
if (run !== generation) return;
pendingRequest = null;
if (result.total !== null) total = result.total;
hasMore = result.hasMore;
updateNavigation();
const parsed = new DOMParser().parseFromString(result.html, 'text/html');
const cards = Array.from(parsed.querySelectorAll('article.card')).slice(0, 32);
currentCount = cards.length;
updateNavigation();
if (!cards.length) {
status.textContent = page === 0 ? 'Nenhum anúncio encontrado para os filtros atuais.' : 'Não há mais anúncios nesta página. Volte ao print anterior.';
return;
}
status.textContent = 'Preparando suas fotos…';
const items = cards.map(card => ({
publicId: card.dataset.adPublicId || '',
title: card.querySelector('h3')?.textContent.trim() || 'Anúncio',
price: card.querySelector('.price')?.textContent.trim() || 'Consulte',
image: card.querySelector('.ad-thumb-img')?.src
}));
const photos = new Array(items.length);
let nextPhoto = 0;
await Promise.all(Array.from({length: Math.min(3, items.length)}, async () => {
while (nextPhoto < items.length && run === generation) {
const index = nextPhoto++;
photos[index] = await loadPrintPhoto(items[index].image);
if (!photos[index] && run === generation && /^[a-zA-Z0-9]{36}$/.test(items[index].publicId)) {
photos[index] = await loadPrintPhoto('/anuncio-miniatura?anuncio=' + encodeURIComponent(items[index].publicId));
}
}
}));
if (run !== generation) return;
const printTitle = storefront.dataset.shareContext === 'catalog'
? 'Anúncios'
: 'Vitrine de ' + (storefront.dataset.shareName || 'colecionador');
brandLogoPromise = brandLogoPromise || loadPrintPhoto('/assets/img/logo-header-novo.png');
const brandLogo = await brandLogoPromise;
if (run !== generation) return;
drawStorefrontPrint(ctx, items, photos, printTitle, brandLogo, filterDescription);
const missing = photos.filter(photo => !photo).length;
if (missing) {
status.textContent = 'Não foi possível carregar ' + missing + ' foto(s). Tente novamente em instantes.';
retry.hidden = false;
return;
}
const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
if (run !== generation) return;
if (!blob) throw new Error('export');
blobUrl = URL.createObjectURL(blob);
if (typeof File === 'function' && typeof navigator.share === 'function' && typeof navigator.canShare === 'function') {
try {
const file = new File([blob], 'anuncios-garagem164-print-' + (page + 1) + '.png', {type: 'image/png'});
if (navigator.canShare({files: [file]})) {
shareFile = file;
shareButton.hidden = false;
}
} catch (_) { /* Download continua disponível se arquivos não forem suportados. */ }
}
download.disabled = false;
status.textContent = '';
} catch (_) {
if (run === generation) {
status.textContent = 'Não foi possível preparar este print. Tente novamente.';
retry.hidden = false;
}
} finally {
if (run === generation) {
busy = false;
pendingRequest = null;
updateNavigation();
}
}
}
});
// Consulta somente o print solicitado, em até dois blocos da API pública.
async function loadPrintAds(filters, request, isCurrent, startOffset = 0, includeSummary = false) {
let offset = startOffset;
let html = '', hasMore = false, total = null;
for (let batch = 0; batch < 2 && offset < startOffset + 32 && isCurrent(); batch++) {
const response = await request({
type: 'POST', url: '/api/anuncios', dataType: 'json', timeout: 15000,
data: {
...filters, offset, limit: Math.min(24, startOffset + 32 - offset),
print_summary: includeSummary && batch === 0 ? '1' : '0',
vehicle_brand: filters.vehicleBrand,
hot_wheels_treasure_type: filters.hotWheelsTreasureType,
ad_types: filters.adTypes, seller_username: filters.sellerUsername
}
});
if (!response || response.result !== 'ads_loaded' || typeof response.html !== 'string') throw new Error('ads');
html += response.html;
if (Number.isInteger(response.totalCount) && response.totalCount >= 0) total = response.totalCount;
hasMore = Boolean(response.hasMore);
if (!hasMore) break;
const next = Number(response.nextOffset);
if (!Number.isInteger(next) || next <= offset) throw new Error('pagination');
offset = next;
}
return {html, hasMore, total};
}
function loadPrintPhoto(url) {
return new Promise(resolve => {
if (!url) { resolve(null); return; }
const image = new Image();
const timer = setTimeout(() => { image.src = ''; resolve(null); }, 12000);
image.crossOrigin = 'anonymous';
image.onload = () => { clearTimeout(timer); resolve(image); };
image.onerror = () => { clearTimeout(timer); resolve(null); };
image.src = url;
});
}
// Rótulos visíveis capturados ao abrir, iguais em todas as páginas do print.
function describePrintFilters(filters) {
const parts = [];
if (filters.search.trim()) parts.push('Busca: ' + filters.search.trim());
const groups = [
['manufacturer', 'Fabricante'], ['accessory_type', 'Tipo'],
['scale', 'Escala'], ['condition', 'Estado'], ['ad_type', 'Formato']
];
groups.forEach(([name, title]) => {
const labels = Array.from(document.querySelectorAll('input[name="' + name + '"]:checked'))
.map(input => input.closest('label')?.textContent.trim() || input.value);
if (labels.length) parts.push(title + ': ' + labels.join(', '));
});
[['adsVehicleBrand', 'Marca'], ['adsHotWheelsTreasureType', 'Hot Wheels'],
['adsPrice', 'Preço'], ['adsState', 'UF'], ['adsCity', 'Cidade']].forEach(([id, title]) => {
const select = document.getElementById(id);
if (select?.value) parts.push(title + ': ' + (select.selectedOptions[0]?.textContent.trim() || select.value));
});
const chips = Array.from(document.querySelectorAll('.chip.active:not([data-chip="all"])'))
.map(chip => chip.textContent.trim());
if (chips.length) parts.push(chips.join(', '));
const sort = document.getElementById('adsSort');
if (sort?.value && sort.value !== 'recent') parts.push('Ordem: ' + sort.selectedOptions[0].textContent.trim());
if (parts.length || filters.listing_category === 'accessory') {
parts.unshift(filters.listing_category === 'accessory' ? 'Acessórios' : 'Miniaturas');
}
return parts.join(' · ');
}
function drawStorefrontPrint(ctx, items, photos, seller, brandLogo = null, filterDescription = '') {
const text = (value, x, y, width, size, color, weight = 400) => {
ctx.font = weight + ' ' + size + 'px Arial, sans-serif';
ctx.fillStyle = color;
let label = value;
while (label.length && ctx.measureText(label).width > width) label = label.slice(0, -1);
if (label !== value) label = label.slice(0, -1) + '…';
ctx.fillText(label, x, y);
};
const height = 1080;
const margin = 16;
const gap = 12;
const headerHeight = 112;
const top = headerHeight + 8;
const availableHeight = height - top - 36;
// Escolhe a grade que oferece a maior foto quadrada sem alterar o tamanho final.
let layout = {side: 0};
for (let columns = 1; columns <= Math.min(10, items.length); columns++) {
const rows = Math.ceil(items.length / columns);
const side = Math.floor(Math.min(
(1920 - margin * 2 - gap * (columns - 1)) / columns,
(availableHeight - gap * (rows - 1)) / rows
));
if (side > layout.side) layout = {columns, rows, side};
}
const {columns, rows, side} = layout;
const width = side;
const imageHeight = side;
const cardHeight = side;
const gridTop = top + (availableHeight - rows * cardHeight - (rows - 1) * gap) / 2;
ctx.canvas.width = 1920;
ctx.canvas.height = height;
ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, 1920, height);
ctx.fillStyle = '#f4f6f8';
ctx.fillRect(0, 0, 1920, headerHeight);
ctx.fillStyle = '#e0e5ec';
ctx.fillRect(0, headerHeight - 1, 1920, 1);
const filterLines = [];
if (filterDescription) {
ctx.font = '18px Arial, sans-serif';
const words = ('Filtros: ' + filterDescription).split(/\s+/);
let line = '';
let lineNumber = 0;
for (let index = 0; index < words.length; index++) {
const candidate = line ? line + ' ' + words[index] : words[index];
if (ctx.measureText(candidate).width > 1580 && line && lineNumber === 0) {
filterLines.push(line);
line = words[index];
lineNumber = 1;
} else line = candidate;
}
filterLines.push(line);
}
// Centraliza o bloco inteiro, mantendo o mesmo cabeçalho com 0, 1 ou 2 linhas de filtros.
const titleBaseline = headerHeight / 2 + 10 - filterLines.length * 13;
text(seller, margin, titleBaseline, 1580, 28, '#20252b', 700);
filterLines.forEach((line, index) => {
text(line, margin, titleBaseline + 28 + index * 26, 1580, 18, '#69727d');
});
if (brandLogo) {
const logoHeight = 72;
const logoWidth = logoHeight * brandLogo.naturalWidth / brandLogo.naturalHeight;
ctx.drawImage(brandLogo, 1920 - margin - logoWidth, (headerHeight - logoHeight) / 2, logoWidth, logoHeight);
} else {
ctx.save();
ctx.textAlign = 'right';
text('Garagem 1:64', 1920 - margin, headerHeight / 2 + 10, 280, 26, '#101820', 700);
ctx.restore();
}
items.forEach((item, index) => {
const row = Math.floor(index / columns);
const rowCount = Math.min(columns, items.length - row * columns);
const rowLeft = (1920 - rowCount * width - (rowCount - 1) * gap) / 2;
const x = rowLeft + (index % columns) * (width + gap);
const y = gridTop + Math.floor(index / columns) * (cardHeight + gap);
ctx.save();
ctx.beginPath();
ctx.roundRect(x, y, width, cardHeight, Math.min(18, width / 12));
ctx.clip();
ctx.fillStyle = '#ffffff'; ctx.fillRect(x, y, width, cardHeight);
ctx.fillStyle = '#f2f4f6'; ctx.fillRect(x, y, width, imageHeight);
const photo = photos[index];
if (photo) {
const side = Math.min(photo.naturalWidth, photo.naturalHeight);
const sourceX = (photo.naturalWidth - side) / 2;
const sourceY = (photo.naturalHeight - side) / 2;
ctx.drawImage(photo, sourceX, sourceY, side, side, x, y, width, imageHeight);
} else text('Foto indisponível', x + 14, y + imageHeight / 2, width - 28, 20, '#626d79');
ctx.fillStyle = 'rgba(255,255,255,0.96)';
ctx.fillRect(x, y + imageHeight - 60, width, 60);
text(item.title, x + 14, y + imageHeight - 37, width - 28, 16, '#58616c');
text(item.price, x + 14, y + imageHeight - 12, width - 28, 22, '#20252b', 700);
ctx.restore();
});
const issuedAt = new Intl.DateTimeFormat('pt-BR', {
timeZone: 'America/Sao_Paulo',
day: '2-digit', month: '2-digit', year: 'numeric',
hour: '2-digit', minute: '2-digit', hour12: false
}).format(new Date());
text(window.location.host + window.location.pathname, margin, height - 12, 1250, 14, '#929aa5');
ctx.save();
ctx.textAlign = 'right';
text('Gerado em ' + issuedAt + ' (Brasília)', 1920 - margin, height - 12, 600, 14, '#929aa5');
ctx.restore();
}