-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
413 lines (323 loc) · 10.8 KB
/
Copy pathscript.js
File metadata and controls
413 lines (323 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
let bares = [];
let ingredientes = [];
let tagsSelecionadas = [];
const COUNTER_NAMESPACE = 'guourso-guia-botecos-cdb-2026';
const COUNTER_BASE_URLS = [
'https://countapi.xyz',
'https://api.countapi.xyz'
];
// =========================
// CARREGAMENTO INICIAL
// =========================
async function carregarDados() {
const resBares = await fetch('./bares.json');
bares = await resBares.json();
const resIngredientes = await fetch('./ingredientes.json');
const dataIngredientes = await resIngredientes.json();
ingredientes = dataIngredientes.todos_ingredientes;
popularFiltros();
carregarFiltrosSalvos(); // 🔥 carrega filtros
aplicarFiltros();
}
carregarDados();
configurarContadorVisitas();
configurarBotaoLike();
// =========================
// CONTADORES GLOBAIS
// =========================
async function consultarContadorGlobal(chave, incrementar = false) {
let ultimoErro = null;
for (const baseUrl of COUNTER_BASE_URLS) {
try {
const rota = incrementar ? 'hit' : 'get';
const resposta = await fetch(`${baseUrl}/${rota}/${COUNTER_NAMESPACE}/${chave}`, {
cache: 'no-store'
});
if (resposta.status === 404) {
return 0;
}
if (!resposta.ok) {
throw new Error(`HTTP ${resposta.status}`);
}
const data = await resposta.json();
return Number(data.value || 0);
} catch (erro) {
ultimoErro = erro;
}
}
throw ultimoErro || new Error('Falha ao consultar contador global.');
}
function obterContadorLocal(chave) {
return Number(localStorage.getItem(chave) || '0');
}
function incrementarContadorLocal(chave) {
const novoTotal = obterContadorLocal(chave) + 1;
localStorage.setItem(chave, String(novoTotal));
return novoTotal;
}
async function configurarContadorVisitas() {
const contador = document.getElementById('visit-counter-value');
if (!contador) return;
contador.textContent = '...';
try {
const totalVisitas = await consultarContadorGlobal('visitas', true);
contador.textContent = totalVisitas;
} catch {
const totalVisitas = incrementarContadorLocal('contadorVisitasSite');
contador.textContent = totalVisitas;
}
}
async function configurarBotaoLike() {
const botao = document.getElementById('like-button');
const contador = document.getElementById('like-counter-value');
const mensagem = document.getElementById('like-message');
if (!botao || !contador || !mensagem) return;
const jaCurtiu = localStorage.getItem('usuarioJaCurtiuSite') === 'true';
contador.textContent = '...';
try {
const totalLikes = await consultarContadorGlobal('likes');
contador.textContent = totalLikes;
} catch {
contador.textContent = obterContadorLocal('contadorLikesSite');
}
if (jaCurtiu) {
botao.disabled = true;
mensagem.textContent = 'Você já deixou seu like neste navegador. 💛';
return;
}
botao.addEventListener('click', async () => {
botao.disabled = true;
mensagem.textContent = 'Registrando seu like...';
try {
const novoTotal = await consultarContadorGlobal('likes', true);
contador.textContent = novoTotal;
} catch {
const novoTotal = incrementarContadorLocal('contadorLikesSite');
contador.textContent = novoTotal;
}
localStorage.setItem('usuarioJaCurtiuSite', 'true');
mensagem.textContent = 'Like registrado com sucesso! 💛';
});
}
// =========================
// FILTROS (BAIRRO / REGIÃO)
// =========================
function popularFiltros() {
const bairros = [...new Set(bares.map(b => b.bairro))];
const regioes = [...new Set(bares.map(b => b.regiao))];
const selectBairro = document.getElementById('filtro-bairro');
const selectRegiao = document.getElementById('filtro-regiao');
bairros.forEach(b => {
const opt = document.createElement('option');
opt.value = b;
opt.innerText = b;
selectBairro.appendChild(opt);
});
regioes.forEach(r => {
const opt = document.createElement('option');
opt.value = r;
opt.innerText = r;
selectRegiao.appendChild(opt);
});
}
// =========================
// RENDERIZAÇÃO
// =========================
function renderizarBares(lista) {
const container = document.getElementById('lista-bares');
const emptyState = document.getElementById('empty-state');
container.innerHTML = '';
if (lista.length === 0) {
emptyState.style.display = 'block';
return;
}
emptyState.style.display = 'none';
lista.forEach(bar => {
const card = document.createElement('div');
card.className = 'bar-card';
card.innerHTML = `
<img src="${bar.imagem}" alt="${bar.bar}">
<div class="bar-card-content">
<h3>${bar.bar}</h3>
<p>${bar.prato}</p>
<button onclick='abrirModal(${JSON.stringify(bar)})'>
Ver detalhes
</button>
</div>
`;
container.appendChild(card);
});
}
// =========================
// FILTROS
// =========================
function aplicarFiltros() {
const busca = document.getElementById('search').value.toLowerCase();
const dia = document.getElementById('filtro-dia').value;
const bairro = document.getElementById('filtro-bairro').value;
const regiao = document.getElementById('filtro-regiao').value;
const filtrados = bares.filter(bar => {
const texto = (bar.prato + ' ' + bar.descricao).toLowerCase();
const matchBusca = bar.bar.toLowerCase().includes(busca);
const matchDia =
!dia ||
(bar.horarios || []).some(h => h.dia === dia);
const matchBairro = !bairro || bar.bairro === bairro;
const matchRegiao = !regiao || bar.regiao === regiao;
const matchTags =
tagsSelecionadas.length === 0 ||
tagsSelecionadas.some(tag =>
texto.includes(tag.toLowerCase())
);
return matchBusca && matchDia && matchBairro && matchRegiao && matchTags;
});
renderizarBares(filtrados);
salvarFiltros(); // 🔥 salva sempre
}
// =========================
// EVENTOS DOS FILTROS
// =========================
document.getElementById('search').addEventListener('input', aplicarFiltros);
document.getElementById('filtro-dia').addEventListener('change', aplicarFiltros);
document.getElementById('filtro-bairro').addEventListener('change', aplicarFiltros);
document.getElementById('filtro-regiao').addEventListener('change', aplicarFiltros);
// =========================
// LOCAL STORAGE
// =========================
function salvarFiltros() {
const filtros = {
busca: document.getElementById('search').value,
dia: document.getElementById('filtro-dia').value,
bairro: document.getElementById('filtro-bairro').value,
regiao: document.getElementById('filtro-regiao').value,
tags: tagsSelecionadas
};
localStorage.setItem('filtrosBares', JSON.stringify(filtros));
}
function carregarFiltrosSalvos() {
const data = localStorage.getItem('filtrosBares');
if (!data) return;
const filtros = JSON.parse(data);
document.getElementById('search').value = filtros.busca || '';
document.getElementById('filtro-dia').value = filtros.dia || '';
document.getElementById('filtro-bairro').value = filtros.bairro || '';
document.getElementById('filtro-regiao').value = filtros.regiao || '';
if (filtros.tags && filtros.tags.length > 0) {
filtros.tags.forEach(tag => adicionarTag(tag));
}
}
// =========================
// BOTÃO LIMPAR FILTROS
// =========================
document.getElementById('limpar-filtros').addEventListener('click', () => {
document.getElementById('search').value = '';
document.getElementById('filtro-dia').value = '';
document.getElementById('filtro-bairro').value = '';
document.getElementById('filtro-regiao').value = '';
tagsSelecionadas = [];
document.getElementById('filtro-tags').innerHTML = '';
localStorage.removeItem('filtrosBares');
aplicarFiltros();
});
// =========================
// AUTOCOMPLETE DE TAGS
// =========================
const inputTag = document.getElementById('input-tag');
const sugestoesBox = document.getElementById('sugestoes-tags');
inputTag.addEventListener('input', () => {
const valor = inputTag.value.toLowerCase();
sugestoesBox.innerHTML = '';
if (!valor) return;
const filtradas = ingredientes
.filter(i => i.toLowerCase().includes(valor))
.slice(0, 10);
if (filtradas.length === 0) {
sugestoesBox.innerHTML = `<div class="sugestao-item">Nenhum resultado</div>`;
return;
}
filtradas.forEach(item => {
const div = document.createElement('div');
div.className = 'sugestao-item';
div.innerHTML = item.replace(
new RegExp(valor, 'gi'),
match => `<strong>${match}</strong>`
);
div.addEventListener('click', () => {
adicionarTag(item);
inputTag.value = '';
sugestoesBox.innerHTML = '';
});
sugestoesBox.appendChild(div);
});
});
document.addEventListener('click', (e) => {
if (!e.target.closest('.busca-tags')) {
sugestoesBox.innerHTML = '';
}
});
// =========================
// TAGS
// =========================
function adicionarTag(tag) {
tag = tag.toLowerCase();
if (tagsSelecionadas.includes(tag)) return;
tagsSelecionadas.push(tag);
const container = document.getElementById('filtro-tags');
const tagEl = document.createElement('div');
tagEl.className = 'tag';
tagEl.innerHTML = `
<span>${tag}</span>
<button class="tag-remove">✕</button>
`;
tagEl.querySelector('.tag-remove').addEventListener('click', (e) => {
e.stopPropagation();
tagsSelecionadas = tagsSelecionadas.filter(t => t !== tag);
tagEl.remove();
aplicarFiltros();
});
container.appendChild(tagEl);
aplicarFiltros();
}
// =========================
// MODAL
// =========================
const modal = document.createElement('div');
modal.className = 'modal';
document.body.appendChild(modal);
function abrirModal(bar) {
const horariosHTML = (bar.horarios || [])
.map(h => `<p>${h.dia}: ${h.abertura} - ${h.fechamento}</p>`)
.join('');
modal.innerHTML = `
<div class="modal-content">
<button class="modal-close" onclick="fecharModal()">✕</button>
<img src="${bar.imagem}" class="modal-img">
<div class="modal-body">
<h2>${bar.bar}</h2>
<p class="modal-prato">${bar.prato}</p>
<p class="modal-descricao">
${bar.descricao || ''}
</p>
<div class="modal-info">
<p><strong>📍 Endereço:</strong> ${bar.endereco}</p>
<p><strong>📞 Telefone:</strong> ${bar.telefone}</p>
</div>
<div class="modal-horarios">
<h4>Horários</h4>
${horariosHTML}
</div>
</div>
</div>
`;
modal.style.display = 'flex';
document.body.style.overflow = 'hidden';
}
function fecharModal() {
modal.style.display = 'none';
document.body.style.overflow = 'auto';
}
modal.addEventListener('click', (e) => {
if (e.target === modal) {
fecharModal();
}
});