All files / app/elements/chat-widget chat-widget.component.ts

40.86% Statements 123/301
66.66% Branches 2/3
8.33% Functions 2/24
40.86% Lines 123/301

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 3021x 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 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x     7x 7x 7x           7x 7x                       7x 7x                     7x 7x         7x 7x     7x 7x                       7x 7x         7x 7x                                               7x 7x                 7x 7x                       7x 7x                                                     7x 7x       7x 7x     7x 7x       7x 7x                   7x 7x                       7x 7x     7x 7x                             7x 7x                   7x 7x     7x 7x 7x     7x 7x         7x  
import { animate, style, transition, trigger } from '@angular/animations';
import { CommonModule } from '@angular/common';
import {
	AfterViewChecked,
	Component,
	ElementRef,
	inject,
	OnDestroy,
	OnInit,
	Renderer2,
	ViewChild,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ChatService } from '@services/chat.service';
import { v4 as uuidv4 } from 'uuid';
import { MarkdownPipe } from '../../pipes/markdown.pipe';
 
interface ChatMessage {
	id: string;
	sender: 'user' | 'bot';
	text: string;
	timestamp: Date;
}
 
@Component({
	selector: 'grt-chat-widget',
	templateUrl: './chat-widget.component.html',
	styleUrl: './chat-widget.component.scss',
	imports: [FormsModule, CommonModule, MarkdownPipe],
	animations: [
		trigger('messageAnimation', [
			transition(':enter', [
				style({ opacity: 0, transform: 'translateY(10px)' }),
				animate('300ms ease-out', style({ opacity: 1, transform: 'translateY(0)' })),
			]),
		]),
		trigger('popoverAnimation', [
			transition(':enter', [
				style({ opacity: 0, transform: 'translateY(10px) scale(0.9)' }),
				animate('400ms cubic-bezier(0.4, 0, 0.2, 1)', style({ opacity: 1, transform: 'translateY(0) scale(1)' })),
			]),
			transition(':leave', [animate('200ms ease-in', style({ opacity: 0, transform: 'translateY(10px) scale(0.9)' }))]),
		]),
	],
})
export class ChatWidgetComponent implements AfterViewChecked, OnDestroy, OnInit {
	@ViewChild('chatBody') private chatBody!: ElementRef;
	@ViewChild('messageInput') private messageInput!: ElementRef;
 
	private readonly STORAGE_KEY = 'grt_chat_state';
 
	isOpen = false;
	isLoading = false;
	messages: ChatMessage[] = [];
	input = '';
	unreadCount = 0;
	sessionId = uuidv4();
	hide = false;
 
	// Support selection
	showSupportOptions = true;
	selectedSupport: 'ai' | 'hubspot' | null = null;
 
	// Popover state
	showPopover = true;
	popoverMessage = 'Hi! Need help planning your dream trip? 🌍';
	private popoverTimer: any;
 
	private chatService = inject(ChatService);
	private renderer = inject(Renderer2);
	private shouldScrollToBottom = false;
	private hubspotScriptLoaded = false;
 
	ngOnDestroy() {
		// Clean up timer
		if (this.popoverTimer) {
			clearTimeout(this.popoverTimer);
		}
	}
 
	ngAfterViewChecked() {
		if (this.shouldScrollToBottom) {
			this.scrollToBottom();
			this.shouldScrollToBottom = false;
		}
	}
 
	toggleChat(): void {
		this.isOpen = !this.isOpen;

		if (this.isOpen) {
			this.showPopover = false;
			this.unreadCount = 0;

			if (this.selectedSupport === 'ai') {
				setTimeout(() => this.messageInput?.nativeElement?.focus(), 300);
			}
		}
	}
 
	private persistChatState(): void {
		sessionStorage.setItem(
			this.STORAGE_KEY,
			JSON.stringify({
				messages: this.messages,
				sessionId: this.sessionId,
				selectedSupport: this.selectedSupport,
				showSupportOptions: this.showSupportOptions,
			}),
		);
	}
 
	goBackToSupportOptions(): void {
		this.selectedSupport = null;
		this.showSupportOptions = true;
		this.persistChatState();
	}
 
	closePopover(): void {
		this.showPopover = false;
	}
 
	selectAIAssistant(): void {
		this.selectedSupport = 'ai';
		this.showSupportOptions = false;

		// Send welcome message
		if (this.messages?.length > 0) return;
		setTimeout(() => {
			this.addBotMessage(
				'Welcome to Go Real Travel! I can help you plan a new trip, connect you to support if you have already booked a trip with us, and share information about our destinations.',
			);
		}, 300);
	}
 
	selectHubSpot(): void {
		this.selectedSupport = 'hubspot';
		this.showSupportOptions = false;
		this.loadHubSpotScript();
	}
 
	private loadHubSpotScript(): void {
		if (this.hubspotScriptLoaded) {
			(window as any).HubSpotConversations.widget.load();
			this.openHubSpotChat();
			return;
		}

		const script = this.renderer.createElement('script');
		script.type = 'text/javascript';
		script.src = '//js-eu1.hs-scripts.com/139818938.js';
		script.id = 'hs-script-loader';
		script.async = true;
		script.defer = true;

		script.onload = () => {
			this.hubspotScriptLoaded = true;
			// Wait for HubSpot widget to initialize
			setTimeout(() => {
				this.openHubSpotChat();
			}, 1000);
		};

		this.renderer.appendChild(document.head, script);
	}
 
	private openHubSpotChat(): void {
		// Try to open HubSpot chat widget
		if ((window as any).HubSpotConversations) {
			(window as any).HubSpotConversations.widget.open();
			// Close our widget since HubSpot has its own
			this.hide = true;
			this.toggleChat();
		}
	}
 
	closeHubSpotAndGoBack(): void {
		// Close HubSpot widget if it's open
		if ((window as any).HubSpotConversations) {
			(window as any).HubSpotConversations.widget.close();
		}

		// Show our widget again and go back to support options
		this.hide = false;
		this.isOpen = true;
		this.selectAIAssistant();
		this.persistChatState();
	}
 
	sendMessage(): void {
		if (!this.input.trim() || this.isLoading) return;

		const userMessage = this.input.trim();

		// Add user message to UI
		this.addUserMessage(userMessage);

		// Clear input
		this.input = '';

		// Set loading state
		this.isLoading = true;

		// Call API
		this.chatService.sendMessage(userMessage).subscribe({
			next: (res) => {
				this.isLoading = false;
				this.addBotMessage(res?.agent_output || '');
			},
			error: (error) => {
				console.error('Chat error:', error);
				this.isLoading = false;
				this.addBotMessage('Something went wrong. Please try again.');
			},
		});
	}
 
	sendQuickMessage(message: string): void {
		this.input = message;
		this.sendMessage();
	}
 
	onInputChange(): void {
		// Can be used for typing indicators or real-time features
	}
 
	handleAttachment(): void {
		// Implement file attachment if needed
		console.log('Attachment feature - coming soon!');
	}
 
	private addUserMessage(text: string): void {
		this.messages.push({
			id: this.generateId(),
			text,
			sender: 'user',
			timestamp: new Date(),
		});
		this.shouldScrollToBottom = true;
		this.persistChatState();
	}
 
	private addBotMessage(text: string): void {
		this.messages.push({
			id: this.generateId(),
			text,
			sender: 'bot',
			timestamp: new Date(),
		});
		this.shouldScrollToBottom = true;
		this.persistChatState();

		if (!this.isOpen) this.unreadCount++;
	}
 
	ngOnInit(): void {
		this.restoreChatState();
	}
 
	private restoreChatState(): void {
		if (globalThis.window) {
			const raw = globalThis.window.sessionStorage.getItem(this.STORAGE_KEY);
			if (!raw) return;
			try {
				const state = JSON.parse(raw);
				this.messages = state.messages || [];
				this.sessionId = state.sessionId || this.sessionId;
				this.selectedSupport = state.selectedSupport;
				this.showSupportOptions = state.showSupportOptions ?? true;
			} catch {
				sessionStorage.removeItem(this.STORAGE_KEY);
			}
		}
	}
 
	private scrollToBottom(): void {
		try {
			if (this.chatBody) {
				const element = this.chatBody.nativeElement;
				element.scrollTop = element.scrollHeight;
			}
		} catch (err) {
			console.error('Error scrolling to bottom:', err);
		}
	}
 
	private generateId(): string {
		return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
	}
 
	// Getter for typing indicator display
	get isTyping(): boolean {
		return this.isLoading;
	}
 
	hideHubspot() {
		if ((window as any).HubSpotConversations) {
			(window as any).HubSpotConversations.widget.remove();
		}
	}
}