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