File size: 7,950 Bytes
f1df910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1ff6f4
 
 
76ab121
 
f1ff6f4
 
 
f1df910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1ff6f4
 
 
 
 
76ab121
f1ff6f4
 
 
f1df910
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
document.addEventListener('DOMContentLoaded', () => {
    // ================= DOM ELEMENTS =================
    const screens = {
        home: document.getElementById('home-screen'),
        loading: document.getElementById('loading-screen'),
        chat: document.getElementById('chat-screen')
    };

    // Inputs
    const nickInput = document.getElementById('input-nick');
    const interestsInput = document.getElementById('input-interests');
    const chatInput = document.getElementById('chat-input');

    // Buttons
    const startBtn = document.getElementById('start-btn');
    const cancelSearchBtn = document.getElementById('cancel-search-btn');
    const skipBtn = document.getElementById('skip-btn');
    const sendBtn = document.getElementById('send-btn');

    // Display Areas
    const messageLog = document.getElementById('messagelog');
    const partnerNameDisplay = document.getElementById('partner-name');
    const partnerStatusDisplay = document.getElementById('partner-status');
    const loadingStatus = document.getElementById('loading-status');

    // ================= STATE =================
    let socket = null;
    let isConnected = false;
    let typingTimeout = null;

    // ================= NAVIGATION =================
    function showScreen(screenName) {
        Object.values(screens).forEach(s => s.classList.remove('active'));
        screens[screenName].classList.add('active');
    }

    // ================= WEBSOCKET LOGIC =================
    function connect() {
        if (socket) {
            socket.close();
        }

        const nick = nickInput.value.trim() || "Stranger";
        const interests = interestsInput.value.trim();
        const clientId = Math.random().toString(36).substring(7);

        const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        // Encode query params
        const url = `${proto}//${window.location.host}/ws/${clientId}?nick=${encodeURIComponent(nick)}&interests=${encodeURIComponent(interests)}`;

        socket = new WebSocket(url);

        socket.onopen = () => {
            console.log("Connected to server");
            loadingStatus.textContent = "Looking for a match...";
        };

        socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            handleMessage(data);
        };

        socket.onclose = () => {
            console.log("Disconnected");
            isConnected = false;
            updatePartnerStatus("Disconnected", "offline");
        };

        socket.onerror = (err) => {
            console.error("WebSocket Error:", err);
            loadingStatus.textContent = "Connection Error. Retrying...";
        };
    }

    function handleMessage(data) {
        switch (data.type) {
            case 'connected':
                isConnected = true;
                partnerNameDisplay.textContent = data.partner;
                updatePartnerStatus("Online", "online");
                messageLog.innerHTML = ''; // Clear chat
                addSystemMessage(`You are talking to ${data.partner}. Say Hi!`);
                showScreen('chat');
                break;

            case 'waiting':
                showScreen('loading');
                loadingStatus.textContent = data.message || "Searching...";
                break;

            case 'message':
                addMessage(data.content, 'stranger', data.sender);
                // Clear typing indicator if message received
                updatePartnerStatus("Online", "online");
                break;

            case 'partner_disconnected':
                isConnected = false;
                updatePartnerStatus("Stranger Disconnected", "offline");
                addSystemMessage("Partner disconnected. Press ESC to find new.");
                break;

            case 'typing':
                if (data.state) {
                    updatePartnerStatus("Typing...", "typing");
                } else {
                    updatePartnerStatus("Online", "online");
                }
                break;
        }
    }

    function sendMessage() {
        const content = chatInput.value.trim();

        const urlPattern = /(https?:\/\/[^\s]+)|(www\.[^\s]+)|(\b[a-zA-Z0-9-]+\.[a-zA-Z]{2,}\b)/i;
        if (urlPattern.test(content)) {
            addSystemMessage("⚠ URLs are not allowed.");
            chatInput.value = '';
            return;
        }

        if (content && isConnected) {
            socket.send(JSON.stringify({ type: 'message', content: content }));
            addMessage(content, 'user');
            chatInput.value = '';
        }
    }

    function skip() {
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify({ type: 'skip' }));
            showScreen('loading');
            loadingStatus.textContent = "Skipping... finding new match";
            messageLog.innerHTML = '';
        } else {
            // Reconnect if socket closed
            connect();
            showScreen('loading');
        }
    }

    // ================= UI HELPERS =================
    function addMessage(text, type, senderName = null) {
        const div = document.createElement('div');
        div.className = `message ${type}`;

        // Allow HTML for bolding names in group chat
        if (senderName && type === 'stranger' && text.includes('<b>')) {
            div.innerHTML = text;
        } else {
            div.textContent = text;
        }

        messageLog.appendChild(div);
        scrollToBottom();
    }

    function addSystemMessage(text) {
        const div = document.createElement('div');
        div.className = 'system-message';
        div.textContent = text;
        messageLog.appendChild(div);
        scrollToBottom();
    }

    function scrollToBottom() {
        messageLog.scrollTop = messageLog.scrollHeight;
    }

    function updatePartnerStatus(text, state) {
        partnerStatusDisplay.textContent = text;

        // Visual indicator could be added here
        if (state === 'typing') {
            partnerStatusDisplay.style.color = 'var(--primary)';
        } else if (state === 'offline') {
            partnerStatusDisplay.style.color = 'var(--danger)';
        } else {
            partnerStatusDisplay.style.color = 'var(--primary)';
        }
    }

    // ================= EVENTS =================
    startBtn.addEventListener('click', () => {
        showScreen('loading');
        connect();
    });

    cancelSearchBtn.addEventListener('click', () => {
        if (socket) socket.close();
        showScreen('home');
    });

    sendBtn.addEventListener('click', sendMessage);

    chatInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    chatInput.addEventListener('paste', (e) => {
        const pastedText = (e.clipboardData || window.clipboardData).getData('text');
        const urlPattern = /(https?:\/\/[^\s]+)|(www\.[^\s]+)|(\b[a-zA-Z0-9-]+\.[a-zA-Z]{2,}\b)/i;
        if (urlPattern.test(pastedText)) {
            e.preventDefault();
            addSystemMessage("⚠ URLs are not allowed.");
        }
    });

    // Typing Indicator Logic
    chatInput.addEventListener('input', () => {
        if (!isConnected) return;

        // Send typing ON
        socket.send(JSON.stringify({ type: 'typing', state: true }));

        // Debounce typing OFF
        clearTimeout(typingTimeout);
        typingTimeout = setTimeout(() => {
            if (isConnected) {
                socket.send(JSON.stringify({ type: 'typing', state: false }));
            }
        }, 1000); // 1 second after stop typing
    });

    skipBtn.addEventListener('click', skip);

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            if (screens.chat.classList.contains('active')) {
                skip();
            }
        }
    });
});