All files / app/pages/category-list-page category-list-page.component.ts

49.4% Statements 374/757
72.72% Branches 32/44
57.14% Functions 16/28
49.4% Lines 374/757

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 7581x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x                         1x 1x 12x 12x 12x 12x 12x 12x 12x 11x 12x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x     12x 12x 12x 12x 12x 12x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x                                                                         12x 12x   12x 12x           12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x                                     12x 12x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 1x 1x 2x 1x 1x 1x 2x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x                                                                                                       1x 1x 1x 1x 1x 1x   1x 2x 2x 1x 2x 2x 1x 1x 1x   1x 2x 2x     2x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x                             1x 1x                                                         1x 1x               1x 1x                                 1x 1x               1x 1x                                                                             1x 1x                                                                                                                                           1x 1x                                                 1x 1x             1x 1x 12x 12x               12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x         1x 1x 1x           1x 1x 2x 2x 2x 1x  
import { DatePipe, NgStyle, isPlatformBrowser } from '@angular/common';
import {
  AfterViewInit,
  Component,
  ElementRef,
  HostListener,
  OnInit,
  PLATFORM_ID,
  Renderer2,
  ViewChild,
  inject,
  DOCUMENT
} from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Meta, Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { PaginationHrefDirective } from '@directives/pagination-href.directive';
import { ErrorElementComponent } from '@elements/error-element/error-element.component';
import { FooterElementComponent } from '@elements/footer-element/footer-element.component';
import { GMapDetailsComponent } from '@elements/g-map-details/g-map-details.component';
import { HeaderElementComponent } from '@elements/header-element/header-element.component';
import { TripCardElementComponent } from '@elements/trip-card-element/trip-card-element.component';
import { TripFilterElementComponent } from '@elements/trip-filter-element/trip-filter-element.component';
import { environment } from '@environments/environment';
import { AnalyticsIntegrationService } from '@services/analyticsIntegration.service';
import { MetaTagService } from '@services/meta-tag.service';
import { NetworkService } from '@services/network.service';
import { WizardService } from '@services/wizard.service';
import { BsModalRef, ModalDirective, ModalModule } from 'ngx-bootstrap/modal';
import { PageChangedEvent, PaginationModule } from 'ngx-bootstrap/pagination';
import { CookieService } from 'ngx-cookie-service';
import Swal from 'sweetalert2';
 
@Component({
	selector: 'grt-category-list-page',
	templateUrl: './category-list-page.component.html',
	styleUrl: './category-list-page.component.scss',
	providers: [DatePipe],
	imports: [
		HeaderElementComponent,
		NgStyle,
		TripFilterElementComponent,
		TripCardElementComponent,
		PaginationModule,
		ReactiveFormsModule,
		FormsModule,
		ModalModule,
		GMapDetailsComponent,
		ErrorElementComponent,
		FooterElementComponent,
		PaginationHrefDirective,
	],
})
export class CategoryListPageComponent implements OnInit, AfterViewInit {
	private meta = inject(Meta);
	private metaTag = inject(MetaTagService);
	private renderer = inject(Renderer2);
	private analyticsIntegrationService = inject(AnalyticsIntegrationService);
	private cookieService = inject(CookieService);
	titleService = inject(Title);
	route = inject(ActivatedRoute);
	network = inject(NetworkService);
	router = inject(Router);
	private platformId = inject(PLATFORM_ID);
	private document = inject<Document>(DOCUMENT);
	private datePipe = inject(DatePipe);
	private wizard = inject(WizardService);
	private MAX_DAYS = 35;
 
	@ViewChild(ModalDirective, { static: false }) modal?: ModalDirective | any;
	@ViewChild('tripSection', { static: false }) tripSection!: ElementRef;
	item = ['', '', '', '', '', '', '', '', '', ''];
	isMobile = true;
	firstTime = true;
	isSmallMobile = false;
	topTripList: any = [];
	isLoading = false;
	error = false;
	modalRef?: BsModalRef | any;
	staticModal: any;
	staticMapModal: any;
	marketingImage = [];
	interactiveMap: any;
	currentPage = 1;
	nextPage = 0;
	totalPages = 0;
	totalItems = 0;
	isBrowser = false;
	name!: string;
	description!: string;
	url!: string;
	breadcrumb!: string;
	filtersParam: any;
	showDescription: boolean = false;
	showMoreDescription: boolean = true;
	scoreIndex: any = null;
	scoreShown = false;
	filterIndex: number | null = null;
	message = '';
	breadcrumbs: any = [];
	breadcrumbLoaded: boolean = false;
	tourDetails = [];
	endDate: Date | any = null;
	date: Date = new Date();
	tripLength: number | null = null;
	citiesIds: string[] = [];
	isPreloading = false;
	isPreloaded = false;
	preloadedTrips = [];
	scrollTimeout: any = null;
	queryParams = null;
	environment = environment;
 
	@HostListener('window:resize', ['$event'])
	onResize(): void {
		if (isPlatformBrowser(this.platformId)) {
			const offsetWidth = document.body.offsetWidth;
			this.isMobile = offsetWidth < 1180;
			this.isSmallMobile = offsetWidth < 800;
		}
	}
 
	@HostListener('window:scroll')
	onScroll(): void {
		if (this.scrollTimeout) {
			clearTimeout(this.scrollTimeout);
		}

		this.scrollTimeout = setTimeout(() => {
			if (window.pageYOffset > 200) {
				if (!this.isPreloaded || this.preloadedTrips === null) {
					this.preloadNextPage();
				}
			}
		}, 500);
	}
 
	constructor() {
		this.MAX_DAYS = this.network.isAdmin ? 60 : 35;
		this.cookieService.set('lead_form_type', 'Wizard Trip List', 120, '/');
		this.cookieService.set('page_url', environment.frontendUrl + this.router.url, 120, '/');
		this.cookieService.set('marketing_trip_name', '', 120, '/');
		let utm_params: any;
 
		if (this.cookieService.check('_utm_params')) {
			utm_params = JSON.parse(this.cookieService.get('_utm_params'));
		} else {
			utm_params = {};
		}
 
		utm_params.lead_form_type = 'Wizard Trip List';
		utm_params.marketing_trip_name = '';
		utm_params.page_url = environment.frontendUrl + this.router.url;
 
		this.cookieService.set('_utm_params', JSON.stringify(utm_params), 120, '/');
		this.metaTag.removeMetaTags();
		this.titleService.setTitle('Best-Selling Vacation Packages & Top Trips for 2025/2026');
	}
 
	ngOnInit() {
		this.route.params.subscribe(() => {
			this.firstTime = true;
			this.filtersParam = null;
			this.tourDetails = [];
			this.breadcrumbs = [];
			this.getDetails();
		});
 
		if (this.isBrowser && !this.breadcrumbLoaded) {
			const existingScript = this.document.head.querySelector('script[type="application/ld+json"][data-breadcrumb]');
			if (existingScript) {
				existingScript.remove();
			}
		}
 
		if (this.isBrowser) {
			this.analyticsIntegrationService.loadScript();
		}
	}
 
	getDetails() {
		const slug = this.router?.url?.split('/')?.[2] ?? null;
 
		if (this.firstTime) {
			this.removeQueryParams();
		}
 
		this.network
			.getCategoryPageDetail(slug || 'id')
			.then((data: any) => {
				if (data?.data?.type === 'redirect' && data?.data?.attributes?.url) {
					this.router.navigateByUrl(data.data.attributes.url);
				} else {
					this.error = false;
					this.isLoading = false;
					this.name = data.data.name;
					this.description = data.data.description;
					if (this.description && this.description.length > 300) {
						this.showMoreDescription = true;
					}
					this.url = data.data['generated_url'].split('?');
					this.breadcrumb = data.data['breadcrumb_name'];
					this.tourDetails = data.data['tours'];
					const title = data.data['meta_title'] || '';
					const description = data.data['meta_description'] || '';

					this.meta.addTags(this.metaTag.getMetaTags(title, description));

					this.titleService.setTitle(`${data.data['meta_title']}`);
					this.addBreadcrumbScript();
					if (this.firstTime) {
						this.firstTime = false;
						this.topTripList = null;
						this.currentPage = 1;
						if (this.isBrowser) {
							sessionStorage.removeItem('pageNo');
							sessionStorage.setItem('pageNo', JSON.stringify(this.currentPage));
						}

						// Process URL query parameters
						this.processQueryParams(this.url[1]);

						// Fetch initial trip list
						this.fetchTripList();
					}
				}
			})
			.then(() => {
				this.updatePaginationLinks();
			})
			.catch((error) => {
				console.log(error);
				this.isLoading = false;
				setTimeout(() => {
					this.error = true;
				}, 1000);
			});
 
		if (isPlatformBrowser(this.platformId)) {
			this.isBrowser = true;
			const offsetWidth = document.body.offsetWidth;
			this.isMobile = offsetWidth < 1180;
			this.isSmallMobile = offsetWidth < 800;
		}
 
		this.route.queryParams.subscribe((queryParams) => {
			if (!this.firstTime) {
				// Check if there are query parameters
				if (Object.keys(queryParams).length > 0) {
					if (Object.keys(queryParams).length > 2) {
						this.preloadedTrips = [];
					}
					this.scoreIndex = null;
					this.currentPage = parseInt(queryParams['number']) || 1;
					if (this.isBrowser) {
						sessionStorage.removeItem('pageNo');
						sessionStorage.setItem('pageNo', JSON.stringify(this.currentPage));
					}

					// Fetch trip list with new query parameters
					this.fetchTripList(queryParams);
				} else {
					this.router.navigate(['/trips']);
				}
			}
		});
	}
 
	processQueryParams(queryString: string) {
		const filters = queryString ? queryString.split('&') : [];
		this.filtersParam = filters
			.map((data) => {
				const equalSignIndex = data.indexOf('=');
				if (equalSignIndex !== -1) {
					const key = data.slice(0, equalSignIndex);
					const valuesString = data.slice(equalSignIndex + 1);
					const cityIds = valuesString.split(',');
					return { [key]: cityIds };
				} else {
					return null;
				}
			})
			.filter((obj) => obj !== null);
 
		if (this.filtersParam.length > 0) {
			let mergedObject = {};
			this.filtersParam.forEach((obj: any) => {
				mergedObject = { ...mergedObject, ...obj };
			});
			this.filtersParam = mergedObject;
		}
	}
 
	fetchTripList(queryParams: any = this.filtersParam) {
		if (!this.preloadedTrips?.length) {
			this.network
				.getTopTripListFiltered(queryParams, true)
				.then((data: any) => {
					this.queryParams = queryParams;
					this.isLoading = false; // Turn off loading state
					this.error = false; // Reset error state
					this.nextPage = data.meta.next_page;
					this.totalPages = data.meta.total_pages;
					this.topTripList = data.data;
					this.insertTripListSchema(this.topTripList);
					this.totalItems = data.meta['total_count'];
					this.scoreIndex = null;
					this.filterIndex = null;
					this.scoreShown = false;
					data.data.some((item: any, index: number) => {
						if (item?.attributes?.score == 0) {
							this.scoreIndex = index;
							return true; // Stop iterating once scoreIndex is found
						}
						return false; // Ensure a boolean value is returned
					});
 
					data.data.map((item: any, index: number) => {
						if (this.shouldShowScore(item)) {
							this.filterIndex = index;
						}
						if (this.filterIndex === 0 && this.currentPage === 1) {
							this.message = 'No trips match all of your selected filters. The trips below match at least one filter.';

							const queryString = this.url[1];

							const extractQueryParams = (queryString: string) => {
								const queryParams = new URLSearchParams(queryString);
								return {
									cityIds: queryParams.get('cities') ? [...new Set(queryParams.get('cities')!.split(','))] : [],
									countryIds: queryParams.get('countries')?.split(',') || [],
									startingCity: queryParams.get('starting-city') || '',
									endingCity: queryParams.get('ending-city') || '',
								};
							};

							const queryParams = extractQueryParams(queryString);

							if (
								queryParams.cityIds.length > 0 ||
								queryParams.countryIds.length > 0 ||
								queryParams.startingCity ||
								queryParams.endingCity
							) {
								if (isPlatformBrowser(this.platformId)) {
									Swal.fire({
										title: '',
										text: 'We don’t have a trip matching your exact preferences but we can build it for you in 2-minutes. Ready to start?',
										icon: 'info',
										confirmButtonColor: '#ffa726',
										cancelButtonColor: '#01937a',
										showDenyButton: false,
										showCancelButton: true,
										confirmButtonText: 'Plan My Custom Trip',
										cancelButtonText: 'Closest Trip Matches',
									}).then((result) => {
										if (result.isConfirmed) {
											this.initCustomPlan();
										}
									});
								}
							} else {
								const themeIds = this.route.snapshot.queryParams['themes']?.split(',');
								localStorage.setItem('interest-id', themeIds);
							}
						} else {
							this.message =
								"There's no more trips matching all of your selected filters. The trips below match at least one filter.";
						}
					});
 
					this.marketingImage =
						data.included && data.included.filter((item: any) => item.type == 'marketing-trip-image');
					const marketingImageById: any = {};
					this.marketingImage?.forEach((tour: any) => {
						marketingImageById[tour.id] = tour;
					});
				})
				.then(() => {
					this.updatePaginationLinks();
				})
				.catch((error) => {
					console.log(error);
					this.isLoading = false;
					setTimeout(() => {
						this.error = true;
					}, 1000);
				});
		} else {
			this.preloadedTrips = []; // Clear preloaded trips
		}
	}
 
	removeQueryParams() {
		const currentUrl = this.router.url;
 
		const questionMarkIndex = currentUrl.indexOf('?');
		const baseUrl = questionMarkIndex !== -1 ? currentUrl.slice(0, questionMarkIndex) : currentUrl;
 
		const currentParams = this.route.snapshot.queryParams;
		const numberParam = currentParams['number'] ? { number: currentParams['number'] } : {};
 
		this.router.navigate([baseUrl], {
			queryParams: numberParam,
			replaceUrl: true,
		});
	}
 
	fetchData(queryParams: any) {
		console.log(queryParams);
	}
 
	favoriteSelection($event: any) {
		console.log($event);
	}
 
	favoriteRemoval($event: any) {
		console.log($event);
	}
 
	mapOpen(event: any) {
		const selectedTrip = this.topTripList.find((e: any) => e.id === event);
		if (selectedTrip && selectedTrip.attributes) {
			const { cities = [], components = [] } = selectedTrip.attributes;
			this.interactiveMap = {
				cities: cities.concat([]),
				components: components.concat([]),
			};
			this.modal.show();
		} else {
			console.error('Trip data not found for ID:', event);
		}
	}
 
	mapClose() {
		this.interactiveMap = null;
	}
 
	appendMarketingTripImageData(topTripsArray: any, marketingTripImagesArray: any) {
		topTripsArray &&
			topTripsArray?.length &&
			topTripsArray.map((topTrip: any) => {
				if (topTrip.relationships['marketing_trip_images']) {
					topTrip.relationships['marketing_trip_images'].data =
						topTrip.relationships['marketing_trip_images']?.data &&
						topTrip.relationships['marketing_trip_images']?.data?.length &&
						topTrip.relationships['marketing_trip_images']?.data.map((imageRef: any) => {
							const detailedImage = marketingTripImagesArray.find((img: any) => img.id === imageRef.id);
							return detailedImage || imageRef; // Replace the reference with detailed data if found
						});
				}
			});
	}
 
	pageChanged(event: PageChangedEvent | any): void {
		if (this.currentPage + 1 === event.page) {
			this.navigateToNextPage();
			this.currentPage = event.page;
			if (this.isBrowser) {
				sessionStorage.removeItem('pageNo');
				sessionStorage.setItem('pageNo', JSON.stringify(this.currentPage));
			}
			this.router.navigate([], {
				relativeTo: this.route,
				queryParams: { ...this.filtersParam, number: event.page },
				queryParamsHandling: 'merge',
			});
		} else {
			this.preloadedTrips = [];
			this.currentPage = event.page;
			if (this.isBrowser) {
				sessionStorage.removeItem('pageNo');
				sessionStorage.setItem('pageNo', JSON.stringify(this.currentPage));
			}
			this.router.navigate([], {
				relativeTo: this.route,
				queryParams: { ...this.filtersParam, number: event.page },
				queryParamsHandling: 'merge',
			});
		}
		this.updatePaginationLinks();
		this.isPreloaded = false;
	}
 
	shouldShowScore(i: any): any {
		if (!this.scoreShown && i.attributes?.score !== i.attributes['total-score'] && i.attributes?.score !== 0) {
			this.scoreShown = true;
			return true;
		} else {
			return false;
		}
	}
 
	private addBreadcrumbScript(): void {
		this.breadcrumbLoaded = true;
		const breadcrumbJsonLd = this.buildBreadcrumbJsonLd();

		// Remove existing breadcrumb script (by marker)
		const existingScript = this.document.head.querySelector('script[type="application/ld+json"][data-breadcrumb]');
		if (existingScript) {
			this.renderer.removeChild(this.document.head, existingScript);
		}

		// Create and append new breadcrumb JSON-LD
		const script = this.renderer.createElement('script');
		script.type = 'application/ld+json';
		script.setAttribute('data-breadcrumb', 'true'); // Identify it later for cleanup
		script.text = JSON.stringify(breadcrumbJsonLd);
		this.renderer.appendChild(this.document.head, script);
	}
 
	private buildBreadcrumbJsonLd(): any {
		const breadcrumbs = this.createBreadcrumbs();
		return {
			'@context': 'https://schema.org',
			'@type': 'BreadcrumbList',
			itemListElement: breadcrumbs,
		};
	}
 
	private createBreadcrumbs(): any[] {
		// Always reset breadcrumbs before building
		this.breadcrumbs = [];

		this.breadcrumbs.push({
			'@type': 'ListItem',
			position: 1,
			name: 'Home',
			item: environment.frontendUrl + '/',
		});

		this.breadcrumbs.push({
			'@type': 'ListItem',
			position: 2,
			name: 'All Tours',
			item: environment.frontendUrl + `/tours`,
		});

		let positionCounter = 3;

		if (this.tourDetails?.[0]?.['country-name'] !== this.breadcrumb) {
			this.tourDetails?.forEach((tour: any) => {
				this.breadcrumbs.push({
					'@type': 'ListItem',
					position: positionCounter,
					name: tour['country-name'],
					item: environment.frontendUrl + `/tours/${tour['country-tours-slugs']}`,
				});
				positionCounter++;
			});
		}

		this.breadcrumbs.push({
			'@type': 'ListItem',
			position: positionCounter,
			name: this.breadcrumb,
		});
		return this.breadcrumbs;
	}
 
	initCustomPlan() {
		let cityIds = this.route.snapshot.queryParams['cities']?.split(',') || [];
		const themeIds = this.route.snapshot.queryParams['themes']?.split(',');
		const startingCity = this.route.snapshot.queryParams['starting-city'];
		const endingCity = this.route.snapshot.queryParams['ending-city'];

		// Extract and parse additional query parameters from generated URL
		const extractQueryParams = (queryString: string) => {
			const queryParams = new URLSearchParams(queryString);
			return {
				cityIds: queryParams.get('cities')?.split(',') || [],
				startingCity: queryParams.get('starting-city') || '',
				endingCity: queryParams.get('ending-city') || '',
			};
		};

		const additionalParams = extractQueryParams(this.url[1]);

		cityIds.push(
			...additionalParams.cityIds,
			startingCity,
			endingCity,
			additionalParams.startingCity,
			additionalParams.endingCity,
		);
		// filtering out any falsy values (null, undefined, or empty strings).
		cityIds = [...new Set(cityIds.filter(Boolean))];

		if (cityIds.length > 0) {
			this.endDate = new Date(+this.date);
			this.endDate.setDate(this.endDate.getDate() + 4);
			this.wizard.mintriplength(cityIds, cityIds[0], cityIds[0]).then((response) => {
				const arrive = new Date();
				arrive.setDate(arrive.getDate() + 60);
				const leave = new Date(arrive);
				leave.setDate(arrive.getDate() + Math.min(Math.floor(response['min-trip-length'] || 0 * 1.5), this.MAX_DAYS));
				const departDay = this.datePipe.transform(leave, 'yyyy-MM-dd');

				const data = {
					id: '',
					'city-ids': cityIds,
					'interest-ids': themeIds,
					'arrive-city-id': startingCity || '',
					'depart-city-id': endingCity || '',
					'arrive-day': this.datePipe.transform(arrive, 'yyyy-MM-dd'),
					'depart-day': departDay,
					'hotel-occupancy-rooms': [],
					'hotel-occupancy-rooms-count': 0,
					'user-agent': '',
					'hotel-requested-stars': 3,
				};

				this.wizard
					.createWizard(data)
					.then(() => {
						this.router.navigate(['/trip-planner'], {
							queryParams: { path: 'triplist' },
						});
					})
					.catch((error) => {
						console.error(error);
					});
			});
		} else {
			localStorage.setItem('interest-id', themeIds?.join(',') || '');
			this.router.navigate(['/trip-planner'], {
				queryParams: { path: 'triplist' },
			});
		}
	}
 
	preloadNextPage(): void {
		if (this.currentPage < this.totalPages) {
			this.isPreloading = true;
			this.isPreloaded = true;
			const nextPage = this.currentPage + 1;
			if (nextPage > 2) {
				this.queryParams = null;
			}
			if (nextPage !== null) {
				this.network
					.getTopTripListFiltered(
						{ ...this.route.snapshot.queryParams, ...(this.queryParams || {}), number: nextPage },
						true,
					)
					.then((data: any) => {
						this.preloadedTrips = data.data; // Store preloaded trips separately
						this.isPreloading = false;
					})
					.catch((error) => {
						console.error('Error preloading next page:', error);
						this.isPreloading = false;
					});
			}
		}
	}
 
	navigateToNextPage(): void {
		if (this.preloadedTrips?.length > 0) {
			this.topTripList = this.preloadedTrips;
			this.insertTripListSchema(this.topTripList);
			this.isLoading = false;
		}
	}
 
	ngAfterViewInit() {
		if (isPlatformBrowser(this.platformId)) {
			setTimeout(() => {
				if (
					this.tripSection &&
					this.tripSection.nativeElement &&
					typeof this.tripSection.nativeElement.scrollIntoView === 'function'
				) {
					this.tripSection.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
				}
			});
		}
	}
 
	private insertTripListSchema(trips: any[]): void {
		if (!isPlatformBrowser(this.platformId)) return; // ⛔ Exit if not browser
 
		const existingScripts = this.document.head.querySelectorAll(
			'script[type="application/ld+json"][data-schema="trip-list"]',
		);
		existingScripts.forEach((script) => this.renderer.removeChild(this.document.head, script));
 
		const itemListSchema = {
			'@context': 'https://schema.org',
			'@type': 'ItemList',
			name: 'Best-Selling Vacation Packages & Top Trips for 2025/2026',
			description:
				'Explore our most popular itineraries across Europe. Discover top destinations for 2025 and 2026, all customizable.',
			itemListElement: trips.map((trip, index) => {
				const data = trip.attributes['marketing-trip-image'];
				const data2 = trip.attributes['marketing-trip-image']['img-url'];
				const mainImage = data && data.length ? data : data2;
				return {
					'@type': 'ListItem',
					position: index + 1,
					item: {
						'@type': 'Trip',
						name: trip.attributes['marketing-trip-name'],
						url: `${environment.frontendUrl}/trips/${trip.attributes.slug}`,
						image: mainImage || '',
						description: trip?.attributes['marketing-summary'] || '',
					},
				};
			}),
		};
 
		const script = this.renderer.createElement('script');
		script.type = 'application/ld+json';
		script.setAttribute('data-schema', 'trip-list');
		script.text = JSON.stringify(itemListSchema);
		this.renderer.appendChild(this.document.head, script);
	}
 
	private serializeQueryParams(params: { [key: string]: any }): string {
		return Object.entries(params)
			.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
			.join('&');
	}
 
	private updatePaginationLinks(): void {
		const totalPages = this.totalPages || 1;
		const currentUrl = this.router.url.split('?')[0];
		const queryParams = { ...this.route.snapshot.queryParams };
 
		this.removeLink('prev');
		this.removeLink('next');
 
		if (this.currentPage > 1) {
			queryParams['number'] = this.currentPage - 1;
			const prevUrl = `${environment.frontendUrl}${currentUrl}?${this.serializeQueryParams(queryParams)}`;
			this.addLink('prev', prevUrl);
		}
 
		if (this.currentPage < totalPages) {
			queryParams['number'] = this.currentPage + 1;
			const nextUrl = `${environment.frontendUrl}${currentUrl}?${this.serializeQueryParams(queryParams)}`;
			this.addLink('next', nextUrl);
		}
	}
 
	private addLink(rel: string, href: string): void {
		const link = this.document.createElement('link');
		link.setAttribute('rel', rel);
		link.setAttribute('href', href);
		this.document.head.appendChild(link);
	}
 
	private removeLink(rel: string): void {
		const links = this.document.querySelectorAll(`link[rel="${rel}"]`);
		links.forEach((link) => link.remove());
	}
}