@garagem-ai/site-sdk 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.js ADDED
@@ -0,0 +1,2070 @@
1
+ "use strict";
2
+ "use client";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/react/index.ts
32
+ var react_exports = {};
33
+ __export(react_exports, {
34
+ FilterPanel: () => FilterPanel,
35
+ ListingCard: () => ListingCard,
36
+ ResultsSkeleton: () => ResultsSkeleton,
37
+ SearchPage: () => SearchPage,
38
+ SearchPagination: () => SearchPagination,
39
+ SearchQueryForm: () => SearchQueryForm,
40
+ SearchSortSelect: () => SearchSortSelect,
41
+ rangeDraftFromPath: () => rangeDraftFromPath,
42
+ usePublicSearch: () => usePublicSearch
43
+ });
44
+ module.exports = __toCommonJS(react_exports);
45
+
46
+ // src/react/listing-card.tsx
47
+ var import_link = __toESM(require("next/link"));
48
+
49
+ // src/presentation.ts
50
+ var SEARCH_CSS_VARS = {
51
+ cardRadius: "--garagem-listing-card-radius",
52
+ cardGap: "--garagem-listing-card-gap",
53
+ priceSize: "--garagem-listing-price-size",
54
+ mediaRatio: "--garagem-listing-media-ratio"
55
+ };
56
+ var SEARCH_CSS_RECIPE = `:root {
57
+ ${SEARCH_CSS_VARS.cardRadius}: 0.75rem;
58
+ ${SEARCH_CSS_VARS.cardGap}: 1.5rem;
59
+ ${SEARCH_CSS_VARS.priceSize}: 1.125rem;
60
+ ${SEARCH_CSS_VARS.mediaRatio}: 4 / 3;
61
+ }
62
+ `;
63
+ function formatListingPrice(amount, locale = "pt-BR", currency = "BRL") {
64
+ if (amount == null) return "Sob consulta";
65
+ try {
66
+ return new Intl.NumberFormat(locale, {
67
+ style: "currency",
68
+ currency,
69
+ minimumFractionDigits: 0,
70
+ maximumFractionDigits: 0
71
+ }).format(amount);
72
+ } catch {
73
+ return `${currency} ${amount}`;
74
+ }
75
+ }
76
+ function formatGroupedInteger(value, locale = "pt-BR") {
77
+ const digits = String(value ?? "").replace(/\D/g, "");
78
+ if (!digits) return "";
79
+ const amount = Number.parseInt(digits, 10);
80
+ if (!Number.isFinite(amount)) return "";
81
+ return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(
82
+ amount
83
+ );
84
+ }
85
+ function parseGroupedInteger(value) {
86
+ if (typeof value === "number") {
87
+ return Number.isFinite(value) ? Math.trunc(value) : void 0;
88
+ }
89
+ const digits = String(value ?? "").replace(/\D/g, "");
90
+ if (!digits) return void 0;
91
+ const amount = Number.parseInt(digits, 10);
92
+ return Number.isFinite(amount) ? amount : void 0;
93
+ }
94
+ function formatAreaM2(area) {
95
+ if (area == null || !Number.isFinite(area)) return null;
96
+ return `${area} m\xB2`;
97
+ }
98
+ function listingBusinessLabel(businessType) {
99
+ return businessType === "rental" ? "Aluguel" : "Venda";
100
+ }
101
+
102
+ // src/listing-path.ts
103
+ function listingPublicPath(listing) {
104
+ const composed = listing.path?.trim() ?? "";
105
+ if (composed.startsWith("/") && !composed.startsWith("//")) return composed;
106
+ const identity = listing.listingCode?.trim() || listing.id?.trim() || "";
107
+ if (!identity || identity === "undefined" || identity === "null") {
108
+ throw new TypeError("listingPublicPath: listing has no listingCode or id");
109
+ }
110
+ return `/imoveis/id-${identity}`;
111
+ }
112
+
113
+ // src/listing-card-model.ts
114
+ function listingLocationLabel(location) {
115
+ return [location.neighborhood, location.city, location.state].map((part) => part ? String(part).trim() : "").filter(Boolean).join(", ");
116
+ }
117
+ function toListingCardModel(listing) {
118
+ const isPrivate = listing.priceVisibility === "private";
119
+ const area = listing.property?.usableArea ?? listing.property?.totalArea;
120
+ return {
121
+ href: listingPublicPath(listing),
122
+ title: listing.title,
123
+ businessType: listing.businessType,
124
+ businessLabel: listingBusinessLabel(listing.businessType),
125
+ priceVisibility: listing.priceVisibility,
126
+ price: listing.price,
127
+ priceLabel: isPrivate ? "Sob consulta" : formatListingPrice(listing.price),
128
+ pricePeriod: listing.businessType === "rental" && !isPrivate && listing.price != null ? "/m\xEAs" : null,
129
+ locationLabel: listingLocationLabel(listing.location || {}),
130
+ propertyType: listing.property?.type ?? null,
131
+ coverSrc: listing.coverImage?.src ?? null,
132
+ coverAlt: listing.coverImage?.alt ?? listing.title,
133
+ bedrooms: listing.property?.bedrooms ?? null,
134
+ bathrooms: listing.property?.bathrooms ?? null,
135
+ parkingSpaces: listing.property?.parkingSpaces ?? null,
136
+ areaM2: area ?? null
137
+ };
138
+ }
139
+
140
+ // src/react/cn.ts
141
+ function cn(...parts) {
142
+ return parts.filter(Boolean).join(" ");
143
+ }
144
+
145
+ // src/react/listing-card.tsx
146
+ var import_jsx_runtime = require("react/jsx-runtime");
147
+ function isListing(value) {
148
+ return "priceVisibility" in value && "businessType" in value && "title" in value;
149
+ }
150
+ function ListingCard({
151
+ listing,
152
+ href,
153
+ className,
154
+ classNames,
155
+ slots,
156
+ style
157
+ }) {
158
+ const model = isListing(listing) ? toListingCardModel(listing) : listing;
159
+ const target = href ?? model.href;
160
+ const areaLabel = formatAreaM2(model.areaM2);
161
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
162
+ "article",
163
+ {
164
+ "data-slot": "listing-card",
165
+ className: cn(
166
+ "group overflow-hidden rounded-[var(--garagem-listing-card-radius,0.75rem)] border border-border bg-background",
167
+ className,
168
+ classNames?.root
169
+ ),
170
+ style,
171
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
172
+ import_link.default,
173
+ {
174
+ href: target,
175
+ className: "block cursor-pointer",
176
+ "data-slot": "listing-card-link",
177
+ children: [
178
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
179
+ "div",
180
+ {
181
+ "data-slot": "listing-card-media",
182
+ className: cn(
183
+ "relative w-full overflow-hidden bg-muted",
184
+ classNames?.media
185
+ ),
186
+ style: { aspectRatio: "var(--garagem-listing-media-ratio, 4 / 3)" },
187
+ children: [
188
+ slots?.media ?? (model.coverSrc ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
189
+ "img",
190
+ {
191
+ src: model.coverSrc,
192
+ alt: model.coverAlt,
193
+ className: "h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
194
+ }
195
+ ) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex h-full w-full items-center justify-center text-xs text-muted-foreground", children: "Sem foto" })),
196
+ slots?.badge ?? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
197
+ "span",
198
+ {
199
+ "data-slot": "listing-card-badge",
200
+ className: cn(
201
+ "absolute left-3 top-3 rounded-full bg-background/90 px-2 py-1 text-xs font-medium",
202
+ classNames?.badge
203
+ ),
204
+ children: model.businessLabel
205
+ }
206
+ )
207
+ ]
208
+ }
209
+ ),
210
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
211
+ "div",
212
+ {
213
+ "data-slot": "listing-card-body",
214
+ className: cn("p-4", classNames?.body),
215
+ children: [
216
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex items-baseline justify-between gap-2", children: [
217
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
218
+ "p",
219
+ {
220
+ "data-slot": "listing-card-price",
221
+ className: cn("font-semibold tracking-tight", classNames?.price),
222
+ style: {
223
+ fontSize: "var(--garagem-listing-price-size, 1.125rem)"
224
+ },
225
+ children: model.priceLabel
226
+ }
227
+ ),
228
+ model.pricePeriod ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "text-xs text-muted-foreground", children: model.pricePeriod }) : null
229
+ ] }),
230
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
231
+ "h3",
232
+ {
233
+ "data-slot": "listing-card-title",
234
+ className: cn(
235
+ "mt-1 line-clamp-1 text-sm font-medium",
236
+ classNames?.title
237
+ ),
238
+ children: model.title
239
+ }
240
+ ),
241
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
242
+ "p",
243
+ {
244
+ "data-slot": "listing-card-location",
245
+ className: cn(
246
+ "mt-0.5 line-clamp-1 text-xs text-muted-foreground",
247
+ classNames?.location
248
+ ),
249
+ children: model.locationLabel || model.propertyType || ""
250
+ }
251
+ ),
252
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
253
+ "ul",
254
+ {
255
+ "data-slot": "listing-card-features",
256
+ className: cn(
257
+ "mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground",
258
+ classNames?.features
259
+ ),
260
+ children: [
261
+ model.bedrooms != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { children: [
262
+ model.bedrooms,
263
+ " quartos"
264
+ ] }) : null,
265
+ model.bathrooms != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { children: [
266
+ model.bathrooms,
267
+ " banheiros"
268
+ ] }) : null,
269
+ model.parkingSpaces != null ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { children: [
270
+ model.parkingSpaces,
271
+ " vagas"
272
+ ] }) : null,
273
+ areaLabel ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: areaLabel }) : null
274
+ ]
275
+ }
276
+ ),
277
+ slots?.cta ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
278
+ "div",
279
+ {
280
+ "data-slot": "listing-card-cta",
281
+ className: cn("mt-3", classNames?.cta),
282
+ children: slots.cta
283
+ }
284
+ ) : null
285
+ ]
286
+ }
287
+ )
288
+ ]
289
+ }
290
+ )
291
+ }
292
+ );
293
+ }
294
+
295
+ // src/react/search-page.tsx
296
+ var import_react2 = require("react");
297
+
298
+ // ../search-url/types.ts
299
+ var SEARCH_BASE_ROUTE = "imoveis";
300
+ var MAX_PAGE = 1e4;
301
+ var MAX_LOC_GROUPS = 20;
302
+ var DEFAULT_MIN_PRICE = 0;
303
+ var DEFAULT_MAX_PRICE = 1e9;
304
+ var DEFAULT_MIN_AREA = 0;
305
+ var DEFAULT_MAX_AREA = 1e5;
306
+ var SORT_URL_TOKENS = [
307
+ "preco-asc",
308
+ "preco-desc",
309
+ "area-asc",
310
+ "area-desc"
311
+ ];
312
+
313
+ // ../search-url/slugify.ts
314
+ function slugifyForUrl(text) {
315
+ if (!text) return "";
316
+ const withDashes = text.replace(/([a-z])([A-Z])/g, "$1-$2");
317
+ return withDashes.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\w\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").trim();
318
+ }
319
+
320
+ // ../search-url/catalog.ts
321
+ var PROPERTY_TYPE_SLUG_ALIASES = {
322
+ rural: ["chacara", "fazenda", "sitio"]
323
+ };
324
+ function buildListingTypeOptions(enabled) {
325
+ const flags = enabled ?? { sale: true, rental: true };
326
+ const out = [];
327
+ if (flags.sale !== false) {
328
+ out.push({ id: "sale", slug: "venda", label: "Venda" });
329
+ }
330
+ if (flags.rental !== false) {
331
+ out.push({ id: "rental", slug: "aluguel", label: "Aluguel" });
332
+ }
333
+ return out;
334
+ }
335
+ function emptySearchUrlDictionary() {
336
+ return {
337
+ listingTypes: buildListingTypeOptions(null),
338
+ propertyTypes: [],
339
+ propertyFeatures: [],
340
+ buildingAmenities: []
341
+ };
342
+ }
343
+ function norm(value) {
344
+ return slugifyForUrl(value) || value.toLowerCase();
345
+ }
346
+ function matchOptionId(segment, options, extraAliases) {
347
+ const n = norm(segment);
348
+ for (const option of options) {
349
+ const aliases = extraAliases?.[option.id] ?? [];
350
+ const candidates = [option.id, option.slug, option.label, ...aliases];
351
+ if (candidates.some((c) => norm(c) === n)) return option.id;
352
+ }
353
+ return null;
354
+ }
355
+ function optionSlugById(id, options) {
356
+ const option = options.find((item) => item.id === id);
357
+ return option?.slug ?? null;
358
+ }
359
+ var LISTING_TYPE_ALIASES = {
360
+ sale: ["comprar"],
361
+ rental: ["alugar"]
362
+ };
363
+
364
+ // ../search-url/path.ts
365
+ function toArray(value) {
366
+ if (value === void 0) return [];
367
+ return Array.isArray(value) ? value : [value];
368
+ }
369
+ function formatNumeric(value) {
370
+ return Array.isArray(value) ? value.join("-") : String(value);
371
+ }
372
+ function formatRange(min, max, unit) {
373
+ return `de-${min}-a-${max}-${unit}`;
374
+ }
375
+ function formatSuiteSuffix(value) {
376
+ const values = Array.isArray(value) ? value : [value];
377
+ const firstValue = values[0] ?? 0;
378
+ return firstValue === 0 || firstValue === 1 ? "suite" : "suites";
379
+ }
380
+ function composeSearchPublicPath(filters, dictionary = emptySearchUrlDictionary()) {
381
+ const segments = [];
382
+ const listingType = filters.listingType;
383
+ if (listingType) {
384
+ segments.push(
385
+ optionSlugById(listingType, dictionary.listingTypes) || slugifyForUrl(listingType)
386
+ );
387
+ }
388
+ for (const propertyType of toArray(filters.propertyType)) {
389
+ segments.push(
390
+ optionSlugById(propertyType, dictionary.propertyTypes) || slugifyForUrl(propertyType)
391
+ );
392
+ }
393
+ const location = filters.location;
394
+ if (location) {
395
+ if (location.state) segments.push(slugifyForUrl(location.state));
396
+ if (location.city) segments.push(slugifyForUrl(location.city));
397
+ if (location.neighborhood)
398
+ segments.push(slugifyForUrl(location.neighborhood));
399
+ if (location.street) segments.push(slugifyForUrl(location.street));
400
+ }
401
+ if (filters.bedrooms !== void 0) {
402
+ segments.push(`${formatNumeric(filters.bedrooms)}-quartos`);
403
+ }
404
+ if (filters.bathrooms !== void 0) {
405
+ segments.push(`${formatNumeric(filters.bathrooms)}-banheiros`);
406
+ }
407
+ if (filters.suites !== void 0) {
408
+ const suffix = formatSuiteSuffix(filters.suites);
409
+ segments.push(`${formatNumeric(filters.suites)}-${suffix}`);
410
+ }
411
+ if (filters.parkingSpots !== void 0) {
412
+ segments.push(`${formatNumeric(filters.parkingSpots)}-vagas`);
413
+ }
414
+ if (filters.price && (filters.price.min !== void 0 || filters.price.max !== void 0)) {
415
+ const min = filters.price.min ?? DEFAULT_MIN_PRICE;
416
+ const max = filters.price.max ?? DEFAULT_MAX_PRICE;
417
+ segments.push(formatRange(min, max, "reais"));
418
+ }
419
+ if (filters.area && (filters.area.min !== void 0 || filters.area.max !== void 0)) {
420
+ const min = filters.area.min ?? DEFAULT_MIN_AREA;
421
+ const max = filters.area.max ?? DEFAULT_MAX_AREA;
422
+ segments.push(formatRange(min, max, "m2"));
423
+ }
424
+ const seenAmenities = /* @__PURE__ */ new Set();
425
+ for (const id of filters.propertyFeatures ?? []) {
426
+ const slug = optionSlugById(id, dictionary.propertyFeatures) || slugifyForUrl(id);
427
+ if (!slug || seenAmenities.has(slug)) continue;
428
+ seenAmenities.add(slug);
429
+ segments.push(slug);
430
+ }
431
+ for (const id of filters.buildingAmenities ?? []) {
432
+ const slug = optionSlugById(id, dictionary.buildingAmenities) || slugifyForUrl(id);
433
+ if (!slug || seenAmenities.has(slug)) continue;
434
+ seenAmenities.add(slug);
435
+ segments.push(slug);
436
+ }
437
+ const path = segments.filter(Boolean).join("/");
438
+ return path ? `/${SEARCH_BASE_ROUTE}/${path}` : `/${SEARCH_BASE_ROUTE}`;
439
+ }
440
+ var BEDROOMS = /^(\d+(?:-\d+)*)-quartos?$/;
441
+ var BATHROOMS = /^(\d+(?:-\d+)*)-banheiros?$/;
442
+ var SUITES = /^(\d+(?:-\d+)*)-suites?$/;
443
+ var PARKING = /^(\d+(?:-\d+)*)-vagas?$/;
444
+ var PRICE = /^de-(\d+)-a-(\d+)-(reais|real)$/;
445
+ var AREA = /^de-(\d+)-a-(\d+)-(m2|m²)$/;
446
+ function parseNumericList(raw) {
447
+ return raw.split("-").map((part) => Number(part)).filter((n) => Number.isFinite(n));
448
+ }
449
+ function collapse(values) {
450
+ return values.length === 1 ? values[0] : values;
451
+ }
452
+ function parseSearchPublicPath(pathname, dictionary = emptySearchUrlDictionary()) {
453
+ const raw = pathname.split(/[?#]/)[0] ?? "";
454
+ let segments = raw.replace(/^\//, "").split("/").filter(Boolean);
455
+ if (segments[0] === SEARCH_BASE_ROUTE) segments = segments.slice(1);
456
+ if (segments.some((segment) => segment.includes("."))) return null;
457
+ if (segments.some((segment) => segment.toLowerCase().startsWith("id-"))) {
458
+ return null;
459
+ }
460
+ const filters = {};
461
+ const locationParts = [];
462
+ const propertyTypes = [];
463
+ const propertyFeatures = [];
464
+ const buildingAmenities = [];
465
+ for (const segment of segments) {
466
+ const lower = segment.toLowerCase();
467
+ const listingType = matchOptionId(
468
+ segment,
469
+ dictionary.listingTypes,
470
+ LISTING_TYPE_ALIASES
471
+ );
472
+ if (listingType && !filters.listingType) {
473
+ filters.listingType = listingType;
474
+ continue;
475
+ }
476
+ const propertyType = matchOptionId(
477
+ segment,
478
+ dictionary.propertyTypes,
479
+ PROPERTY_TYPE_SLUG_ALIASES
480
+ );
481
+ if (propertyType) {
482
+ propertyTypes.push(propertyType);
483
+ continue;
484
+ }
485
+ const bedrooms = lower.match(BEDROOMS);
486
+ if (bedrooms) {
487
+ filters.bedrooms = collapse(parseNumericList(bedrooms[1]));
488
+ continue;
489
+ }
490
+ const bathrooms = lower.match(BATHROOMS);
491
+ if (bathrooms) {
492
+ filters.bathrooms = collapse(parseNumericList(bathrooms[1]));
493
+ continue;
494
+ }
495
+ const suites = lower.match(SUITES);
496
+ if (suites) {
497
+ filters.suites = collapse(parseNumericList(suites[1]));
498
+ continue;
499
+ }
500
+ const parking = lower.match(PARKING);
501
+ if (parking) {
502
+ filters.parkingSpots = collapse(parseNumericList(parking[1]));
503
+ continue;
504
+ }
505
+ const price = lower.match(PRICE);
506
+ if (price) {
507
+ filters.price = { min: Number(price[1]), max: Number(price[2]) };
508
+ continue;
509
+ }
510
+ const area = lower.match(AREA);
511
+ if (area) {
512
+ filters.area = { min: Number(area[1]), max: Number(area[2]) };
513
+ continue;
514
+ }
515
+ const featureId = matchOptionId(segment, dictionary.propertyFeatures);
516
+ if (featureId) {
517
+ propertyFeatures.push(featureId);
518
+ continue;
519
+ }
520
+ const amenityId = matchOptionId(segment, dictionary.buildingAmenities);
521
+ if (amenityId) {
522
+ buildingAmenities.push(amenityId);
523
+ continue;
524
+ }
525
+ locationParts.push(segment);
526
+ }
527
+ if (propertyTypes.length === 1) filters.propertyType = propertyTypes[0];
528
+ else if (propertyTypes.length > 1) filters.propertyType = propertyTypes;
529
+ if (propertyFeatures.length) filters.propertyFeatures = propertyFeatures;
530
+ if (buildingAmenities.length) filters.buildingAmenities = buildingAmenities;
531
+ const location = locationFromPathLeftovers(locationParts);
532
+ if (location) filters.location = location;
533
+ return filters;
534
+ }
535
+ var PATH_STREET_PREFIX = /^(rua|r|avenida|av|alameda|al|travessa|tv|estrada|rodovia|rod)-/i;
536
+ function locationFromPathLeftovers(parts) {
537
+ if (parts.length === 0) return void 0;
538
+ if (parts.length === 1) {
539
+ const value = parts[0];
540
+ if (PATH_STREET_PREFIX.test(value)) return { street: value };
541
+ if (/^[a-z]{2}$/i.test(value)) return { state: value };
542
+ return { neighborhood: value };
543
+ }
544
+ const [state, city, neighborhood, street] = parts;
545
+ return {
546
+ ...state ? { state } : {},
547
+ ...city ? { city } : {},
548
+ ...neighborhood ? { neighborhood } : {},
549
+ ...street ? { street } : {}
550
+ };
551
+ }
552
+
553
+ // ../search-url/applied-query.ts
554
+ var SORT_SET = new Set(SORT_URL_TOKENS);
555
+ function isSortToken(value) {
556
+ return SORT_SET.has(value);
557
+ }
558
+ function normalizeAppliedSearchQuery(query) {
559
+ if (query.loc && query.loc.length > 0) {
560
+ const { query: _query, ...rest } = query;
561
+ return rest;
562
+ }
563
+ return query;
564
+ }
565
+ function parseAppliedSearchQuery(search) {
566
+ const params = search instanceof URLSearchParams ? search : new URLSearchParams(search.startsWith("?") ? search.slice(1) : search);
567
+ const result = {};
568
+ const pageRaw = params.get("page");
569
+ if (pageRaw) {
570
+ const page = Number.parseInt(pageRaw, 10);
571
+ if (Number.isFinite(page) && page > 1) {
572
+ result.page = Math.min(page, MAX_PAGE);
573
+ }
574
+ }
575
+ const sort = params.get("ordenar");
576
+ if (sort && isSortToken(sort)) result.sort = sort;
577
+ const q = params.get("q")?.trim();
578
+ if (q) result.query = q;
579
+ const loc = params.getAll("loc").map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
580
+ if (loc.length > 0) result.loc = loc;
581
+ return normalizeAppliedSearchQuery(result);
582
+ }
583
+ var APPLIED_QUERY_KEYS = ["page", "ordenar", "q", "loc"];
584
+ function serializeAppliedSearchQuery(query) {
585
+ const normalized = normalizeAppliedSearchQuery(query);
586
+ const params = new URLSearchParams();
587
+ if (normalized.page !== void 0 && normalized.page > 1) {
588
+ params.set("page", String(Math.min(normalized.page, MAX_PAGE)));
589
+ }
590
+ if (normalized.sort && isSortToken(normalized.sort)) {
591
+ params.set("ordenar", normalized.sort);
592
+ }
593
+ const text = normalized.query?.trim();
594
+ if (text) params.set("q", text);
595
+ for (const value of (normalized.loc ?? []).slice(0, MAX_LOC_GROUPS)) {
596
+ const trimmed = value.trim();
597
+ if (trimmed) params.append("loc", trimmed);
598
+ }
599
+ return params;
600
+ }
601
+ function mergeAppliedSearchQueryIntoSearch(existing, query) {
602
+ const params = existing instanceof URLSearchParams ? new URLSearchParams(existing) : new URLSearchParams(
603
+ existing.startsWith("?") ? existing.slice(1) : existing
604
+ );
605
+ for (const key of APPLIED_QUERY_KEYS) {
606
+ params.delete(key);
607
+ }
608
+ const serialized = serializeAppliedSearchQuery(query);
609
+ serialized.forEach((value, key) => {
610
+ if (key === "loc") {
611
+ params.append("loc", value);
612
+ } else {
613
+ params.set(key, value);
614
+ }
615
+ });
616
+ return params;
617
+ }
618
+ function reduceAppliedSearchQuery(prev, change) {
619
+ switch (change.type) {
620
+ case "sort": {
621
+ const next = { ...prev };
622
+ delete next.page;
623
+ if (change.sort) next.sort = change.sort;
624
+ else delete next.sort;
625
+ return normalizeAppliedSearchQuery(next);
626
+ }
627
+ case "applyFilters": {
628
+ const next = { ...prev };
629
+ delete next.page;
630
+ return normalizeAppliedSearchQuery(next);
631
+ }
632
+ case "query": {
633
+ const next = { ...prev };
634
+ delete next.page;
635
+ const trimmed = change.query.trim();
636
+ if (trimmed) {
637
+ next.query = trimmed;
638
+ delete next.loc;
639
+ } else {
640
+ delete next.query;
641
+ }
642
+ return normalizeAppliedSearchQuery(next);
643
+ }
644
+ case "loc": {
645
+ const next = { ...prev };
646
+ delete next.page;
647
+ delete next.query;
648
+ const loc = change.loc.map((value) => value.trim()).filter(Boolean).slice(0, MAX_LOC_GROUPS);
649
+ if (loc.length > 0) next.loc = loc;
650
+ else delete next.loc;
651
+ return normalizeAppliedSearchQuery(next);
652
+ }
653
+ case "page": {
654
+ const next = { ...prev };
655
+ if (change.page <= 1) delete next.page;
656
+ else next.page = Math.min(change.page, MAX_PAGE);
657
+ return normalizeAppliedSearchQuery(next);
658
+ }
659
+ default: {
660
+ const _exhaustive = change;
661
+ return _exhaustive;
662
+ }
663
+ }
664
+ }
665
+ function composeSearchPublicHref(pathname, query, existingSearch) {
666
+ const params = existingSearch ? mergeAppliedSearchQueryIntoSearch(existingSearch, query) : serializeAppliedSearchQuery(query);
667
+ const qs = params.toString();
668
+ return qs ? `${pathname}?${qs}` : pathname;
669
+ }
670
+
671
+ // src/applied-query.ts
672
+ function parseAppliedSearchQuery2(search) {
673
+ return parseAppliedSearchQuery(search);
674
+ }
675
+ function reduceAppliedSearchQuery2(prev, change) {
676
+ return reduceAppliedSearchQuery(prev, change);
677
+ }
678
+ function composeSearchPublicHref2(pathname, query, existingSearch) {
679
+ return composeSearchPublicHref(pathname, query, existingSearch);
680
+ }
681
+
682
+ // src/loc-params.ts
683
+ function pathLocationToFilterInput(location) {
684
+ if (!location || typeof location !== "object") return null;
685
+ const { state, city, neighborhood, street } = location;
686
+ const levels = [];
687
+ if (state) levels.push(state);
688
+ if (city) levels.push(city);
689
+ if (neighborhood) levels.push(neighborhood);
690
+ if (street) levels.push(street);
691
+ if (levels.length === 0) return null;
692
+ if (levels.length === 1) {
693
+ if (state) return { type: "state", value: state };
694
+ if (city) return { type: "city", value: city };
695
+ if (neighborhood) return { type: "neighborhood", value: neighborhood };
696
+ if (street) return { type: "street", value: street };
697
+ }
698
+ return { type: "path", value: levels.join("/") };
699
+ }
700
+
701
+ // src/path.ts
702
+ function composeSearchPublicPath2(filters, dictionary) {
703
+ return dictionary ? composeSearchPublicPath(filters, dictionary) : composeSearchPublicPath(filters);
704
+ }
705
+ function parseSearchPublicPath2(pathname, dictionary) {
706
+ return dictionary ? parseSearchPublicPath(pathname, dictionary) : parseSearchPublicPath(pathname);
707
+ }
708
+ function pathFiltersToQueryFilters(pathFilters) {
709
+ const result = {};
710
+ if (pathFilters.listingType !== void 0) {
711
+ result.listing_type = pathFilters.listingType;
712
+ }
713
+ if (pathFilters.propertyType !== void 0) {
714
+ result.property_type = pathFilters.propertyType;
715
+ }
716
+ if (pathFilters.bedrooms !== void 0) {
717
+ result.property_bedrooms = pathFilters.bedrooms;
718
+ }
719
+ if (pathFilters.bathrooms !== void 0) {
720
+ result.property_bathrooms = pathFilters.bathrooms;
721
+ }
722
+ if (pathFilters.suites !== void 0) {
723
+ result.property_suites = pathFilters.suites;
724
+ }
725
+ if (pathFilters.parkingSpots !== void 0) {
726
+ result.property_parking_spots = pathFilters.parkingSpots;
727
+ }
728
+ if (pathFilters.price !== void 0) {
729
+ result.price = pathFilters.price;
730
+ }
731
+ if (pathFilters.area !== void 0) {
732
+ result.property_area_total = pathFilters.area;
733
+ }
734
+ if (pathFilters.propertyFeatures !== void 0) {
735
+ result.propertyFeatures = pathFilters.propertyFeatures;
736
+ }
737
+ if (pathFilters.buildingAmenities !== void 0) {
738
+ result.buildingAmenities = pathFilters.buildingAmenities;
739
+ }
740
+ return result;
741
+ }
742
+
743
+ // src/search-engine.ts
744
+ var PATH_FILTER_IDS = {
745
+ listing_type: "listingType",
746
+ property_type: "propertyType",
747
+ property_bedrooms: "bedrooms",
748
+ property_bathrooms: "bathrooms",
749
+ property_suites: "suites",
750
+ property_parking_spots: "parkingSpots",
751
+ price: "price",
752
+ property_area_total: "area",
753
+ propertyFeatures: "propertyFeatures",
754
+ buildingAmenities: "buildingAmenities"
755
+ };
756
+ var SEARCH_SORT_RELEVANCE = {
757
+ id: "",
758
+ label: "Mais relevantes"
759
+ };
760
+ function searchSortOptions(sorts) {
761
+ const fromApi = (sorts || []).filter((sort) => sort.id);
762
+ return [
763
+ { id: SEARCH_SORT_RELEVANCE.id, label: SEARCH_SORT_RELEVANCE.label },
764
+ ...fromApi
765
+ ];
766
+ }
767
+ var TOOLBAR_PRIMARY_FILTER_IDS = [
768
+ "price",
769
+ "property_bedrooms"
770
+ ];
771
+ var HIDDEN_FILTER_IDS = /* @__PURE__ */ new Set(["property_suites"]);
772
+ function toFiniteNumber(value) {
773
+ if (value === "" || value == null) return void 0;
774
+ const n = Number(value);
775
+ return Number.isFinite(n) ? n : void 0;
776
+ }
777
+ function pathnameOnly(pathname) {
778
+ return String(pathname || "").split(/[?#]/)[0] || "/";
779
+ }
780
+ function readPublicSearch(pathname, search, dictionary) {
781
+ const pathFilters = parseSearchPublicPath2(pathnameOnly(pathname), dictionary) || {};
782
+ const applied = parseAppliedSearchQuery2(search || "");
783
+ return { pathFilters, applied };
784
+ }
785
+ function lookupDisplay(table, slug) {
786
+ if (!slug || !table) return slug;
787
+ return table[slug] || table[String(slug).toLowerCase()] || slug;
788
+ }
789
+ function displayPathLocation(location, values) {
790
+ if (!location) return null;
791
+ const table = values || {};
792
+ return {
793
+ state: lookupDisplay(table.states, location.state),
794
+ city: lookupDisplay(table.cities, location.city),
795
+ neighborhood: lookupDisplay(table.neighborhoods, location.neighborhood),
796
+ street: lookupDisplay(table.streets, location.street)
797
+ };
798
+ }
799
+ function buildQueryListingsParams(pathFilters, applied, schema, locationValues) {
800
+ const filters = pathFiltersToQueryFilters(pathFilters || {});
801
+ const locations = [];
802
+ const displayed = displayPathLocation(pathFilters?.location, locationValues);
803
+ const pathLoc = displayed ? pathLocationToFilterInput(displayed) : null;
804
+ if (pathLoc) locations.push(pathLoc);
805
+ for (const value of applied?.loc || []) {
806
+ locations.push({ type: "loc", value });
807
+ }
808
+ const params = {
809
+ page: applied?.page || 1,
810
+ limit: schema?.defaultLimit || 12,
811
+ filters
812
+ };
813
+ if (applied?.sort) params.sort = applied.sort;
814
+ const hasLocation = locations.length > 0;
815
+ if (applied?.query && !hasLocation) params.q = applied.query;
816
+ if (hasLocation) params.location = locations;
817
+ return params;
818
+ }
819
+ function applyPathFilter(pathFilters, filterId, value) {
820
+ const next = { ...pathFilters || {} };
821
+ const key = PATH_FILTER_IDS[filterId];
822
+ if (!key) return next;
823
+ if (value === "" || value == null) {
824
+ delete next[key];
825
+ return next;
826
+ }
827
+ if (key === "price" || key === "area") {
828
+ const range = value || {};
829
+ const parse = key === "price" ? parseGroupedInteger : toFiniteNumber;
830
+ const min = parse(range.min);
831
+ const max = parse(range.max);
832
+ if (min == null && max == null) {
833
+ delete next[key];
834
+ return next;
835
+ }
836
+ next[key] = {
837
+ ...min != null ? { min } : {},
838
+ ...max != null ? { max } : {}
839
+ };
840
+ return next;
841
+ }
842
+ if (key === "propertyFeatures" || key === "buildingAmenities") {
843
+ const current = Array.isArray(next[key]) ? [...next[key]] : [];
844
+ const id = String(value);
845
+ const i = current.indexOf(id);
846
+ if (i >= 0) current.splice(i, 1);
847
+ else current.push(id);
848
+ if (current.length) next[key] = current;
849
+ else delete next[key];
850
+ return next;
851
+ }
852
+ if (key === "propertyType") {
853
+ const id = String(value);
854
+ const current = Array.isArray(next.propertyType) ? [...next.propertyType] : next.propertyType ? [String(next.propertyType)] : [];
855
+ const i = current.indexOf(id);
856
+ if (i >= 0) current.splice(i, 1);
857
+ else current.push(id);
858
+ if (current.length === 0) delete next.propertyType;
859
+ else if (current.length === 1) next.propertyType = current[0];
860
+ else next.propertyType = current;
861
+ return next;
862
+ }
863
+ if (key === "listingType") {
864
+ const id = String(value);
865
+ if (next.listingType === id) delete next.listingType;
866
+ else next.listingType = id;
867
+ return next;
868
+ }
869
+ if (key === "bedrooms" || key === "bathrooms" || key === "suites" || key === "parkingSpots") {
870
+ const n = Number(value);
871
+ if (!Number.isFinite(n)) {
872
+ delete next[key];
873
+ return next;
874
+ }
875
+ if (next[key] === n) delete next[key];
876
+ else next[key] = n;
877
+ return next;
878
+ }
879
+ return next;
880
+ }
881
+ function pathFilterValue(pathFilters, filterId) {
882
+ const key = PATH_FILTER_IDS[filterId];
883
+ const value = pathFilters && key ? pathFilters[key] : void 0;
884
+ if (value == null) return "";
885
+ if (Array.isArray(value)) return value[0] != null ? String(value[0]) : "";
886
+ if (typeof value === "object") return "";
887
+ return String(value);
888
+ }
889
+ function pathFilterHasOption(pathFilters, filterId, optionId) {
890
+ const key = PATH_FILTER_IDS[filterId];
891
+ const value = pathFilters && key ? pathFilters[key] : void 0;
892
+ if (value == null) return false;
893
+ if (Array.isArray(value)) return value.map(String).includes(optionId);
894
+ if (typeof value === "object") return false;
895
+ return String(value) === optionId;
896
+ }
897
+ function publicSearchHref(pathFilters, applied, dictionary, existingSearch) {
898
+ const pathname = composeSearchPublicPath2(pathFilters || {}, dictionary);
899
+ return composeSearchPublicHref2(pathname, applied || {}, existingSearch);
900
+ }
901
+ function hrefForPathFilters(pathname, search, dictionary, nextPathFilters) {
902
+ const { applied } = readPublicSearch(pathname, search, dictionary);
903
+ const nextApplied = reduceAppliedSearchQuery2(applied, {
904
+ type: "applyFilters"
905
+ });
906
+ return publicSearchHref(nextPathFilters, nextApplied, dictionary, search);
907
+ }
908
+ function hrefForAppliedChange(pathname, search, dictionary, change) {
909
+ const { pathFilters, applied } = readPublicSearch(
910
+ pathname,
911
+ search,
912
+ dictionary
913
+ );
914
+ let nextPath = pathFilters;
915
+ if (change && change.type === "query") {
916
+ nextPath = { ...pathFilters };
917
+ delete nextPath.location;
918
+ }
919
+ const nextApplied = reduceAppliedSearchQuery2(applied, change);
920
+ return publicSearchHref(nextPath, nextApplied, dictionary, search);
921
+ }
922
+ function currentSearchHref(pathname, search) {
923
+ const path = pathnameOnly(pathname);
924
+ const qs = search.replace(/^\?/, "");
925
+ return qs ? `${path}?${qs}` : path;
926
+ }
927
+ function canonicalizeSearchHref(pathname, search, dictionary) {
928
+ const { pathFilters, applied } = readPublicSearch(
929
+ pathname,
930
+ search,
931
+ dictionary
932
+ );
933
+ const href = publicSearchHref(pathFilters, applied, dictionary, search);
934
+ if (href === currentSearchHref(pathname, search)) return null;
935
+ return href;
936
+ }
937
+ function clearStagedPathFilters(current, keepFilterIds = []) {
938
+ const next = current.location ? { location: current.location } : {};
939
+ for (const id of keepFilterIds) {
940
+ const key = PATH_FILTER_IDS[id];
941
+ if (!key || key === "location") continue;
942
+ const value = current[key];
943
+ if (value != null) Object.assign(next, { [key]: value });
944
+ }
945
+ return next;
946
+ }
947
+ function visibleSearchFilters(schema) {
948
+ if (!schema?.filters) return [];
949
+ return schema.filters.filter((filter) => {
950
+ if (HIDDEN_FILTER_IDS.has(filter.id)) return false;
951
+ if (filter.id === "listing_type" && (filter.options?.length ?? 0) <= 1) {
952
+ return false;
953
+ }
954
+ return true;
955
+ });
956
+ }
957
+ function toolbarFilterIds(schema) {
958
+ const visible = new Set(visibleSearchFilters(schema).map((f) => f.id));
959
+ return TOOLBAR_PRIMARY_FILTER_IDS.filter((id) => visible.has(id));
960
+ }
961
+ function countOptionLabel(option) {
962
+ const label = String(option?.label ?? "");
963
+ if (/^[1-9]\d*$/.test(label)) return `${label}+`;
964
+ return label;
965
+ }
966
+ function countFacetChoices(options) {
967
+ const list = options || [];
968
+ const zero = list.find((o) => o.id === "0" || o.label === "Studio");
969
+ const isStudio = Boolean(
970
+ zero && /studio/i.test(String(zero.label)) && zero.id === "0"
971
+ );
972
+ const max = isStudio ? 3 : 4;
973
+ const out = [];
974
+ if (zero) out.push({ id: zero.id, label: countOptionLabel(zero) });
975
+ for (let n = 1; n <= max; n += 1) {
976
+ const option = list.find((o) => o.id === String(n));
977
+ out.push({
978
+ id: String(n),
979
+ label: countOptionLabel(option || { label: String(n) })
980
+ });
981
+ }
982
+ return out;
983
+ }
984
+ function paginationPages(currentPage, totalPages, padding) {
985
+ if (totalPages < 1) return [];
986
+ const current = Math.min(Math.max(1, currentPage), totalPages);
987
+ const start = Math.max(1, current - padding);
988
+ const end = Math.min(totalPages, current + padding);
989
+ const pages = [];
990
+ for (let i = start; i <= end; i += 1) pages.push(i);
991
+ return pages;
992
+ }
993
+
994
+ // src/react/filter-panel.tsx
995
+ var import_jsx_runtime2 = require("react/jsx-runtime");
996
+ function RangeFields({
997
+ filter,
998
+ rangeDraft,
999
+ onRangePatch,
1000
+ onRangeCommit
1001
+ }) {
1002
+ const draft = rangeDraft[filter.id] || { min: "", max: "" };
1003
+ const isPrice = filter.id === "price";
1004
+ const patch = (side, raw) => {
1005
+ onRangePatch(filter.id, side, isPrice ? formatGroupedInteger(raw) : raw);
1006
+ };
1007
+ const inputClass = "min-h-10 w-full rounded-lg border border-border bg-background px-3";
1008
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("fieldset", { className: "text-sm", children: [
1009
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("legend", { className: "mb-1 text-muted-foreground", children: filter.label }),
1010
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex gap-2", children: [
1011
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1012
+ RangeSide,
1013
+ {
1014
+ id: `${filter.id}-min`,
1015
+ label: "M\xEDn",
1016
+ isPrice,
1017
+ value: draft.min,
1018
+ inputClass,
1019
+ onPatch: (raw) => patch("min", raw),
1020
+ onCommit: () => onRangeCommit(filter.id)
1021
+ }
1022
+ ),
1023
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1024
+ RangeSide,
1025
+ {
1026
+ id: `${filter.id}-max`,
1027
+ label: "M\xE1x",
1028
+ isPrice,
1029
+ value: draft.max,
1030
+ inputClass,
1031
+ onPatch: (raw) => patch("max", raw),
1032
+ onCommit: () => onRangeCommit(filter.id)
1033
+ }
1034
+ )
1035
+ ] })
1036
+ ] });
1037
+ }
1038
+ function RangeSide({
1039
+ id,
1040
+ label,
1041
+ isPrice,
1042
+ value,
1043
+ inputClass,
1044
+ onPatch,
1045
+ onCommit
1046
+ }) {
1047
+ const input = /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1048
+ "input",
1049
+ {
1050
+ id,
1051
+ type: isPrice ? "text" : "number",
1052
+ inputMode: isPrice ? "numeric" : "decimal",
1053
+ min: isPrice ? void 0 : 0,
1054
+ step: isPrice ? void 0 : 0.01,
1055
+ value,
1056
+ placeholder: isPrice ? "0" : void 0,
1057
+ onChange: (event) => onPatch(event.target.value),
1058
+ onBlur: onCommit,
1059
+ onKeyDown: (event) => {
1060
+ if (event.key === "Enter") onCommit();
1061
+ },
1062
+ className: isPrice ? `${inputClass} pl-10` : inputClass
1063
+ }
1064
+ );
1065
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("label", { className: "min-w-0 flex-1", htmlFor: id, children: [
1066
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "mb-1 block text-xs text-muted-foreground", children: label }),
1067
+ isPrice ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "relative block", children: [
1068
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3 text-muted-foreground", children: "R$" }),
1069
+ input
1070
+ ] }) : input
1071
+ ] });
1072
+ }
1073
+ function CountFields({
1074
+ filter,
1075
+ pathFilters,
1076
+ onChange
1077
+ }) {
1078
+ const selected = pathFilterValue(pathFilters, filter.id);
1079
+ const choices = countFacetChoices(filter.options);
1080
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("fieldset", { className: "text-sm", children: [
1081
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("legend", { className: "mb-2 text-muted-foreground", children: filter.label }),
1082
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "flex flex-wrap gap-1.5", role: "group", children: choices.map((choice) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1083
+ "button",
1084
+ {
1085
+ type: "button",
1086
+ onClick: () => onChange(filter.id, Number(choice.id)),
1087
+ className: cn(
1088
+ "min-h-10 cursor-pointer rounded-lg border px-3 text-sm hover:bg-muted",
1089
+ selected === choice.id && "border-primary bg-primary/10"
1090
+ ),
1091
+ children: choice.label
1092
+ },
1093
+ choice.id
1094
+ )) })
1095
+ ] });
1096
+ }
1097
+ function EnumFields({
1098
+ filter,
1099
+ pathFilters,
1100
+ onChange
1101
+ }) {
1102
+ const options = filter.options || [];
1103
+ const scroll = options.length > 8;
1104
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("fieldset", { className: "text-sm", children: [
1105
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("legend", { className: "mb-2 text-muted-foreground", children: filter.label }),
1106
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1107
+ "div",
1108
+ {
1109
+ className: cn(
1110
+ "flex flex-col gap-1.5",
1111
+ scroll && "max-h-48 overflow-y-auto"
1112
+ ),
1113
+ children: options.map((option) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1114
+ "label",
1115
+ {
1116
+ className: "flex cursor-pointer items-center gap-2",
1117
+ children: [
1118
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1119
+ "input",
1120
+ {
1121
+ type: "checkbox",
1122
+ checked: pathFilterHasOption(pathFilters, filter.id, option.id),
1123
+ onChange: () => onChange(filter.id, option.id),
1124
+ className: "cursor-pointer"
1125
+ }
1126
+ ),
1127
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { children: option.label })
1128
+ ]
1129
+ },
1130
+ option.id
1131
+ ))
1132
+ }
1133
+ )
1134
+ ] });
1135
+ }
1136
+ function FilterPanel({
1137
+ filters,
1138
+ pathFilters,
1139
+ onChange,
1140
+ rangeDraft,
1141
+ onRangePatch,
1142
+ onRangeCommit
1143
+ }) {
1144
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: "flex flex-col gap-5", "data-slot": "search-filters", children: filters.map((filter) => {
1145
+ if (filter.type === "range") {
1146
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1147
+ RangeFields,
1148
+ {
1149
+ filter,
1150
+ rangeDraft,
1151
+ onRangePatch,
1152
+ onRangeCommit
1153
+ },
1154
+ filter.id
1155
+ );
1156
+ }
1157
+ if (filter.type === "count") {
1158
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1159
+ CountFields,
1160
+ {
1161
+ filter,
1162
+ pathFilters,
1163
+ onChange
1164
+ },
1165
+ filter.id
1166
+ );
1167
+ }
1168
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1169
+ EnumFields,
1170
+ {
1171
+ filter,
1172
+ pathFilters,
1173
+ onChange
1174
+ },
1175
+ filter.id
1176
+ );
1177
+ }) });
1178
+ }
1179
+ function rangeDraftFromPath(pathFilters) {
1180
+ const price = pathFilters.price || {};
1181
+ const area = pathFilters.area || {};
1182
+ return {
1183
+ price: {
1184
+ min: price.min != null ? formatGroupedInteger(price.min) : "",
1185
+ max: price.max != null ? formatGroupedInteger(price.max) : ""
1186
+ },
1187
+ property_area_total: {
1188
+ min: area.min != null ? String(area.min) : "",
1189
+ max: area.max != null ? String(area.max) : ""
1190
+ }
1191
+ };
1192
+ }
1193
+
1194
+ // src/react/search-chrome.tsx
1195
+ var import_jsx_runtime3 = require("react/jsx-runtime");
1196
+ function SearchSortSelect({
1197
+ value,
1198
+ onChange,
1199
+ sorts,
1200
+ className
1201
+ }) {
1202
+ const options = searchSortOptions(sorts);
1203
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("label", { className: cn("text-sm", className), children: [
1204
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "mb-1 block text-muted-foreground", children: "Ordenar" }),
1205
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1206
+ "select",
1207
+ {
1208
+ id: "garagem-search-sort",
1209
+ value,
1210
+ onChange: (event) => onChange(event.target.value || null),
1211
+ className: "min-h-10 cursor-pointer rounded-lg border border-border bg-background px-3",
1212
+ children: options.map((sort) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("option", { value: sort.id, children: sort.label }, sort.id || "relevance"))
1213
+ }
1214
+ )
1215
+ ] });
1216
+ }
1217
+ function ResultsSkeleton({
1218
+ className
1219
+ }) {
1220
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1221
+ "div",
1222
+ {
1223
+ "data-slot": "search-skeleton",
1224
+ className: cn(
1225
+ "grid grid-cols-1 gap-[var(--garagem-listing-card-gap,1.5rem)] sm:grid-cols-2 lg:grid-cols-3",
1226
+ className
1227
+ ),
1228
+ children: Array.from({ length: 6 }, (_, i) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
1229
+ "div",
1230
+ {
1231
+ className: "overflow-hidden rounded-[var(--garagem-listing-card-radius,0.75rem)] border border-border",
1232
+ children: [
1233
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1234
+ "div",
1235
+ {
1236
+ className: "animate-pulse bg-muted",
1237
+ style: { aspectRatio: "4 / 3" }
1238
+ }
1239
+ ),
1240
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "space-y-2 p-4", children: [
1241
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "h-5 w-1/2 animate-pulse rounded bg-muted" }),
1242
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "h-4 w-3/4 animate-pulse rounded bg-muted" }),
1243
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "h-3 w-2/3 animate-pulse rounded bg-muted" })
1244
+ ] })
1245
+ ]
1246
+ },
1247
+ i
1248
+ ))
1249
+ }
1250
+ );
1251
+ }
1252
+
1253
+ // src/react/search-pagination.tsx
1254
+ var import_link2 = __toESM(require("next/link"));
1255
+ var import_jsx_runtime4 = require("react/jsx-runtime");
1256
+ function NavItem({
1257
+ href,
1258
+ label,
1259
+ disabled,
1260
+ current,
1261
+ className
1262
+ }) {
1263
+ const itemClass = cn(
1264
+ "inline-flex size-8 cursor-pointer items-center justify-center rounded-md border text-xs font-medium md:size-9",
1265
+ current && "bg-primary text-primary-foreground",
1266
+ disabled && "cursor-not-allowed text-muted-foreground",
1267
+ className
1268
+ );
1269
+ if (disabled || !href || current) {
1270
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("li", { className: itemClass, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "flex size-full items-center justify-center", children: label }) });
1271
+ }
1272
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("li", { className: itemClass, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1273
+ import_link2.default,
1274
+ {
1275
+ href,
1276
+ className: "flex size-full items-center justify-center",
1277
+ "aria-label": label,
1278
+ children: label
1279
+ }
1280
+ ) });
1281
+ }
1282
+ function SearchPagination({
1283
+ page,
1284
+ totalPages,
1285
+ hrefForPage,
1286
+ className
1287
+ }) {
1288
+ if (totalPages <= 1) return null;
1289
+ const mobile = paginationPages(page, totalPages, 1);
1290
+ const desktop = paginationPages(page, totalPages, 2);
1291
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1292
+ "nav",
1293
+ {
1294
+ "data-slot": "search-pagination",
1295
+ className: cn("mt-10 flex justify-center", className),
1296
+ "aria-label": "Pagina\xE7\xE3o",
1297
+ children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("ul", { className: "flex gap-0.5 md:gap-1", children: [
1298
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(NavItem, { href: hrefForPage(1), label: "\u2039\u2039", disabled: page <= 1 }),
1299
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1300
+ NavItem,
1301
+ {
1302
+ href: hrefForPage(Math.max(1, page - 1)),
1303
+ label: "\u2039",
1304
+ disabled: page <= 1
1305
+ }
1306
+ ),
1307
+ mobile.map((n) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1308
+ NavItem,
1309
+ {
1310
+ href: hrefForPage(n),
1311
+ label: String(n),
1312
+ current: n === page,
1313
+ className: "md:hidden"
1314
+ },
1315
+ `m-${n}`
1316
+ )),
1317
+ desktop.map((n) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1318
+ NavItem,
1319
+ {
1320
+ href: hrefForPage(n),
1321
+ label: String(n),
1322
+ current: n === page,
1323
+ className: "hidden md:inline-flex"
1324
+ },
1325
+ `d-${n}`
1326
+ )),
1327
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1328
+ NavItem,
1329
+ {
1330
+ href: hrefForPage(Math.min(totalPages, page + 1)),
1331
+ label: "\u203A",
1332
+ disabled: page >= totalPages
1333
+ }
1334
+ ),
1335
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1336
+ NavItem,
1337
+ {
1338
+ href: hrefForPage(totalPages),
1339
+ label: "\u203A\u203A",
1340
+ disabled: page >= totalPages
1341
+ }
1342
+ )
1343
+ ] })
1344
+ }
1345
+ );
1346
+ }
1347
+
1348
+ // src/react/search-query-form.tsx
1349
+ var import_jsx_runtime5 = require("react/jsx-runtime");
1350
+ function SearchQueryForm({
1351
+ value,
1352
+ onChange,
1353
+ onSubmit,
1354
+ onClear,
1355
+ className
1356
+ }) {
1357
+ function handleSubmit(event) {
1358
+ event.preventDefault();
1359
+ onSubmit();
1360
+ }
1361
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1362
+ "form",
1363
+ {
1364
+ role: "search",
1365
+ "data-slot": "search-query",
1366
+ onSubmit: handleSubmit,
1367
+ className: cn("flex items-end gap-2", className),
1368
+ children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "min-w-0 flex-1", children: [
1369
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1370
+ "label",
1371
+ {
1372
+ htmlFor: "garagem-search-q",
1373
+ className: "mb-1 block text-sm text-muted-foreground",
1374
+ children: "Busca"
1375
+ }
1376
+ ),
1377
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "relative", children: [
1378
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1379
+ "input",
1380
+ {
1381
+ id: "garagem-search-q",
1382
+ name: "q",
1383
+ type: "search",
1384
+ autoComplete: "off",
1385
+ enterKeyHint: "search",
1386
+ value,
1387
+ onChange: (event) => onChange(event.target.value),
1388
+ placeholder: "Busque por bairro, rua ou c\xF3digo",
1389
+ className: "min-h-12 w-full rounded-xl border border-border bg-background px-4 pr-20 outline-none focus:border-primary"
1390
+ }
1391
+ ),
1392
+ value ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1393
+ "button",
1394
+ {
1395
+ type: "button",
1396
+ title: "Limpar busca",
1397
+ "aria-label": "Limpar busca",
1398
+ onClick: onClear,
1399
+ className: "absolute right-10 top-1/2 -translate-y-1/2 cursor-pointer rounded-md px-2 py-1 text-sm text-muted-foreground hover:text-foreground",
1400
+ children: "\xD7"
1401
+ }
1402
+ ) : null,
1403
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1404
+ "button",
1405
+ {
1406
+ type: "submit",
1407
+ title: "Buscar",
1408
+ "aria-label": "Buscar",
1409
+ className: "absolute right-2 top-1/2 -translate-y-1/2 cursor-pointer rounded-md px-2 py-1 text-sm font-medium hover:bg-muted",
1410
+ children: "\u2315"
1411
+ }
1412
+ )
1413
+ ] })
1414
+ ] })
1415
+ }
1416
+ );
1417
+ }
1418
+
1419
+ // src/react/use-public-search.ts
1420
+ var import_react = require("react");
1421
+ var import_navigation = require("next/navigation");
1422
+
1423
+ // src/internal/url.ts
1424
+ var DEFAULT_BASE_URL = "https://app.garagem.ai";
1425
+ function normalizeBaseUrl(baseUrl) {
1426
+ const url = baseUrl ?? DEFAULT_BASE_URL;
1427
+ return url.endsWith("/") ? url.slice(0, -1) : url;
1428
+ }
1429
+ async function coerceSiteId(siteId) {
1430
+ const value = await Promise.resolve(siteId);
1431
+ if (typeof value !== "string" || !value.trim()) {
1432
+ throw new TypeError(
1433
+ "Garagem SDK: siteId must be a string. Await resolveSiteId(...) before getListings / getSearchUi / queryListings."
1434
+ );
1435
+ }
1436
+ return value;
1437
+ }
1438
+
1439
+ // src/fetchers.ts
1440
+ async function callJson(url, init, fetchImpl) {
1441
+ const response = await fetchImpl(url, init);
1442
+ if (!response.ok) {
1443
+ const text = await response.text().catch(() => "");
1444
+ throw new GaragemSdkError(
1445
+ `Garagem SDK: request failed (${response.status} ${response.statusText}) for ${url}${text ? ` \u2014 ${text.slice(0, 200)}` : ""}`,
1446
+ { status: response.status, url }
1447
+ );
1448
+ }
1449
+ return await response.json();
1450
+ }
1451
+ var GaragemSdkError = class extends Error {
1452
+ status;
1453
+ url;
1454
+ constructor(message, info) {
1455
+ super(message);
1456
+ this.name = "GaragemSdkError";
1457
+ this.status = info.status;
1458
+ this.url = info.url;
1459
+ }
1460
+ };
1461
+ async function getSearchUi(options) {
1462
+ const { baseUrl, fetch: fetchImpl, next } = options;
1463
+ const siteId = await coerceSiteId(options.siteId);
1464
+ const base = normalizeBaseUrl(baseUrl);
1465
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search-ui`;
1466
+ return callJson(
1467
+ url,
1468
+ { method: "GET", headers: { Accept: "application/json" }, next },
1469
+ fetchImpl ?? fetch
1470
+ );
1471
+ }
1472
+ async function queryListings(options) {
1473
+ const { params, baseUrl, fetch: fetchImpl, next } = options;
1474
+ const siteId = await coerceSiteId(options.siteId);
1475
+ const base = normalizeBaseUrl(baseUrl);
1476
+ const url = `${base}/api/sites/${encodeURIComponent(siteId)}/search/listings`;
1477
+ return callJson(
1478
+ url,
1479
+ {
1480
+ method: "POST",
1481
+ headers: {
1482
+ Accept: "application/json",
1483
+ "Content-Type": "application/json"
1484
+ },
1485
+ body: JSON.stringify(params ?? {}),
1486
+ next
1487
+ },
1488
+ fetchImpl ?? fetch
1489
+ );
1490
+ }
1491
+
1492
+ // src/react/use-public-search.ts
1493
+ async function resolveSiteIdInput(siteId) {
1494
+ const value = typeof siteId === "function" ? siteId() : siteId;
1495
+ return coerceSiteId(value);
1496
+ }
1497
+ function currentHref(pathname, search) {
1498
+ return search ? `${pathname}?${search}` : pathname;
1499
+ }
1500
+ function usePublicSearch(options) {
1501
+ const { siteId, baseUrl } = options;
1502
+ const router = (0, import_navigation.useRouter)();
1503
+ const pathname = (0, import_navigation.usePathname)() || "/imoveis";
1504
+ const searchParams = (0, import_navigation.useSearchParams)();
1505
+ const search = searchParams.toString();
1506
+ const siteIdRef = (0, import_react.useRef)(siteId);
1507
+ siteIdRef.current = siteId;
1508
+ const siteIdToken = typeof siteId === "string" ? siteId : null;
1509
+ const [catalogId, setCatalogId] = (0, import_react.useState)(null);
1510
+ const [schema, setSchema] = (0, import_react.useState)(null);
1511
+ const [listings, setListings] = (0, import_react.useState)([]);
1512
+ const [page, setPage] = (0, import_react.useState)(1);
1513
+ const [total, setTotal] = (0, import_react.useState)(0);
1514
+ const [totalPages, setTotalPages] = (0, import_react.useState)(1);
1515
+ const [loading, setLoading] = (0, import_react.useState)(true);
1516
+ const [qDraft, setQDraft] = (0, import_react.useState)("");
1517
+ const [staged, setStaged] = (0, import_react.useState)({});
1518
+ const parsed = (0, import_react.useMemo)(
1519
+ () => readPublicSearch(pathname, search, schema?.dictionary),
1520
+ [pathname, search, schema?.dictionary]
1521
+ );
1522
+ (0, import_react.useEffect)(() => {
1523
+ setQDraft(parsed.applied.query || "");
1524
+ }, [parsed.applied.query]);
1525
+ const resetStagedFromUrl = (0, import_react.useCallback)(() => {
1526
+ setStaged({ ...parsed.pathFilters });
1527
+ }, [parsed.pathFilters]);
1528
+ (0, import_react.useEffect)(() => {
1529
+ setStaged({ ...parsed.pathFilters });
1530
+ }, [parsed.pathFilters]);
1531
+ const locationsRef = (0, import_react.useRef)(null);
1532
+ (0, import_react.useEffect)(() => {
1533
+ if (!schema) return;
1534
+ const canonical = canonicalizeSearchHref(
1535
+ pathname,
1536
+ search,
1537
+ schema.dictionary
1538
+ );
1539
+ if (canonical) router.replace(canonical);
1540
+ }, [pathname, search, schema, router]);
1541
+ (0, import_react.useEffect)(() => {
1542
+ let active = true;
1543
+ setCatalogId(null);
1544
+ setSchema(null);
1545
+ setListings([]);
1546
+ setLoading(true);
1547
+ resolveSiteIdInput(siteIdRef.current).then((id) => {
1548
+ if (active) setCatalogId(id);
1549
+ }).catch(() => {
1550
+ if (active) setLoading(false);
1551
+ });
1552
+ return () => {
1553
+ active = false;
1554
+ };
1555
+ }, [baseUrl, siteIdToken]);
1556
+ (0, import_react.useEffect)(() => {
1557
+ if (!catalogId) return;
1558
+ const id = catalogId;
1559
+ let active = true;
1560
+ locationsRef.current = null;
1561
+ setSchema(null);
1562
+ setListings([]);
1563
+ setLoading(true);
1564
+ async function loadSchema() {
1565
+ try {
1566
+ const nextSchema = await getSearchUi({ siteId: id, baseUrl });
1567
+ if (!active) return;
1568
+ let locations = null;
1569
+ if (nextSchema.locationsPath.startsWith("/")) {
1570
+ try {
1571
+ const response = await fetch(
1572
+ `${normalizeBaseUrl(baseUrl)}${nextSchema.locationsPath}`
1573
+ );
1574
+ if (response.ok) {
1575
+ locations = await response.json();
1576
+ }
1577
+ } catch {
1578
+ locations = null;
1579
+ }
1580
+ }
1581
+ if (!active) return;
1582
+ locationsRef.current = locations;
1583
+ setSchema(nextSchema);
1584
+ } catch {
1585
+ if (active) {
1586
+ locationsRef.current = null;
1587
+ setSchema(null);
1588
+ setLoading(false);
1589
+ }
1590
+ }
1591
+ }
1592
+ loadSchema();
1593
+ return () => {
1594
+ active = false;
1595
+ };
1596
+ }, [baseUrl, catalogId]);
1597
+ (0, import_react.useEffect)(() => {
1598
+ if (!schema || !catalogId) return;
1599
+ const currentSchema = schema;
1600
+ const id = catalogId;
1601
+ let active = true;
1602
+ async function loadListings() {
1603
+ setLoading(true);
1604
+ try {
1605
+ const { pathFilters, applied } = readPublicSearch(
1606
+ pathname,
1607
+ search,
1608
+ currentSchema.dictionary
1609
+ );
1610
+ const response = await queryListings({
1611
+ siteId: id,
1612
+ baseUrl,
1613
+ params: buildQueryListingsParams(
1614
+ pathFilters,
1615
+ applied,
1616
+ currentSchema,
1617
+ locationsRef.current
1618
+ )
1619
+ });
1620
+ if (!active) return;
1621
+ setListings(response.listings || []);
1622
+ setPage(response.page || 1);
1623
+ setTotal(response.total || 0);
1624
+ setTotalPages(response.totalPages || 1);
1625
+ } catch {
1626
+ if (active) {
1627
+ setListings([]);
1628
+ setPage(1);
1629
+ setTotal(0);
1630
+ setTotalPages(1);
1631
+ }
1632
+ } finally {
1633
+ if (active) setLoading(false);
1634
+ }
1635
+ }
1636
+ loadListings();
1637
+ return () => {
1638
+ active = false;
1639
+ };
1640
+ }, [pathname, search, baseUrl, schema, catalogId]);
1641
+ const go = (0, import_react.useCallback)(
1642
+ (href) => {
1643
+ if (href && href !== currentHref(pathname, search)) router.push(href);
1644
+ },
1645
+ [pathname, search, router]
1646
+ );
1647
+ const applyFilter = (0, import_react.useCallback)(
1648
+ (filterId, value) => {
1649
+ if (!schema) return;
1650
+ go(
1651
+ hrefForPathFilters(
1652
+ pathname,
1653
+ search,
1654
+ schema.dictionary,
1655
+ applyPathFilter(parsed.pathFilters, filterId, value)
1656
+ )
1657
+ );
1658
+ },
1659
+ [go, pathname, search, schema, parsed.pathFilters]
1660
+ );
1661
+ const stageFilter = (0, import_react.useCallback)((filterId, value) => {
1662
+ setStaged((current) => applyPathFilter(current, filterId, value));
1663
+ }, []);
1664
+ const applyStaged = (0, import_react.useCallback)(() => {
1665
+ if (!schema) return;
1666
+ go(hrefForPathFilters(pathname, search, schema.dictionary, staged));
1667
+ }, [go, pathname, search, schema, staged]);
1668
+ const clearStaged = (0, import_react.useCallback)(() => {
1669
+ setStaged((current) => clearStagedPathFilters(current));
1670
+ }, []);
1671
+ const submitQuery = (0, import_react.useCallback)(() => {
1672
+ if (!schema) return;
1673
+ go(
1674
+ hrefForAppliedChange(pathname, search, schema.dictionary, {
1675
+ type: "query",
1676
+ query: qDraft
1677
+ })
1678
+ );
1679
+ }, [go, pathname, search, schema, qDraft]);
1680
+ const clearQuery = (0, import_react.useCallback)(() => {
1681
+ setQDraft("");
1682
+ if (!schema) return;
1683
+ go(
1684
+ hrefForAppliedChange(pathname, search, schema.dictionary, {
1685
+ type: "query",
1686
+ query: ""
1687
+ })
1688
+ );
1689
+ }, [go, pathname, search, schema]);
1690
+ const setSort = (0, import_react.useCallback)(
1691
+ (sort) => {
1692
+ if (!schema) return;
1693
+ go(
1694
+ hrefForAppliedChange(pathname, search, schema.dictionary, {
1695
+ type: "sort",
1696
+ sort
1697
+ })
1698
+ );
1699
+ },
1700
+ [go, pathname, search, schema]
1701
+ );
1702
+ const hrefForPage = (0, import_react.useCallback)(
1703
+ (nextPage) => {
1704
+ if (!schema) return pathname;
1705
+ return hrefForAppliedChange(pathname, search, schema.dictionary, {
1706
+ type: "page",
1707
+ page: nextPage
1708
+ });
1709
+ },
1710
+ [pathname, search, schema]
1711
+ );
1712
+ return {
1713
+ schema,
1714
+ listings,
1715
+ page,
1716
+ total,
1717
+ totalPages,
1718
+ loading,
1719
+ pathname,
1720
+ search,
1721
+ pathFilters: parsed.pathFilters,
1722
+ applied: parsed.applied,
1723
+ qDraft,
1724
+ setQDraft,
1725
+ staged,
1726
+ setStaged,
1727
+ resetStagedFromUrl,
1728
+ applyFilter,
1729
+ stageFilter,
1730
+ applyStaged,
1731
+ clearStaged,
1732
+ submitQuery,
1733
+ clearQuery,
1734
+ setSort,
1735
+ hrefForPage,
1736
+ go
1737
+ };
1738
+ }
1739
+
1740
+ // src/react/search-page.tsx
1741
+ var import_jsx_runtime6 = require("react/jsx-runtime");
1742
+ function ToolbarPopover({
1743
+ label,
1744
+ children
1745
+ }) {
1746
+ const [open, setOpen] = (0, import_react2.useState)(false);
1747
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "relative", children: [
1748
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1749
+ "button",
1750
+ {
1751
+ type: "button",
1752
+ onClick: () => setOpen((value) => !value),
1753
+ className: "min-h-10 cursor-pointer rounded-lg border border-border px-3 text-sm hover:bg-muted",
1754
+ children: label
1755
+ }
1756
+ ),
1757
+ open ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", { className: "absolute z-20 mt-2 w-72 rounded-xl border border-border bg-background p-4 shadow-lg", children }) : null
1758
+ ] });
1759
+ }
1760
+ function FiltersTrigger({
1761
+ onClick,
1762
+ className
1763
+ }) {
1764
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1765
+ "button",
1766
+ {
1767
+ type: "button",
1768
+ title: "Filtros",
1769
+ onClick,
1770
+ className: cn(
1771
+ "min-h-10 cursor-pointer rounded-lg border border-border px-3 text-sm hover:bg-muted",
1772
+ className
1773
+ ),
1774
+ children: "Filtros"
1775
+ }
1776
+ );
1777
+ }
1778
+ function ApplyBar({
1779
+ onClear,
1780
+ onApply,
1781
+ className
1782
+ }) {
1783
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: cn("mt-6 flex gap-2", className), children: [
1784
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1785
+ "button",
1786
+ {
1787
+ type: "button",
1788
+ onClick: onClear,
1789
+ className: "min-h-10 flex-1 cursor-pointer rounded-lg border border-border px-4 hover:bg-muted",
1790
+ children: "Limpar"
1791
+ }
1792
+ ),
1793
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1794
+ "button",
1795
+ {
1796
+ type: "button",
1797
+ onClick: onApply,
1798
+ className: "min-h-10 flex-1 cursor-pointer rounded-lg bg-primary px-4 font-semibold text-primary-foreground hover:opacity-90",
1799
+ children: "Ver resultados"
1800
+ }
1801
+ )
1802
+ ] });
1803
+ }
1804
+ function SearchPage({
1805
+ siteId,
1806
+ baseUrl,
1807
+ variant = "toolbar",
1808
+ className,
1809
+ classNames,
1810
+ heading,
1811
+ listingCard: Card = ListingCard
1812
+ }) {
1813
+ const search = usePublicSearch({ siteId, baseUrl });
1814
+ const dialogRef = (0, import_react2.useRef)(null);
1815
+ const [mobileFiltersOpen, setMobileFiltersOpen] = (0, import_react2.useState)(false);
1816
+ const [rangeDraft, setRangeDraft] = (0, import_react2.useState)(
1817
+ () => rangeDraftFromPath(search.pathFilters)
1818
+ );
1819
+ (0, import_react2.useEffect)(() => {
1820
+ setRangeDraft(rangeDraftFromPath(search.pathFilters));
1821
+ }, [search.pathFilters]);
1822
+ const filters = visibleSearchFilters(search.schema);
1823
+ const toolbarIds = new Set(toolbarFilterIds(search.schema));
1824
+ const toolbarFilters = filters.filter((filter) => toolbarIds.has(filter.id));
1825
+ const extraFilters = filters.filter((filter) => !toolbarIds.has(filter.id));
1826
+ function patchRange(filterId, side, value) {
1827
+ setRangeDraft((prev) => ({
1828
+ ...prev,
1829
+ [filterId]: {
1830
+ min: prev[filterId]?.min ?? "",
1831
+ max: prev[filterId]?.max ?? "",
1832
+ [side]: value
1833
+ }
1834
+ }));
1835
+ }
1836
+ function commitRange(filterId, immediate) {
1837
+ const draft = rangeDraft[filterId] || { min: "", max: "" };
1838
+ if (immediate) search.applyFilter(filterId, draft);
1839
+ else search.stageFilter(filterId, draft);
1840
+ }
1841
+ function openStagedFilters() {
1842
+ search.resetStagedFromUrl();
1843
+ setRangeDraft(rangeDraftFromPath(search.pathFilters));
1844
+ if (variant === "sidebar") setMobileFiltersOpen(true);
1845
+ else dialogRef.current?.showModal();
1846
+ }
1847
+ function clearStagedFilters() {
1848
+ const keepIds = variant === "toolbar" ? [...toolbarIds] : [];
1849
+ const source = variant === "toolbar" ? search.pathFilters : search.staged;
1850
+ const next = clearStagedPathFilters(source, keepIds);
1851
+ search.setStaged(next);
1852
+ setRangeDraft((prev) => {
1853
+ const cleared = rangeDraftFromPath(next);
1854
+ if (variant !== "toolbar") return cleared;
1855
+ const kept = { ...cleared };
1856
+ for (const id of keepIds) {
1857
+ if (prev[id]) kept[id] = prev[id];
1858
+ }
1859
+ return kept;
1860
+ });
1861
+ }
1862
+ function applyStagedAndClose() {
1863
+ search.applyStaged();
1864
+ dialogRef.current?.close();
1865
+ setMobileFiltersOpen(false);
1866
+ }
1867
+ const results = search.loading ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ResultsSkeleton, { className: classNames?.grid }) : /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
1868
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("p", { className: "mb-4 text-sm text-muted-foreground", children: [
1869
+ search.total,
1870
+ " ",
1871
+ search.total === 1 ? "im\xF3vel encontrado" : "im\xF3veis encontrados"
1872
+ ] }),
1873
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1874
+ "div",
1875
+ {
1876
+ "data-slot": "search-grid",
1877
+ className: cn(
1878
+ "grid grid-cols-1 gap-[var(--garagem-listing-card-gap,1.5rem)] sm:grid-cols-2 lg:grid-cols-3",
1879
+ classNames?.grid
1880
+ ),
1881
+ children: search.listings.map((listing) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1882
+ Card,
1883
+ {
1884
+ listing,
1885
+ className: classNames?.card
1886
+ },
1887
+ listing.id
1888
+ ))
1889
+ }
1890
+ ),
1891
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1892
+ SearchPagination,
1893
+ {
1894
+ page: search.page,
1895
+ totalPages: search.totalPages,
1896
+ hrefForPage: search.hrefForPage,
1897
+ className: classNames?.pagination
1898
+ }
1899
+ )
1900
+ ] });
1901
+ const queryAndSort = /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end", children: [
1902
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1903
+ SearchQueryForm,
1904
+ {
1905
+ value: search.qDraft,
1906
+ onChange: search.setQDraft,
1907
+ onSubmit: search.submitQuery,
1908
+ onClear: search.clearQuery,
1909
+ className: cn("flex-1", classNames?.query)
1910
+ }
1911
+ ),
1912
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1913
+ SearchSortSelect,
1914
+ {
1915
+ value: search.applied.sort || "",
1916
+ onChange: search.setSort,
1917
+ sorts: search.schema?.sorts
1918
+ }
1919
+ )
1920
+ ] });
1921
+ const header = heading ?? /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
1922
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "text-xs uppercase tracking-widest text-primary", children: "Busca de im\xF3veis" }),
1923
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("h1", { className: "mt-3 text-4xl font-semibold tracking-tight", children: "Encontre seu pr\xF3ximo im\xF3vel" })
1924
+ ] });
1925
+ const stagedPanel = (items) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1926
+ FilterPanel,
1927
+ {
1928
+ filters: items,
1929
+ pathFilters: search.staged,
1930
+ onChange: search.stageFilter,
1931
+ rangeDraft,
1932
+ onRangePatch: patchRange,
1933
+ onRangeCommit: (id) => commitRange(id, false)
1934
+ }
1935
+ );
1936
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
1937
+ "main",
1938
+ {
1939
+ "data-slot": "search-page",
1940
+ "data-variant": variant,
1941
+ className: cn(
1942
+ "mx-auto max-w-7xl px-6 py-12",
1943
+ className,
1944
+ classNames?.root
1945
+ ),
1946
+ children: [
1947
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("div", { className: classNames?.header, children: header }),
1948
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "mt-8 space-y-6", children: [
1949
+ queryAndSort,
1950
+ variant === "toolbar" ? /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
1951
+ "div",
1952
+ {
1953
+ "data-slot": "search-toolbar",
1954
+ className: cn(
1955
+ "flex flex-wrap items-end gap-2",
1956
+ classNames?.toolbar
1957
+ ),
1958
+ children: [
1959
+ toolbarFilters.map((filter) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ToolbarPopover, { label: filter.label, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1960
+ FilterPanel,
1961
+ {
1962
+ filters: [filter],
1963
+ pathFilters: search.pathFilters,
1964
+ onChange: search.applyFilter,
1965
+ rangeDraft,
1966
+ onRangePatch: patchRange,
1967
+ onRangeCommit: (id) => commitRange(id, true)
1968
+ }
1969
+ ) }, filter.id)),
1970
+ extraFilters.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FiltersTrigger, { onClick: openStagedFilters }) : null
1971
+ ]
1972
+ }
1973
+ ) : null,
1974
+ variant === "dialog" ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FiltersTrigger, { onClick: openStagedFilters }) : null,
1975
+ variant === "sidebar" ? /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "grid gap-8 lg:grid-cols-[280px_minmax(0,1fr)]", children: [
1976
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
1977
+ "aside",
1978
+ {
1979
+ "data-slot": "search-sidebar",
1980
+ className: cn(
1981
+ "hidden lg:sticky lg:top-6 lg:block lg:self-start",
1982
+ classNames?.sidebar
1983
+ ),
1984
+ children: [
1985
+ stagedPanel(filters),
1986
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1987
+ ApplyBar,
1988
+ {
1989
+ onClear: clearStagedFilters,
1990
+ onApply: search.applyStaged,
1991
+ className: classNames?.applyBar
1992
+ }
1993
+ )
1994
+ ]
1995
+ }
1996
+ ),
1997
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { children: [
1998
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1999
+ FiltersTrigger,
2000
+ {
2001
+ onClick: openStagedFilters,
2002
+ className: "mb-4 lg:hidden"
2003
+ }
2004
+ ),
2005
+ results
2006
+ ] })
2007
+ ] }) : results
2008
+ ] }),
2009
+ variant !== "sidebar" ? /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
2010
+ "dialog",
2011
+ {
2012
+ ref: dialogRef,
2013
+ className: cn(
2014
+ "w-[min(32rem,calc(100%-2rem))] rounded-2xl border border-border bg-background p-6 shadow-xl",
2015
+ classNames?.dialog
2016
+ ),
2017
+ children: [
2018
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "mb-4 text-lg font-semibold", children: "Filtros" }),
2019
+ stagedPanel(variant === "toolbar" ? extraFilters : filters),
2020
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
2021
+ ApplyBar,
2022
+ {
2023
+ onClear: clearStagedFilters,
2024
+ onApply: applyStagedAndClose,
2025
+ className: classNames?.applyBar
2026
+ }
2027
+ )
2028
+ ]
2029
+ }
2030
+ ) : null,
2031
+ variant === "sidebar" && mobileFiltersOpen ? /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "fixed inset-0 z-40 lg:hidden", children: [
2032
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
2033
+ "button",
2034
+ {
2035
+ type: "button",
2036
+ "aria-label": "Fechar filtros",
2037
+ className: "absolute inset-0 bg-black/40",
2038
+ onClick: () => setMobileFiltersOpen(false)
2039
+ }
2040
+ ),
2041
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "absolute inset-y-0 right-0 w-[min(22rem,100%)] overflow-y-auto bg-background p-6", children: [
2042
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "mb-4 text-lg font-semibold", children: "Filtros" }),
2043
+ stagedPanel(filters),
2044
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
2045
+ ApplyBar,
2046
+ {
2047
+ onClear: clearStagedFilters,
2048
+ onApply: applyStagedAndClose,
2049
+ className: classNames?.applyBar
2050
+ }
2051
+ )
2052
+ ] })
2053
+ ] }) : null
2054
+ ]
2055
+ }
2056
+ );
2057
+ }
2058
+ // Annotate the CommonJS export names for ESM import in node:
2059
+ 0 && (module.exports = {
2060
+ FilterPanel,
2061
+ ListingCard,
2062
+ ResultsSkeleton,
2063
+ SearchPage,
2064
+ SearchPagination,
2065
+ SearchQueryForm,
2066
+ SearchSortSelect,
2067
+ rangeDraftFromPath,
2068
+ usePublicSearch
2069
+ });
2070
+ //# sourceMappingURL=react.js.map