Spaces:
Configuration error

Carlos z commited on
Commit
9270380
·
verified ·
1 Parent(s): 6fed12b

Upload 6 files

Browse files
static/js/api.js ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Sahkey Imóveis — camada de acesso à API e helpers de formatação */
2
+
3
+ const API_BASE = "/api/anuncios";
4
+ const WHATSAPP_NUMERO = "5541998112201"; // Sahkey — atendimento central (demo)
5
+
6
+ function apiUrl(path, params = {}) {
7
+ const url = new URL(API_BASE + path, window.location.origin);
8
+ Object.entries(params).forEach(([k, v]) => {
9
+ if (v !== null && v !== undefined && v !== "") url.searchParams.set(k, v);
10
+ });
11
+ return url.toString();
12
+ }
13
+
14
+ async function apiGet(path, params = {}) {
15
+ const res = await fetch(apiUrl(path, params));
16
+ if (!res.ok) {
17
+ const detalhe = await res.json().catch(() => ({}));
18
+ throw new Error(detalhe.detail || `Erro ${res.status} ao consultar a API`);
19
+ }
20
+ return res.json();
21
+ }
22
+
23
+ async function apiSend(method, path, body) {
24
+ const res = await fetch(API_BASE + path, {
25
+ method,
26
+ headers: { "Content-Type": "application/json" },
27
+ body: JSON.stringify(body),
28
+ });
29
+ if (!res.ok) {
30
+ const detalhe = await res.json().catch(() => ({}));
31
+ throw new Error(detalhe.detail ? JSON.stringify(detalhe.detail) : `Erro ${res.status}`);
32
+ }
33
+ return method === "DELETE" ? null : res.json();
34
+ }
35
+
36
+ function formatMoney(valor, tipoNegocio) {
37
+ const n = Number(valor) || 0;
38
+ const formatted = n.toLocaleString("pt-BR", { style: "currency", currency: "BRL", maximumFractionDigits: 0 });
39
+ if (tipoNegocio === "Locação") return `${formatted}<small> /mês</small>`;
40
+ return formatted;
41
+ }
42
+
43
+ function escapeHtml(str) {
44
+ const div = document.createElement("div");
45
+ div.textContent = str ?? "";
46
+ return div.innerHTML;
47
+ }
48
+
49
+ function statusClass(status) {
50
+ const map = {
51
+ "Disponível": "status-disponivel",
52
+ "Reservado": "status-reservado",
53
+ "Inativo": "status-inativo",
54
+ "Vendido": "status-vendido",
55
+ "Alugado": "status-alugado",
56
+ };
57
+ return map[status] || "status-disponivel";
58
+ }
59
+
60
+ function iconCama() {
61
+ return `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 18v-6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v6"/><path d="M2 18v2"/><path d="M22 18v2"/><path d="M4 10V7a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v3"/></svg>`;
62
+ }
63
+ function iconBanheiro() {
64
+ return `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 12h16v3a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4v-3Z"/><path d="M4 12V5a2 2 0 0 1 2-2c1.1 0 2 .9 2 2"/><path d="M8 19v2M16 19v2"/></svg>`;
65
+ }
66
+ function iconVaga() {
67
+ return `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="7" width="18" height="12" rx="2"/><path d="M7 7V5a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2"/></svg>`;
68
+ }
69
+ function iconArea() {
70
+ return `<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="1"/><path d="M9 3v4M15 3v4M9 21v-4M15 21v-4M3 9h4M3 15h4M21 9h-4M21 15h-4"/></svg>`;
71
+ }
72
+
73
+ function cardImovel(a) {
74
+ const specs = [];
75
+ if (a.quartos) specs.push(`<span>${iconCama()} ${a.quartos}</span>`);
76
+ if (a.banheiros) specs.push(`<span>${iconBanheiro()} ${a.banheiros}</span>`);
77
+ if (a.vagas_garagem) specs.push(`<span>${iconVaga()} ${a.vagas_garagem}</span>`);
78
+ const area = a.area_util || a.area_total;
79
+ if (area) specs.push(`<span>${iconArea()} ${area}m²</span>`);
80
+
81
+ return `
82
+ <a class="card" href="imovel.html?id=${a.id}">
83
+ <div class="card-media">
84
+ <span class="tag ${a.tipo_negocio === 'Venda' ? 'tag-venda' : 'tag-locacao'}">${a.tipo_negocio}</span>
85
+ ${a.destaque ? '<span class="tag-destaque">Destaque</span>' : ''}
86
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M3 21h18M5 21V9l7-6 7 6v12M9 21v-6h6v6"/></svg>
87
+ </div>
88
+ <div class="card-body">
89
+ <span class="status-pill ${statusClass(a.status)}">${a.status}</span>
90
+ <div class="card-price">${formatMoney(a.preco, a.tipo_negocio)}</div>
91
+ <h3 class="card-title">${escapeHtml(a.titulo)}</h3>
92
+ <div class="card-loc">📍 ${escapeHtml(a.bairro)}, ${escapeHtml(a.cidade)}</div>
93
+ <div class="card-specs">${specs.join("")}</div>
94
+ </div>
95
+ </a>`;
96
+ }
97
+
98
+ function skeletonCards(n = 6) {
99
+ return Array.from({ length: n }).map(() => `
100
+ <div class="card" style="opacity:.5">
101
+ <div class="card-media"></div>
102
+ <div class="card-body">
103
+ <div style="height:14px;background:#e5ded0;border-radius:4px;width:60%"></div>
104
+ <div style="height:18px;background:#e5ded0;border-radius:4px;width:90%;margin-top:8px"></div>
105
+ </div>
106
+ </div>`).join("");
107
+ }
108
+
109
+ function whatsappLink(mensagem) {
110
+ return `https://wa.me/${WHATSAPP_NUMERO}?text=${encodeURIComponent(mensagem)}`;
111
+ }
112
+
113
+ function toast(msg, isError = false) {
114
+ let el = document.querySelector(".toast");
115
+ if (!el) {
116
+ el = document.createElement("div");
117
+ el.className = "toast";
118
+ document.body.appendChild(el);
119
+ }
120
+ el.textContent = msg;
121
+ el.classList.toggle("error", isError);
122
+ el.classList.add("show");
123
+ clearTimeout(el._t);
124
+ el._t = setTimeout(() => el.classList.remove("show"), 3200);
125
+ }
static/js/busca.js ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Sahkey Imóveis — busca exploratória com filtros dinâmicos
2
+ Combina dois endpoints:
3
+ - /api/anuncios/filtros/opcoes -> popula negócio / cidade / bairro / quartos / faixas (com cascata)
4
+ - /api/anuncios/busca -> resultados paginados + facetas de tipo de imóvel e status
5
+ calculadas sobre o conjunto já filtrado
6
+ */
7
+
8
+ const LIMIT = 12;
9
+
10
+ const state = {
11
+ tipo_negocio: "", cidade: "", bairro: "", tipo_imovel: "", status: "",
12
+ preco_min: "", preco_max: "", quartos_min: "", destaque: false, busca: "",
13
+ ordenar_por: "mais_recentes", skip: 0,
14
+ };
15
+
16
+ const LABELS = {
17
+ tipo_negocio: "Negócio", cidade: "Cidade", bairro: "Bairro", tipo_imovel: "Tipo",
18
+ status: "Status", preco_min: "Preço mín.", preco_max: "Preço máx.",
19
+ quartos_min: "Quartos", destaque: "Destaque", busca: "Busca",
20
+ };
21
+
22
+ function lerFiltrosDaURL() {
23
+ const params = new URLSearchParams(window.location.search);
24
+ Object.keys(state).forEach((key) => {
25
+ if (params.has(key)) {
26
+ state[key] = key === "destaque" ? params.get(key) === "true" : params.get(key);
27
+ }
28
+ });
29
+ }
30
+
31
+ function atualizarURL() {
32
+ const params = new URLSearchParams();
33
+ Object.entries(state).forEach(([k, v]) => {
34
+ if (v !== "" && v !== false && v !== null && k !== "skip") params.set(k, v);
35
+ });
36
+ history.replaceState(null, "", `${window.location.pathname}?${params.toString()}`);
37
+ }
38
+
39
+ function filtrosAtuais() {
40
+ return {
41
+ tipo_negocio: state.tipo_negocio || undefined,
42
+ tipo_imovel: state.tipo_imovel || undefined,
43
+ status: state.status || undefined,
44
+ cidade: state.cidade || undefined,
45
+ bairro: state.bairro || undefined,
46
+ preco_min: state.preco_min || undefined,
47
+ preco_max: state.preco_max || undefined,
48
+ quartos_min: state.quartos_min || undefined,
49
+ destaque: state.destaque ? true : undefined,
50
+ busca: state.busca || undefined,
51
+ ordenar_por: state.ordenar_por,
52
+ skip: state.skip,
53
+ limit: LIMIT,
54
+ };
55
+ }
56
+
57
+ function renderFacetList(elId, itens, campo, { formatLabel } = {}) {
58
+ const el = document.getElementById(elId);
59
+ if (!itens || !itens.length) {
60
+ el.innerHTML = `<li class="muted" style="font-size:.8rem">Nenhuma opção disponível</li>`;
61
+ return;
62
+ }
63
+ el.innerHTML = itens.map((item) => {
64
+ const valor = item.valor;
65
+ const ativo = String(state[campo]) === String(valor);
66
+ const label = formatLabel ? formatLabel(valor) : valor;
67
+ return `<li class="facet-row ${ativo ? "active" : ""}" data-campo="${campo}" data-valor="${escapeHtml(valor)}">
68
+ <span>${escapeHtml(label)}</span><span class="count">${item.quantidade}</span>
69
+ </li>`;
70
+ }).join("");
71
+ }
72
+
73
+ async function carregarOpcoes() {
74
+ const opts = await apiGet("/filtros/opcoes", {
75
+ tipo_negocio: state.tipo_negocio || undefined,
76
+ cidade: state.cidade || undefined,
77
+ });
78
+
79
+ document.getElementById("filters-total").textContent = `${opts.total_anuncios} imóveis disponíveis na base`;
80
+
81
+ renderFacetList("facet-negocio", opts.tipos_negocio, "tipo_negocio");
82
+ renderFacetList("facet-cidade", opts.cidades, "cidade");
83
+ renderFacetList("facet-bairro", opts.bairros, "bairro");
84
+
85
+ // Faixa de preço: usa como placeholder quando o campo está vazio
86
+ const minInput = document.getElementById("f-preco-min");
87
+ const maxInput = document.getElementById("f-preco-max");
88
+ if (opts.faixa_preco) {
89
+ minInput.placeholder = `mín. R$ ${Math.round(opts.faixa_preco.min).toLocaleString("pt-BR")}`;
90
+ maxInput.placeholder = `máx. R$ ${Math.round(opts.faixa_preco.max).toLocaleString("pt-BR")}`;
91
+ }
92
+
93
+ // Quartos: lista de valores existentes, tratados como filtro "N ou mais"
94
+ const quartosEl = document.getElementById("facet-quartos");
95
+ if (opts.quartos_disponiveis && opts.quartos_disponiveis.length) {
96
+ quartosEl.innerHTML = opts.quartos_disponiveis.slice().reverse().map((q) => {
97
+ const ativo = String(state.quartos_min) === String(q);
98
+ return `<li class="facet-row ${ativo ? "active" : ""}" data-campo="quartos_min" data-valor="${q}">
99
+ <span>${q}+ quarto${q > 1 ? "s" : ""}</span><span class="count"></span>
100
+ </li>`;
101
+ }).join("");
102
+ } else {
103
+ quartosEl.innerHTML = "";
104
+ }
105
+ }
106
+
107
+ async function carregarResultados() {
108
+ const grid = document.getElementById("results-grid");
109
+ const resumo = document.getElementById("results-count");
110
+ grid.innerHTML = skeletonCards(LIMIT);
111
+ resumo.textContent = "Buscando…";
112
+
113
+ try {
114
+ const data = await apiGet("/busca", filtrosAtuais());
115
+
116
+ if (!data.resultados.length) {
117
+ grid.innerHTML = `<div class="empty-state" style="grid-column:1/-1">
118
+ <h3>Nenhum imóvel encontrado</h3>
119
+ <p>Tente ampliar a faixa de preço ou remover algum filtro.</p>
120
+ </div>`;
121
+ } else {
122
+ grid.innerHTML = data.resultados.map(cardImovel).join("");
123
+ }
124
+
125
+ const de = data.total === 0 ? 0 : data.skip + 1;
126
+ const ate = Math.min(data.skip + data.resultados.length, data.total);
127
+ resumo.innerHTML = `<b>${data.total}</b> imóve${data.total === 1 ? "l" : "is"} encontrados${data.total ? ` · exibindo ${de}–${ate}` : ""}`;
128
+
129
+ renderFacetList("facet-tipo", data.facetas.tipos_imovel, "tipo_imovel");
130
+ renderFacetList("facet-status", data.facetas.status, "status");
131
+
132
+ renderPaginacao(data.total, data.skip, LIMIT);
133
+ } catch (err) {
134
+ grid.innerHTML = `<div class="empty-state" style="grid-column:1/-1">
135
+ <h3>Não foi possível carregar os resultados</h3>
136
+ <p>${escapeHtml(err.message)}</p>
137
+ </div>`;
138
+ resumo.textContent = "";
139
+ }
140
+
141
+ renderChips();
142
+ }
143
+
144
+ function renderPaginacao(total, skip, limit) {
145
+ const el = document.getElementById("pagination");
146
+ const totalPaginas = Math.ceil(total / limit);
147
+ const paginaAtual = Math.floor(skip / limit) + 1;
148
+ if (totalPaginas <= 1) { el.innerHTML = ""; return; }
149
+
150
+ let html = `<button ${paginaAtual === 1 ? "disabled" : ""} data-skip="${(paginaAtual - 2) * limit}">‹ Anterior</button>`;
151
+ const janela = 2;
152
+ for (let p = 1; p <= totalPaginas; p++) {
153
+ if (p === 1 || p === totalPaginas || Math.abs(p - paginaAtual) <= janela) {
154
+ html += `<button class="${p === paginaAtual ? "active" : ""}" data-skip="${(p - 1) * limit}">${p}</button>`;
155
+ } else if (Math.abs(p - paginaAtual) === janela + 1) {
156
+ html += `<span class="muted">…</span>`;
157
+ }
158
+ }
159
+ html += `<button ${paginaAtual === totalPaginas ? "disabled" : ""} data-skip="${paginaAtual * limit}">Próxima ›</button>`;
160
+ el.innerHTML = html;
161
+
162
+ el.querySelectorAll("button[data-skip]").forEach((btn) => {
163
+ btn.addEventListener("click", () => {
164
+ state.skip = Number(btn.dataset.skip);
165
+ atualizarURL();
166
+ carregarResultados();
167
+ document.querySelector(".search-layout").scrollIntoView({ behavior: "smooth" });
168
+ });
169
+ });
170
+ }
171
+
172
+ function renderChips() {
173
+ const el = document.getElementById("chips-ativos");
174
+ const ativos = Object.entries(state).filter(([k, v]) => v !== "" && v !== false && k !== "skip" && k !== "ordenar_por");
175
+ if (!ativos.length) { el.innerHTML = ""; return; }
176
+ el.innerHTML = ativos.map(([k, v]) => `
177
+ <span class="chip">${LABELS[k] || k}: ${escapeHtml(String(v))}
178
+ <button data-campo="${k}" aria-label="Remover filtro">✕</button>
179
+ </span>`).join("");
180
+
181
+ el.querySelectorAll("button[data-campo]").forEach((btn) => {
182
+ btn.addEventListener("click", () => {
183
+ aplicarFiltro(btn.dataset.campo, btn.dataset.campo === "destaque" ? false : "");
184
+ });
185
+ });
186
+ }
187
+
188
+ function aplicarFiltro(campo, valor) {
189
+ // Selecionar a mesma opção novamente remove o filtro (toggle)
190
+ state[campo] = String(state[campo]) === String(valor) ? "" : valor;
191
+ if (campo === "cidade") state.bairro = ""; // cascata: trocar cidade limpa o bairro
192
+ if (campo === "tipo_negocio") { /* preço costuma mudar de escala entre venda/locação */ }
193
+ state.skip = 0;
194
+ atualizarURL();
195
+ sincronizarCamposComEstado();
196
+ carregarOpcoes();
197
+ carregarResultados();
198
+ }
199
+
200
+ function sincronizarCamposComEstado() {
201
+ document.getElementById("f-busca").value = state.busca || "";
202
+ document.getElementById("f-preco-min").value = state.preco_min || "";
203
+ document.getElementById("f-preco-max").value = state.preco_max || "";
204
+ document.getElementById("f-destaque").checked = !!state.destaque;
205
+ document.getElementById("f-ordenar").value = state.ordenar_por;
206
+ }
207
+
208
+ function ligarEventos() {
209
+ document.getElementById("filters-panel").addEventListener("click", (e) => {
210
+ const row = e.target.closest(".facet-row");
211
+ if (row) aplicarFiltro(row.dataset.campo, row.dataset.valor);
212
+ });
213
+
214
+ let debounce;
215
+ document.getElementById("f-busca").addEventListener("input", (e) => {
216
+ clearTimeout(debounce);
217
+ debounce = setTimeout(() => {
218
+ state.busca = e.target.value;
219
+ state.skip = 0;
220
+ atualizarURL();
221
+ carregarResultados();
222
+ }, 400);
223
+ });
224
+
225
+ ["f-preco-min", "f-preco-max"].forEach((id) => {
226
+ document.getElementById(id).addEventListener("change", (e) => {
227
+ state[id === "f-preco-min" ? "preco_min" : "preco_max"] = e.target.value;
228
+ state.skip = 0;
229
+ atualizarURL();
230
+ carregarOpcoes();
231
+ carregarResultados();
232
+ });
233
+ });
234
+
235
+ document.getElementById("f-destaque").addEventListener("change", (e) => {
236
+ state.destaque = e.target.checked;
237
+ state.skip = 0;
238
+ atualizarURL();
239
+ carregarResultados();
240
+ });
241
+
242
+ document.getElementById("f-ordenar").addEventListener("change", (e) => {
243
+ state.ordenar_por = e.target.value;
244
+ state.skip = 0;
245
+ atualizarURL();
246
+ carregarResultados();
247
+ });
248
+
249
+ document.getElementById("btn-limpar").addEventListener("click", () => {
250
+ Object.assign(state, {
251
+ tipo_negocio: "", cidade: "", bairro: "", tipo_imovel: "", status: "",
252
+ preco_min: "", preco_max: "", quartos_min: "", destaque: false, busca: "",
253
+ skip: 0,
254
+ });
255
+ atualizarURL();
256
+ sincronizarCamposComEstado();
257
+ carregarOpcoes();
258
+ carregarResultados();
259
+ });
260
+ }
261
+
262
+ document.addEventListener("DOMContentLoaded", async () => {
263
+ lerFiltrosDaURL();
264
+ sincronizarCamposComEstado();
265
+ ligarEventos();
266
+ await Promise.all([carregarOpcoes(), carregarResultados()]);
267
+ });
static/js/home.js ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Sahkey Imóveis — página inicial: destaques e estatísticas gerais */
2
+
3
+ async function carregarDestaques() {
4
+ const el = document.getElementById("destaques-carousel");
5
+ try {
6
+ const destaques = await apiGet("/destaques", { limite: 8 });
7
+ if (!destaques.length) {
8
+ el.innerHTML = `<p class="empty-state">Nenhum imóvel em destaque no momento.</p>`;
9
+ return;
10
+ }
11
+ el.innerHTML = destaques.map(cardImovel).join("");
12
+ } catch (err) {
13
+ el.innerHTML = `<p class="empty-state">Não foi possível carregar os destaques agora. (${escapeHtml(err.message)})</p>`;
14
+ }
15
+ }
16
+
17
+ async function carregarStats() {
18
+ try {
19
+ const stats = await apiGet("/stats/resumo");
20
+ document.getElementById("stat-total").textContent = stats.total_anuncios;
21
+ document.getElementById("stat-venda").textContent = stats.total_venda;
22
+ document.getElementById("stat-locacao").textContent = stats.total_locacao;
23
+ } catch (err) {
24
+ // silencioso — a tira de estatísticas simplesmente mantém "—"
25
+ console.warn("stats indisponíveis", err);
26
+ }
27
+ }
28
+
29
+ document.addEventListener("DOMContentLoaded", () => {
30
+ carregarDestaques();
31
+ carregarStats();
32
+ });
static/js/imovel.js ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Sahkey Imóveis — página de detalhe de um imóvel */
2
+
3
+ function getId() {
4
+ return new URLSearchParams(window.location.search).get("id");
5
+ }
6
+
7
+ function specRow(label, valor) {
8
+ if (!valor) return "";
9
+ return `<tr><td>${label}</td><td>${valor}</td></tr>`;
10
+ }
11
+
12
+ function iniciais(nome) {
13
+ return (nome || "SK").split(" ").map((p) => p[0]).slice(0, 2).join("").toUpperCase();
14
+ }
15
+
16
+ async function carregarImovel() {
17
+ const id = getId();
18
+ const container = document.getElementById("imovel-container");
19
+ if (!id) {
20
+ container.innerHTML = `<div class="empty-state"><h3>Imóvel não informado</h3><p><a href="busca.html">Voltar para a busca</a></p></div>`;
21
+ return;
22
+ }
23
+
24
+ try {
25
+ const a = await apiGet(`/${id}`);
26
+ document.getElementById("page-title").textContent = `${a.titulo} — Sahkey Imóveis`;
27
+
28
+ const area = a.area_util || a.area_total;
29
+ const mensagemWhats = `Olá! Tenho interesse no imóvel "${a.titulo}" (código #${a.id}), em ${a.bairro}, ${a.cidade}. Podem me passar mais informações?`;
30
+
31
+ container.innerHTML = `
32
+ <p class="breadcrumb"><a href="index.html">Início</a> / <a href="busca.html">Imóveis</a> / ${escapeHtml(a.cidade)} / <span>#${a.id}</span></p>
33
+
34
+ <div class="property-hero">
35
+ <span class="tag ${a.tipo_negocio === 'Venda' ? 'tag-venda' : 'tag-locacao'}" style="position:static;margin-right:8px">${a.tipo_negocio}</span>
36
+ <div>
37
+ <h1 style="color:#fff;margin-bottom:6px">${escapeHtml(a.titulo)}</h1>
38
+ <span class="badge-mono" style="color:rgba(255,255,255,.85)">📍 ${escapeHtml(a.endereco)}, ${escapeHtml(a.bairro)} — ${escapeHtml(a.cidade)}/${escapeHtml(a.estado)}</span>
39
+ </div>
40
+ </div>
41
+
42
+ <div class="property-detail-grid">
43
+ <div>
44
+ <span class="status-pill ${statusClass(a.status)}" style="margin-top:20px;display:inline-block">${a.status}</span>
45
+ <h2 style="margin-top:16px">Sobre o imóvel</h2>
46
+ <p>${escapeHtml(a.descricao) || "Descrição não informada pelo corretor responsável."}</p>
47
+
48
+ <h2>Características</h2>
49
+ <table class="specs-table">
50
+ ${specRow("Tipo", a.tipo_imovel)}
51
+ ${specRow("Área útil", area ? `${a.area_util} m²` : "")}
52
+ ${specRow("Área total", a.area_total ? `${a.area_total} m²` : "")}
53
+ ${specRow("Quartos", a.quartos)}
54
+ ${specRow("Suítes", a.suites)}
55
+ ${specRow("Banheiros", a.banheiros)}
56
+ ${specRow("Vagas de garagem", a.vagas_garagem)}
57
+ ${specRow("Condomínio", a.condominio ? `R$ ${Number(a.condominio).toLocaleString("pt-BR")}/mês` : "")}
58
+ ${specRow("IPTU", a.iptu ? `R$ ${Number(a.iptu).toLocaleString("pt-BR")}/ano` : "")}
59
+ ${specRow("CEP", a.cep)}
60
+ ${specRow("Código do anúncio", `#${a.id}`)}
61
+ </table>
62
+ </div>
63
+
64
+ <aside class="contact-card">
65
+ <div class="price">${formatMoney(a.preco, a.tipo_negocio)}</div>
66
+ <p class="form-note">${a.tipo_negocio === "Locação" ? "Valor mensal, sem condomínio e IPTU" : "Valor de venda à vista, sujeito a condições de financiamento"}</p>
67
+
68
+ <div class="broker">
69
+ <div class="avatar">${iniciais(a.corretor_responsavel)}</div>
70
+ <div>
71
+ <strong>${escapeHtml(a.corretor_responsavel || "Equipe Sahkey")}</strong><br>
72
+ <span class="muted" style="font-size:.82rem">Corretor(a) responsável</span>
73
+ </div>
74
+ </div>
75
+
76
+ <a class="btn btn-primary btn-block" target="_blank" rel="noopener" href="${whatsappLink(mensagemWhats)}">Conversar no WhatsApp</a>
77
+ <a class="btn btn-outline btn-block" style="margin-top:10px" href="tel:${(a.telefone_contato || '').replace(/\D/g, '')}">Ligar: ${escapeHtml(a.telefone_contato || "—")}</a>
78
+ </aside>
79
+ </div>
80
+ `;
81
+
82
+ carregarSimilares(id);
83
+ } catch (err) {
84
+ container.innerHTML = `<div class="empty-state"><h3>Imóvel não encontrado</h3><p>${escapeHtml(err.message)}</p><p><a href="busca.html">Voltar para a busca</a></p></div>`;
85
+ }
86
+ }
87
+
88
+ async function carregarSimilares(id) {
89
+ try {
90
+ const similares = await apiGet(`/${id}/similares`, { limite: 4 });
91
+ if (!similares.length) return;
92
+ document.getElementById("similares-section").style.display = "";
93
+ document.getElementById("similares-carousel").innerHTML = similares.map(cardImovel).join("");
94
+ } catch (err) {
95
+ console.warn("similares indisponíveis", err);
96
+ }
97
+ }
98
+
99
+ document.addEventListener("DOMContentLoaded", carregarImovel);
static/js/main.js ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Sahkey Imóveis — comportamentos globais de todas as páginas */
2
+
3
+ document.addEventListener("DOMContentLoaded", () => {
4
+ const toggle = document.querySelector(".nav-toggle");
5
+ const nav = document.querySelector(".nav");
6
+ if (toggle && nav) {
7
+ toggle.addEventListener("click", () => nav.classList.toggle("open"));
8
+ }
9
+
10
+ // Marca o link ativo do menu conforme a página atual
11
+ const current = window.location.pathname.split("/").pop() || "index.html";
12
+ document.querySelectorAll(".nav-links a").forEach((a) => {
13
+ const href = a.getAttribute("href");
14
+ if (href === current || (current === "" && href === "index.html")) {
15
+ a.classList.add("active");
16
+ }
17
+ });
18
+
19
+ document.querySelectorAll("[data-year]").forEach((el) => {
20
+ el.textContent = new Date().getFullYear();
21
+ });
22
+ });