/* Sahkey Imóveis — camada de acesso à API e helpers de formatação */
const API_BASE = "/api/anuncios";
const WHATSAPP_NUMERO = "5541998112201"; // Sahkey — atendimento central (demo)
function apiUrl(path, params = {}) {
const url = new URL(API_BASE + path, window.location.origin);
Object.entries(params).forEach(([k, v]) => {
if (v !== null && v !== undefined && v !== "") url.searchParams.set(k, v);
});
return url.toString();
}
async function apiGet(path, params = {}) {
const res = await fetch(apiUrl(path, params));
if (!res.ok) {
const detalhe = await res.json().catch(() => ({}));
throw new Error(detalhe.detail || `Erro ${res.status} ao consultar a API`);
}
return res.json();
}
async function apiSend(method, path, body) {
const res = await fetch(API_BASE + path, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const detalhe = await res.json().catch(() => ({}));
throw new Error(detalhe.detail ? JSON.stringify(detalhe.detail) : `Erro ${res.status}`);
}
return method === "DELETE" ? null : res.json();
}
function formatMoney(valor, tipoNegocio) {
const n = Number(valor) || 0;
const formatted = n.toLocaleString("pt-BR", { style: "currency", currency: "BRL", maximumFractionDigits: 0 });
if (tipoNegocio === "Locação") return `${formatted} /mês`;
return formatted;
}
function escapeHtml(str) {
const div = document.createElement("div");
div.textContent = str ?? "";
return div.innerHTML;
}
function statusClass(status) {
const map = {
"Disponível": "status-disponivel",
"Reservado": "status-reservado",
"Inativo": "status-inativo",
"Vendido": "status-vendido",
"Alugado": "status-alugado",
};
return map[status] || "status-disponivel";
}
function iconCama() {
return ``;
}
function iconBanheiro() {
return ``;
}
function iconVaga() {
return ``;
}
function iconArea() {
return ``;
}
function cardImovel(a) {
const specs = [];
if (a.quartos) specs.push(`${iconCama()} ${a.quartos}`);
if (a.banheiros) specs.push(`${iconBanheiro()} ${a.banheiros}`);
if (a.vagas_garagem) specs.push(`${iconVaga()} ${a.vagas_garagem}`);
const area = a.area_util || a.area_total;
if (area) specs.push(`${iconArea()} ${area}m²`);
return `
${escapeHtml(a.titulo)}