File size: 12,113 Bytes
2e9afea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// --- Mock Knowledge Base for MANIT Bhopal ---
const KNOWLEDGE_BASE = [
    {
        keywords: /\b(hi|hello|hey|greetings|greet|who are you|about)\b/i,
        response: `<span class="academic-heading">Welcome to MANIT Chat</span>
I am your minimalist academic assistant. I can provide detailed insights about Maulana Azad National Institute of Technology (MANIT), Bhopal. 

Try asking me about:
• <strong style="font-weight:600;">Placements</strong> (packages, recruiters)
• <strong style="font-weight:600;">Hostels</strong> (facilities, rooms)
• <strong style="font-weight:600;">Departments</strong> (branches, courses)
• <strong style="font-weight:600;">Campus Life</strong> (sports, library)`
    },
    {
        keywords: /\b(placement|recruit|job|salary|lpa|package|hire|hiring)\b/i,
        response: `<span class="academic-heading">Campus Placements</span>
MANIT Bhopal is recognized for its outstanding placement performance across all engineering and planning branches. 

• <strong style="font-weight:600;">Top Recruiters</strong>: Tech giants and core enterprises visit annually, including Google, Amazon, Microsoft, Goldman Sachs, BPCL, Bajaj Auto, and Tata Motors.
• <strong style="font-weight:600;">Computer Science (CSE)</strong>: Average package ranges between <strong style="font-weight:600;">15 to 20 LPA</strong>, with placement rates consistently near 95-100%.
• <strong style="font-weight:600;">Overall Average Package</strong>: Approximately <strong style="font-weight:600;">9.5 to 11.5 LPA</strong> across all branches.
• <strong style="font-weight:600;">Highest Package</strong>: Has touched <strong style="font-weight:600;">82 LPA</strong> in recent recruitment cycles.`
    },
    {
        keywords: /\b(admis|cutoff|josaa|csab|jee|entrance|rank|how to get in|apply)\b/i,
        response: `<span class="academic-heading">Admission Guidelines</span>
Entry into MANIT Bhopal is highly competitive and strictly merit-based:

• <strong style="font-weight:600;">B.Tech & B.Arch</strong>: Admission is purely through the <strong style="font-weight:600;">JEE Main</strong> examination. Final allocation is conducted via <strong style="font-weight:600;">JoSAA</strong> (Joint Seat Allocation Authority) or <strong style="font-weight:600;">CSAB</strong> counselling.
• <strong style="font-weight:600;">M.Tech & M.Plan</strong>: Candidates must possess a valid <strong style="font-weight:600;">GATE</strong> score and register through the <strong style="font-weight:600;">CCMT</strong> central portal.
• <strong style="font-weight:600;">MCA Program</strong>: Admission is granted based on ranks secured in the national-level <strong style="font-weight:600;">NIMCET</strong> exam.
• <strong style="font-weight:600;">MBA & Ph.D.</strong>: Determined via national exam scores (CAT/MAT) followed by institute level interviews.`
    },
    {
        keywords: /\b(hostel|room|mess|accommodation|living|dining|canteen)\b/i,
        response: `<span class="academic-heading">Residential Hostels</span>
MANIT Bhopal features a fully residential campus layout with <strong style="font-weight:600;">10 Hostels</strong>:

• <strong style="font-weight:600;">Male Accommodation</strong>: Hostels 1 to 6 and Hostel 8 cater to male students, with shared rooms for juniors and single rooms allocated to seniors.
• <strong style="font-weight:600;">Female Accommodation</strong>: Hostels 7 and 10 are girls' hostels. Hostel 10 is a modern, high-capacity, multi-story building featuring strict 24/7 security.
• <strong style="font-weight:600;">International Students</strong>: Hostel 9 is dedicated to international DASA students and research scholars.
• <strong style="font-weight:600;">Amenities</strong>: Each hostel houses its own cooperative mess, table tennis/badminton courts, high-speed Wi-Fi, and laundry provisions.`
    },
    {
        keywords: /\b(department|branch|course|cse|ece|mech|civil|chemical|meta|bio|architecture|study|degree)\b/i,
        response: `<span class="academic-heading">Academic Departments</span>
MANIT Bhopal offers academic coursework across several engineering and allied disciplines:

• <strong style="font-weight:600;">Engineering Branches</strong>: Computer Science, Electronics & Communication, Electrical, Mechanical, Civil, Chemical, and Materials & Metallurgical Engineering.
• <strong style="font-weight:600;">Sciences</strong>: Biological Science & Bioinformatics, Physics, Chemistry, and Mathematics.
• <strong style="font-weight:600;">Architecture</strong>: The prestigious Department of Architecture & Planning is regularly ranked among the top architecture programs in India.`
    },
    {
        keywords: /\b(facility|library|sports|campus|wifi|gym|medical|dispensary|lake)\b/i,
        response: `<span class="academic-heading">Campus & Infrastructure</span>
Spread across a lush 650-acre campus, MANIT provides high-grade amenities:

• <strong style="font-weight:600;">Central Library</strong>: Stacks more than 120,000 text volumes and gives students licensing to electronic databases like IEEE Xplore, ScienceDirect, and Springer.
• <strong style="font-weight:600;">Sports Complex</strong>: Features a cricket ground, football fields, running tracks, an indoor gym, and basketball, volleyball, and tennis courts.
• <strong style="font-weight:600;">Medical Dispensary</strong>: Offers round-the-clock medical care, basic triage, and free medicine distribution with an on-site ambulance.`
    },
    {
        keywords: /\b(contact|location|where|address|phone|email|map|reach|city|station|airport)\b/i,
        response: `<span class="academic-heading">Location & Contacts</span>
MANIT is located in the central, scenic highlands of Bhopal:

• <strong style="font-weight:600;">Address</strong>: Link Road No. 3, Near Kaliyasot Dam, Bhopal, Madhya Pradesh, India - 462003.
• <strong style="font-weight:600;">Transit Proximity</strong>:
  - Bhopal Junction Railway Station: ~10 km
  - Rani Kamlapati (Habibganj) Station: ~6 km
  - Raja Bhoj Airport (BHO): ~20 km
• <strong style="font-weight:600;">General Email</strong>: pro@manit.ac.in
• <strong style="font-weight:600;">Web Portal</strong>: www.manit.ac.in`
    }
];

// --- Fallback Response ---
const DEFAULT_RESPONSE = `<span class="academic-heading">Search Query Processed</span>
I couldn't locate details matching those specific terms. However, you can find exhaustive resources on the official <strong style="font-weight:600;">MANIT Bhopal Portal</strong> (www.manit.ac.in).

Alternatively, try asking about:
• Placement statistics or top recruiters
• Hostels, mess facilities, or campus size
• Academic departments (CSE, ECE, Architecture)`;

// --- DOM Elements ---
const chatForm = document.getElementById('chat-form');
const chatInput = document.getElementById('chat-input');
const sendButton = document.getElementById('send-button');
const chatArea = document.getElementById('chat-area');
const chatWrapper = document.getElementById('chat-wrapper');

// --- Input Visual States ---
chatInput.addEventListener('input', () => {
    if (chatInput.value.trim().length > 0) {
        sendButton.classList.add('active');
    } else {
        sendButton.classList.remove('active');
    }
});

// --- Chat Core Controls ---
chatForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const queryText = chatInput.value.trim();
    if (!queryText) return;

    // Reset Input
    chatInput.value = '';
    sendButton.classList.remove('active');

    // Add User Message
    addUserMessage(queryText);

    // Disable input while bot processing
    toggleInputState(true);

    // Show Custom Loading State
    showLoadingState(async (loadingBubble, clearLoadingTimer) => {
        // Formulate Response
        const backendData = await getBotResponse(queryText);
        // 2. Kill the loading animation the exact millisecond the server responds
        clearLoadingTimer();
        loadingBubble.remove();

        const message= backendData.reply? backendData.reply: backendData
        const parsedHTML = marked.parse(message, { breaks: true });
        addBotMessage(parsedHTML);
    });
});

// --- UI Helpers ---

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

function toggleInputState(disabled) {
    chatInput.disabled = disabled;
    sendButton.disabled = disabled;
    if (disabled) {
        chatInput.blur();
    } else {
        chatInput.focus();
    }
}

function addUserMessage(text) {
    const msgDiv = document.createElement('div');
    msgDiv.className = 'message user-message';
    msgDiv.innerHTML = `<div class="message-content"></div>`;
    msgDiv.querySelector('.message-content').textContent = text;
    chatWrapper.appendChild(msgDiv);
    scrollToBottom();
}

/**
 * Creates and cycles loading text phrases
 */
function showLoadingState(callback) {
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'loading-bubble';
    loadingDiv.innerHTML = `
        <div class="loading-dots">
            <span class="loading-dot"></span>
            <span class="loading-dot"></span>
            <span class="loading-dot"></span>
        </div>
        <span class="loading-text-span" id="loading-text-span">Thinking...</span>
    `;
    chatWrapper.appendChild(loadingDiv);
    scrollToBottom();

    const loadingTextSpan = loadingDiv.querySelector('#loading-text-span');
    const phrases = ["Thinking...", "Searching MANIT Database...", "Processing Query..."];
    let phraseIndex = 0;

    // Cycle text phrase with visual fade
    const cycleInterval = setInterval(() => {
        loadingTextSpan.classList.add('fade-out');
        
        // Wait for CSS transition to fade out (300ms) before updating text and fading back in
        setTimeout(() => {
            phraseIndex = (phraseIndex + 1) % phrases.length;
            loadingTextSpan.textContent = phrases[phraseIndex];
            loadingTextSpan.classList.remove('fade-out');
        }, 300);

    }, 1200);

    // Provide the DOM node and a cleanup callback
    const clearLoadingTimer = () => {
        clearInterval(cycleInterval);
    };

    callback(loadingDiv, clearLoadingTimer);
}

/**
 * Maps input queries to responses in the database
 */
async function getBotResponse(user_query) {
    try{
        // Connect to port 8000 if opened as a local file or viewed on Live Preview (port 3000)
        const isDevEnv = window.location.protocol === 'file:' || window.location.port === '3000';
        const apiBaseUrl = isDevEnv ? 'http://127.0.0.1:8000' : '';
        const response= await fetch(`${apiBaseUrl}/chat`,{
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({query:user_query})
        })
        // 1. THE FIX: Catch server errors BEFORE parsing JSON
        if (!response.ok) {
            // Read the raw text (which will be your 401 Unauthorized message)
            const errorText = await response.text(); 
            console.error(`Backend Error (${response.status}):`, errorText);
            
            // Return a safe fallback dictionary so your UI doesn't crash
            return { reply: `Connection error: Server returned ${response.status}. Please check backend logs.` };
        }

        const data= await response.json()
        return data
    }

    catch(err){
        console.log("error in recieving output from server: ",err)
        return { reply: DEFAULT_RESPONSE };
    }
}

/**
 * Adds bot response directly and instantly to the chat area.
 */
function addBotMessage(htmlContent) {
    // Create container bubble
    const msgDiv = document.createElement('div');
    msgDiv.className = 'message bot-message';
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    contentDiv.innerHTML = htmlContent;
    msgDiv.appendChild(contentDiv);
    
    chatWrapper.appendChild(msgDiv);
    scrollToBottom();

    // Instantly restore user input state
    toggleInputState(false);
}