AI / chat.html
Moncey10's picture
Update chat.html
caf05d9 verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>New Age β€” Internal AI Support</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #F5F4F0;
--surface: #FFFFFF;
--surface-2: #F0EEE9;
--border: #E2E0DA;
--border-strong:#C8C6BF;
--text: #1A1916;
--muted: #6B6A65;
--hint: #9E9C97;
--accent: #1A1916;
--accent-fg: #FFFFFF;
--user-bubble: #1A1916;
--user-fg: #FFFFFF;
--bot-bubble: #FFFFFF;
--bot-fg: #1A1916;
--radius: 12px;
--radius-sm: 8px;
--radius-xs: 6px;
--shadow: 0 1px 3px rgba(0,0,0,0.06), 0 4px 16px rgba(0,0,0,0.06);
}
body {
font-family: 'DM Sans', sans-serif;
background: var(--bg);
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
/* ── Top navbar ── */
.navbar {
background: var(--surface);
border-bottom: 1px solid var(--border);
padding: 0 1.5rem;
height: 56px;
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
z-index: 10;
}
.navbar-left {
display: flex;
align-items: center;
gap: 12px;
}
.logo-mark {
width: 32px;
height: 32px;
background: var(--accent);
border-radius: var(--radius-xs);
display: flex;
align-items: center;
justify-content: center;
}
.logo-mark svg {
width: 17px;
height: 17px;
stroke: #fff;
fill: none;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.brand-name {
font-size: 0.9375rem;
font-weight: 600;
color: var(--text);
letter-spacing: -0.01em;
}
.brand-tag {
font-size: 0.75rem;
color: var(--hint);
font-weight: 400;
margin-left: 2px;
}
.navbar-right {
display: flex;
align-items: center;
gap: 8px;
}
.nav-btn {
height: 32px;
padding: 0 12px;
border: 1px solid var(--border);
border-radius: var(--radius-xs);
background: none;
font-family: 'DM Sans', sans-serif;
font-size: 0.8125rem;
color: var(--muted);
cursor: pointer;
display: flex;
align-items: center;
gap: 6px;
transition: border-color 0.15s, color 0.15s;
}
.nav-btn:hover { border-color: var(--border-strong); color: var(--text); }
.nav-btn svg {
width: 14px;
height: 14px;
stroke: currentColor;
fill: none;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.user-pill {
height: 32px;
padding: 0 10px;
background: var(--surface-2);
border: 1px solid var(--border);
border-radius: 99px;
display: flex;
align-items: center;
gap: 7px;
font-size: 0.8125rem;
color: var(--text);
font-weight: 500;
}
.avatar {
width: 20px;
height: 20px;
background: var(--accent);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.625rem;
color: #fff;
font-weight: 600;
}
/* ── Main layout ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
max-width: 800px;
width: 100%;
margin: 0 auto;
padding: 0 1rem;
overflow: hidden;
}
/* ── Messages area ── */
.messages {
flex: 1;
overflow-y: auto;
padding: 1.5rem 0;
display: flex;
flex-direction: column;
gap: 1rem;
scrollbar-width: thin;
scrollbar-color: var(--border) transparent;
}
.messages::-webkit-scrollbar { width: 4px; }
.messages::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }
/* ── Welcome state ── */
.welcome {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 2rem;
gap: 1rem;
}
.welcome-icon {
width: 48px;
height: 48px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
display: flex;
align-items: center;
justify-content: center;
}
.welcome-icon svg {
width: 24px;
height: 24px;
stroke: var(--muted);
fill: none;
stroke-width: 1.6;
stroke-linecap: round;
stroke-linejoin: round;
}
.welcome h2 {
font-size: 1.25rem;
font-weight: 600;
color: var(--text);
letter-spacing: -0.01em;
}
.welcome p {
font-size: 0.875rem;
color: var(--muted);
max-width: 380px;
line-height: 1.6;
}
/* Suggestion chips */
.suggestions {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: center;
margin-top: 0.5rem;
}
.chip {
padding: 7px 14px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 99px;
font-size: 0.8125rem;
color: var(--muted);
cursor: pointer;
font-family: 'DM Sans', sans-serif;
transition: border-color 0.15s, color 0.15s, background 0.15s;
}
.chip:hover {
border-color: var(--border-strong);
color: var(--text);
background: var(--surface-2);
}
/* ── Message bubbles ── */
.msg-row {
display: flex;
gap: 10px;
animation: fadeUp 0.2s ease both;
}
@keyframes fadeUp {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
.msg-row.user { flex-direction: row-reverse; }
.msg-avatar {
width: 28px;
height: 28px;
border-radius: 50%;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.6875rem;
font-weight: 600;
margin-top: 2px;
}
.msg-avatar.bot {
background: var(--accent);
color: #fff;
}
.msg-avatar.user-av {
background: var(--surface-2);
border: 1px solid var(--border);
color: var(--muted);
}
.msg-content { max-width: 72%; display: flex; flex-direction: column; gap: 4px; }
.msg-row.user .msg-content { align-items: flex-end; }
.msg-sender {
font-size: 0.75rem;
color: var(--hint);
font-weight: 500;
padding: 0 4px;
}
.bubble {
padding: 10px 14px;
border-radius: var(--radius);
font-size: 0.875rem;
line-height: 1.6;
word-break: break-word;
}
.bubble.bot {
background: var(--bot-bubble);
color: var(--bot-fg);
border: 1px solid var(--border);
border-top-left-radius: 4px;
}
.bubble.user {
background: var(--user-bubble);
color: var(--user-fg);
border-top-right-radius: 4px;
}
/* Image in bubble */
.bubble img {
max-width: 100%;
border-radius: var(--radius-xs);
display: block;
margin-top: 6px;
}
.bubble .img-only {
max-width: 260px;
border-radius: var(--radius-sm);
}
.msg-time {
font-size: 0.6875rem;
color: var(--hint);
padding: 0 4px;
}
/* Typing indicator */
.typing-bubble {
padding: 12px 16px;
background: var(--bot-bubble);
border: 1px solid var(--border);
border-radius: var(--radius);
border-top-left-radius: 4px;
display: flex;
gap: 4px;
align-items: center;
}
.typing-bubble span {
width: 6px;
height: 6px;
background: var(--hint);
border-radius: 50%;
animation: blink 1.2s ease infinite;
}
.typing-bubble span:nth-child(2) { animation-delay: 0.2s; }
.typing-bubble span:nth-child(3) { animation-delay: 0.4s; }
@keyframes blink {
0%, 80%, 100% { opacity: 0.3; transform: scale(0.85); }
40% { opacity: 1; transform: scale(1); }
}
/* ── Image preview bar ── */
.image-preview-bar {
display: none;
padding: 8px 0;
gap: 8px;
flex-wrap: wrap;
}
.image-preview-bar.visible { display: flex; }
.img-thumb {
position: relative;
width: 60px;
height: 60px;
}
.img-thumb img {
width: 60px;
height: 60px;
object-fit: cover;
border-radius: var(--radius-xs);
border: 1px solid var(--border);
}
.img-remove {
position: absolute;
top: -6px;
right: -6px;
width: 18px;
height: 18px;
background: var(--text);
color: #fff;
border: none;
border-radius: 50%;
font-size: 10px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
line-height: 1;
}
/* ── Input area ── */
.input-area {
padding: 0.75rem 0 1rem;
flex-shrink: 0;
}
.input-box {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
transition: border-color 0.15s;
overflow: hidden;
}
.input-box:focus-within { border-color: var(--border-strong); }
.input-top {
display: flex;
align-items: flex-end;
gap: 8px;
padding: 10px 12px;
}
textarea {
flex: 1;
border: none;
outline: none;
font-family: 'DM Sans', sans-serif;
font-size: 0.875rem;
color: var(--text);
background: transparent;
resize: none;
min-height: 24px;
max-height: 160px;
line-height: 1.6;
padding: 0;
}
textarea::placeholder { color: var(--hint); }
.input-bottom {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 12px 10px;
border-top: 1px solid var(--border);
}
.input-actions { display: flex; align-items: center; gap: 4px; }
.action-btn {
width: 32px;
height: 32px;
border: none;
background: none;
border-radius: var(--radius-xs);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
color: var(--hint);
transition: background 0.15s, color 0.15s;
}
.action-btn:hover { background: var(--surface-2); color: var(--muted); }
.action-btn svg {
width: 16px;
height: 16px;
stroke: currentColor;
fill: none;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.send-btn {
height: 32px;
padding: 0 14px;
background: var(--accent);
color: var(--accent-fg);
border: none;
border-radius: var(--radius-xs);
font-family: 'DM Sans', sans-serif;
font-size: 0.8125rem;
font-weight: 500;
cursor: pointer;
display: flex;
align-items: center;
gap: 6px;
transition: opacity 0.15s;
}
.send-btn:hover { opacity: 0.85; }
.send-btn:disabled { opacity: 0.4; cursor: not-allowed; }
.send-btn svg {
width: 14px;
height: 14px;
stroke: currentColor;
fill: none;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
.disclaimer {
text-align: center;
font-size: 0.6875rem;
color: var(--hint);
margin-top: 8px;
}
/* ── New chat btn ── */
#newChatBtn { display: none; }
/* ── Confidential badge on bot messages ── */
.conf-badge {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 0.6875rem;
color: #B91C1C;
background: #FEF2F2;
border: 1px solid #FECACA;
border-radius: 99px;
padding: 2px 8px;
margin-top: 4px;
}
/* Hidden file input */
#imageInput { display: none; }
/* ── NAR Suggestion Card ── */
.nar-card {
margin-top: 10px;
background: linear-gradient(135deg, rgba(10,15,40,0.95) 0%, rgba(10,15,55,0.92) 100%);
backdrop-filter: blur(16px);
border: 1px solid rgba(99,130,255,0.3);
box-shadow: 0 0 20px rgba(0,66,234,0.15), 0 8px 32px rgba(0,0,0,0.35);
border-radius: 14px;
padding: 16px 18px;
max-width: 400px;
animation: fadeUp 0.3s ease both;
position: relative;
overflow: hidden;
}
.nar-card::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0; height: 1px;
background: linear-gradient(90deg, transparent, rgba(99,130,255,0.5), transparent);
}
.nar-badge {
display: inline-flex;
align-items: center;
gap: 6px;
background: rgba(99,130,255,0.12);
border: 1px solid rgba(99,130,255,0.3);
border-radius: 99px;
padding: 3px 10px;
font-size: 0.6875rem;
font-weight: 700;
color: #818cf8;
letter-spacing: 0.05em;
text-transform: uppercase;
margin-bottom: 10px;
}
.nar-pulse {
width: 6px; height: 6px;
background: #818cf8; border-radius: 50%;
animation: pulse-dot 1.5s ease-in-out infinite;
}
@keyframes pulse-dot {
0%,100% { opacity:1; transform:scale(1); }
50% { opacity:0.4; transform:scale(0.65); }
}
.nar-title {
font-size: 1rem; font-weight: 700;
color: #f1f5f9; margin-bottom: 6px; line-height: 1.3;
}
.nar-cat {
display: inline-block;
font-size: 0.6875rem; font-weight: 600;
padding: 2px 8px; border-radius: 4px;
margin-bottom: 10px;
}
.nar-reason {
font-size: 0.8125rem; color: #94a3b8; line-height: 1.55;
margin-bottom: 14px; padding: 8px 10px;
background: rgba(255,255,255,0.04);
border-left: 2px solid rgba(99,130,255,0.4);
border-radius: 0 6px 6px 0;
}
.nar-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.nar-btn-primary {
padding: 8px 16px; background: #0042EA; color: #fff;
border: none; border-radius: 8px;
font-family: 'DM Sans', sans-serif; font-size: 0.8125rem; font-weight: 600;
cursor: pointer; transition: background 0.2s, transform 0.15s;
box-shadow: 0 2px 10px rgba(0,66,234,0.4);
}
.nar-btn-primary:hover { background: #0037C1; transform: translateY(-1px); }
.nar-btn-ghost {
padding: 8px 14px;
background: rgba(255,255,255,0.05); color: #94a3b8;
border: 1px solid rgba(255,255,255,0.1); border-radius: 8px;
font-family: 'DM Sans', sans-serif; font-size: 0.8125rem;
cursor: pointer; transition: background 0.2s, color 0.2s;
}
.nar-btn-ghost:hover { background: rgba(255,255,255,0.1); color: #cbd5e1; }
.nar-alts {
display: none; flex-direction: column; gap: 6px; margin-top: 10px;
}
.nar-alts.open { display: flex; }
.nar-alt-item {
display: flex; align-items: center; justify-content: space-between;
padding: 8px 12px;
background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);
border-radius: 8px; cursor: pointer; transition: background 0.15s;
}
.nar-alt-item:hover { background: rgba(99,130,255,0.1); border-color: rgba(99,130,255,0.25); }
.nar-alt-name { font-size: 0.8125rem; color: #cbd5e1; font-weight: 500; }
.nar-alt-cat { font-size: 0.6875rem; color: #475569; }
</style>
</head>
<body>
<!-- NAVBAR -->
<nav class="navbar">
<div class="navbar-left">
<div class="logo-mark" aria-hidden="true">
<svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
</div>
<div>
<span class="brand-name">New Age</span>
<span class="brand-tag">/ AI Support</span>
</div>
</div>
<div class="navbar-right">
<button class="nav-btn" id="newChatBtn" onclick="startNewChat()">
<svg viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
New chat
</button>
<div class="user-pill">
<div class="avatar" id="userAvatar">A</div>
<span id="userName">Admin</span>
</div>
<button class="nav-btn" onclick="logout()" title="Logout">
<svg viewBox="0 0 24 24"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
Logout
</button>
</div>
</nav>
<!-- MAIN -->
<div class="main">
<div class="messages" id="messages">
<!-- Welcome screen -->
<div class="welcome" id="welcome">
<div class="welcome-icon">
<svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
</div>
<h2>How can I help you today?</h2>
<p>Ask me anything about New Age β€” teams, policies, divisions, contacts, or NAR requests.</p>
<div class="suggestions">
<button class="chip" onclick="useChip(this)">What is NAR?</button>
<button class="chip" onclick="useChip(this)">Who should I contact for IT issues?</button>
<button class="chip" onclick="useChip(this)">What are the office timings?</button>
<button class="chip" onclick="useChip(this)">How do I submit a reimbursement?</button>
<button class="chip" onclick="useChip(this)">Tell me about New Age divisions</button>
</div>
</div>
</div>
<!-- Image preview bar -->
<div class="image-preview-bar" id="imagePreviewBar"></div>
<!-- Input area -->
<div class="input-area">
<div class="input-box">
<div class="input-top">
<textarea
id="msgInput"
placeholder="Ask anything about New Age..."
rows="1"
onkeydown="handleKey(event)"
oninput="autoResize(this)"
></textarea>
</div>
<div class="input-bottom">
<div class="input-actions">
<!-- Image upload -->
<button class="action-btn" title="Attach image" onclick="document.getElementById('imageInput').click()">
<svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
</button>
<input type="file" id="imageInput" accept="image/*" multiple onchange="handleImages(this)"/>
<span style="font-size:0.75rem; color:var(--hint); margin-left:4px;">Add image for context</span>
</div>
<button class="send-btn" id="sendBtn" onclick="sendMessage()" disabled>
Send
<svg viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
</button>
</div>
</div>
<p class="disclaimer">New Age AI will not share confidential information such as salary, revenue, or profit.</p>
</div>
</div>
<script>
/* ── State ── */
const pendingImages = []; // { file, dataUrl }
let isTyping = false;
let msgCount = 0;
/* ── Load user from session ── */
window.addEventListener('DOMContentLoaded', () => {
// Read user info from sessionStorage (set by login page)
const savedUser = sessionStorage.getItem('loggedInUser');
if (!savedUser) {
// Not logged in β€” redirect to login page
window.location.href = 'login.html';
return;
}
const user = JSON.parse(savedUser);
document.getElementById('userName').textContent = user.name;
document.getElementById('userAvatar').textContent = user.initials;
// Enable send on input
document.getElementById('msgInput').addEventListener('input', updateSendBtn);
});
/* ── Enable/disable send button ── */
function updateSendBtn() {
const hasText = document.getElementById('msgInput').value.trim().length > 0;
const hasImg = pendingImages.length > 0;
document.getElementById('sendBtn').disabled = !(hasText || hasImg);
}
/* ── Auto-resize textarea ── */
function autoResize(el) {
el.style.height = 'auto';
el.style.height = Math.min(el.scrollHeight, 160) + 'px';
updateSendBtn();
}
/* ── Handle Enter key ── */
function handleKey(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!document.getElementById('sendBtn').disabled) sendMessage();
}
}
/* ── Image handling ── */
function handleImages(input) {
const files = Array.from(input.files);
files.forEach(file => {
const reader = new FileReader();
reader.onload = e => {
pendingImages.push({ file, dataUrl: e.target.result });
renderImagePreviews();
updateSendBtn();
};
reader.readAsDataURL(file);
});
input.value = '';
}
function renderImagePreviews() {
const bar = document.getElementById('imagePreviewBar');
bar.innerHTML = '';
if (pendingImages.length === 0) { bar.classList.remove('visible'); return; }
bar.classList.add('visible');
pendingImages.forEach((img, i) => {
const wrap = document.createElement('div');
wrap.className = 'img-thumb';
wrap.innerHTML = `<img src="${img.dataUrl}" alt="Preview"/><button class="img-remove" onclick="removeImage(${i})">βœ•</button>`;
bar.appendChild(wrap);
});
}
function removeImage(i) {
pendingImages.splice(i, 1);
renderImagePreviews();
updateSendBtn();
}
/* ── Send message ── */
async function sendMessage() {
const input = document.getElementById('msgInput');
const text = input.value.trim();
const images = [...pendingImages];
if (!text && images.length === 0) return;
if (isTyping) return;
// Protection 1: Minimum message length
if (text && text.length < 3) {
alert('Please type a proper question!');
return;
}
// Protection 2: Simple cache β€” avoid duplicate API calls
const cacheKey = text.trim().toLowerCase();
if (messageCache[cacheKey]) {
document.getElementById('welcome') && (document.getElementById('welcome').style.display = 'none');
document.getElementById('newChatBtn').style.display = 'flex';
addMessage('user', text, images);
document.getElementById('msgInput').value = '';
document.getElementById('msgInput').style.height = 'auto';
updateSendBtn();
addMessage('bot', messageCache[cacheKey] + ' *(cached)*');
return;
}
// Hide welcome screen
document.getElementById('welcome').style.display = 'none';
document.getElementById('newChatBtn').style.display = 'flex';
// Render user message
addMessage('user', text, images);
// Clear input
input.value = '';
input.style.height = 'auto';
pendingImages.length = 0;
renderImagePreviews();
updateSendBtn();
// Show typing and call Groq API
showTyping();
await callGroqAPI(text, images);
}
/* ── Add message to DOM ── */
function addMessage(role, text, images = []) {
msgCount++;
const msgs = document.getElementById('messages');
const isUser = role === 'user';
const row = document.createElement('div');
row.className = `msg-row ${isUser ? 'user' : ''}`;
const initials = isUser ? (document.getElementById('userAvatar').textContent || 'U') : 'NA';
const now = new Date();
const time = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
let imagesHtml = '';
if (images.length > 0) {
imagesHtml = images.map(img =>
`<img src="${img.dataUrl}" alt="Attached image" class="${!text ? 'img-only' : ''}"/>`
).join('');
}
// Parse NAR suggestion block out of bot reply
let narCardHtml = '';
let cleanText = text;
if (!isUser) {
const m = text.match(/:::nar-suggestion\s*(\{[\s\S]*?\})\s*:::/);
if (m) {
try {
narCardHtml = buildNarCard(JSON.parse(m[1]));
cleanText = text.replace(/:::nar-suggestion[\s\S]*?:::/, '').trim();
} catch(e) { /* keep raw text if JSON broken */ }
}
}
const isConfidential = !isUser && /salary|revenue|profit|confidential/i.test(cleanText);
const confidentialBadge = isConfidential
? `<span class="conf-badge">⚠ Confidential info not disclosed</span>` : '';
row.innerHTML = `
<div class="msg-avatar ${isUser ? 'user-av' : 'bot'}">${initials}</div>
<div class="msg-content">
<span class="msg-sender">${isUser ? 'You' : 'New Age AI'}</span>
<div class="bubble ${isUser ? 'user' : 'bot'}">
${(cleanText && !narCardHtml) ? `<span>${escHtml(cleanText)}</span>` : (cleanText && narCardHtml) ? `<span>${escHtml(cleanText.split('\n')[0])}</span>` : ''}
${imagesHtml}
</div>
${narCardHtml}
${confidentialBadge}
<span class="msg-time">${time}</span>
</div>
`;
msgs.appendChild(row);
msgs.scrollTop = msgs.scrollHeight;
}
/* ── Build NAR card HTML ── */
function buildNarCard(data) {
const catColors = { IT:'#06b6d4', HR:'#a78bfa', Finance:'#34d399', General:'#94a3b8', Legal:'#fb923c', Growth:'#f472b6', Ops:'#facc15', Management:'#818cf8' };
const c = catColors[data.category] || '#818cf8';
const uid = 'nar_' + Date.now() + '_' + Math.random().toString(36).slice(2,6);
const MONDAY_BOARD_URL = 'https://new-age1.monday.com/boards/9934117905/views/210975370';
const altsHtml = (data.alternatives||[]).map(a =>
`<div class="nar-alt-item" onclick='adoptNar(${JSON.stringify(a).replace(/'/g,"&#39;")})'>
<span class="nar-alt-name">${a.title}</span>
<span class="nar-alt-cat">${a.category}</span>
</div>`
).join('');
return `
<div class="nar-card">
<div class="nar-badge"><span class="nar-pulse"></span>🎯 Suggested NAR</div>
<div class="nar-title">${data.title}</div>
<div class="nar-cat" style="color:${c};background:${c}18;border:1px solid ${c}30">${data.category}</div>
<div class="nar-reason">${data.reason}</div>
${data.fields_guide ? `<div class="nar-reason" style="margin-top:-6px; font-size:0.78rem; color:#64748b; line-height:1.6;">
πŸ“‹ <strong style="color:#94a3b8; font-size:0.78rem;">How to fill:</strong><br>${data.fields_guide}
</div>` : ''}
<div class="nar-actions">
<button class="nar-btn-primary" onclick="window.open('${MONDAY_BOARD_URL}','_blank')">Open NAR Board β†—</button>
${altsHtml ? `<button class="nar-btn-ghost" onclick="this.textContent=this.textContent.includes('Show')?'β–² Hide others':'β–Ό Show others';document.getElementById('${uid}').classList.toggle('open')">β–Ό Show others</button>` : ''}
</div>
<div class="nar-alts" id="${uid}">${altsHtml}</div>
</div>`;
}
/* ── Adopt an alternative NAR into a new card ── */
function adoptNar(alt) {
const msgs = document.getElementById('messages');
const div = document.createElement('div');
div.className = 'msg-row';
div.innerHTML = `
<div class="msg-avatar bot">NA</div>
<div class="msg-content">
<span class="msg-sender">New Age AI</span>
${buildNarCard({...alt, reason:'You selected this as an alternative.', alternatives:[]})}
<span class="msg-time">${new Date().toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})}</span>
</div>`;
msgs.appendChild(div);
msgs.scrollTop = msgs.scrollHeight;
}
/* ── Typing indicator ── */
function showTyping() {
isTyping = true;
document.getElementById('sendBtn').disabled = true;
const msgs = document.getElementById('messages');
const row = document.createElement('div');
row.className = 'msg-row';
row.id = 'typingRow';
row.innerHTML = `
<div class="msg-avatar bot">NA</div>
<div class="msg-content">
<span class="msg-sender">New Age AI</span>
<div class="typing-bubble"><span></span><span></span><span></span></div>
</div>
`;
msgs.appendChild(row);
msgs.scrollTop = msgs.scrollHeight;
}
function hideTyping() {
isTyping = false;
const row = document.getElementById('typingRow');
if (row) row.remove();
updateSendBtn();
}
/* ── Suggestion chips ── */
function useChip(btn) {
document.getElementById('msgInput').value = btn.textContent;
autoResize(document.getElementById('msgInput'));
updateSendBtn();
sendMessage();
}
/* ── New chat ── */
function startNewChat() {
const msgs = document.getElementById('messages');
msgs.innerHTML = `
<div class="welcome" id="welcome">
<div class="welcome-icon">
<svg viewBox="0 0 24 24" stroke="var(--muted)" fill="none" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" width="24" height="24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
</div>
<h2>How can I help you today?</h2>
<p>Ask me anything about New Age β€” teams, policies, divisions, contacts, or NAR requests.</p>
<div class="suggestions">
<button class="chip" onclick="useChip(this)">What is NAR?</button>
<button class="chip" onclick="useChip(this)">Who should I contact for IT issues?</button>
<button class="chip" onclick="useChip(this)">What are the office timings?</button>
<button class="chip" onclick="useChip(this)">How do I submit a reimbursement?</button>
<button class="chip" onclick="useChip(this)">Tell me about New Age divisions</button>
</div>
</div>`;
document.getElementById('newChatBtn').style.display = 'none';
msgCount = 0;
}
/* ── Logout ── */
function logout() {
if (confirm('Are you sure you want to logout?')) {
sessionStorage.removeItem('loggedInUser');
window.location.href = 'login.html';
}
}
/* ── Escape HTML ── */
function escHtml(str) {
return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'<br>');
}
/* ══════════════════════════════════════════════
NAR DATABASE β€” all 28 request types
══════════════════════════════════════════════ */
const NAR_TYPES = [
{ id:1, title:'General Requests', category:'General', keywords:['general','misc','other','help','info'] },
{ id:2, title:'Access Request', category:'IT', keywords:['access','permission','login','account','tool','software','system','monday','slack','drive','github','credentials'] },
{ id:3, title:'Leave Request', category:'HR', keywords:['leave','vacation','time off','holiday','sick','absence','pto','break'] },
{ id:4, title:'Purchase Request', category:'Finance', keywords:['buy','purchase','order','laptop','monitor','hardware','equipment','device','phone','keyboard','mouse','screen'] },
{ id:5, title:'Payment Request', category:'Finance', keywords:['payment','pay','invoice','reimbursement','expense','reimburse','refund','bill','money'] },
{ id:6, title:'Contract Change', category:'Legal', keywords:['contract','agreement','change','modify','update','terms','scope','role','rate','hours'] },
{ id:7, title:'Billing / Subscription Concern', category:'Finance', keywords:['billing','subscription','charge','overcharge','plan','renewal','pricing','overage'] },
{ id:8, title:'Subscription Cancellation Request', category:'Finance', keywords:['cancel','cancellation','unsubscribe','stop subscription','terminate plan'] },
{ id:9, title:'Data Report Blocker', category:'Ops', keywords:['report blocked','data stuck','blocker','report issue','data error','dashboard broken','analytics issue'] },
{ id:10, title:'Data Analysis and Reporting Request', category:'Ops', keywords:['data analysis','reporting','analytics','dashboard','metrics','stats','report','insight','kpi'] },
{ id:11, title:'Grievance / Strategic Alignment Requests', category:'HR', keywords:['grievance','complaint','alignment','strategy','concern','issue with team','unfair','conflict','disagreement'] },
{ id:12, title:'Onboard New Access', category:'IT', keywords:['onboard','new joiner','new employee','new access','setup','new hire','joining','first day','create account'] },
{ id:13, title:'Complaint', category:'HR', keywords:['complaint','problem','unhappy','dissatisfied','bad experience','report problem'] },
{ id:14, title:'Offer Release Request', category:'HR', keywords:['offer letter','offer release','job offer','send offer','hiring offer','appointment letter'] },
{ id:15, title:'Contract Termination', category:'Legal', keywords:['terminate','termination','end contract','fire','exit','notice period','last day'] },
{ id:16, title:'Resignation Letter', category:'HR', keywords:['resign','resignation','quit','leaving','notice','last working day','stepping down'] },
{ id:17, title:'Job Requisition', category:'HR', keywords:['hire','hiring','job opening','vacancy','recruit','new position','headcount','open role'] },
{ id:18, title:'HR Support', category:'HR', keywords:['hr','human resources','hr help','policy','payroll','hr query','documents','certificate','letter'] },
{ id:19, title:'Project Request', category:'General', keywords:['project','new project','start project','initiate','kick off','new work','client project'] },
{ id:20, title:'Automation Request', category:'Ops', keywords:['automate','automation','workflow','bot','script','automatic','zapier','make','n8n','monday automation'] },
{ id:21, title:'Process Change Request', category:'Ops', keywords:['process','change process','improve process','workflow change','sop','procedure','operations'] },
{ id:22, title:'Root Cause Analysis', category:'Ops', keywords:['root cause','rca','why did','investigation','post mortem','incident','bug cause','what went wrong'] },
{ id:23, title:'Emergency Protocol', category:'General', keywords:['emergency','urgent','critical','asap','immediately','down','outage','crisis','production issue'] },
{ id:24, title:'Growth Team Bug Report', category:'Growth', keywords:['bug','error','crash','broken','not working','fix','glitch','app crash','defect'] },
{ id:25, title:'Training Required', category:'HR', keywords:['training','learn','course','skill','workshop','upskill','tutorial','mentorship','education'] },
{ id:26, title:'Meeting Request with CEO', category:'Management', keywords:['ceo','meeting with ceo','talk to ceo','bhargav','leadership','executive','founder'] },
{ id:27, title:'WFH Request', category:'HR', keywords:['wfh','work from home','remote','work remotely','home office'] },
{ id:28, title:'Maintenance Task', category:'Ops', keywords:['maintenance','maintain','upkeep','routine task','scheduled','infra','server maintenance'] },
];
/* ── Keyword-score a query against NAR types, return top 3 ── */
function matchNarTypes(query) {
const q = query.toLowerCase();
return NAR_TYPES
.map(n => ({ ...n, score: n.keywords.reduce((s,kw) => s + (q.includes(kw) ? kw.split(' ').length : 0), 0) }))
.filter(n => n.score > 0)
.sort((a,b) => b.score - a.score)
.slice(0, 3);
}
/* ══════════════════════════════════════════════
GROQ AI API
══════════════════════════════════════════════ */
const GROQ_API_KEYS = [
'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',
'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',
'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'
];
let currentKeyIndex = 0;
const chatHistory = [];
const messageCache = {};
async function callGroqAPI(userText, images = []) {
try {
let userContent = userText || '';
if (images.length > 0) userContent += `\n[User attached ${images.length} image(s)]`;
// Pre-match NAR types locally β€” kept internal, never shown to user
const matches = matchNarTypes(userContent);
const narHints = matches.length > 0
? `\n[SYSTEM ONLY - never repeat this to the user]: Likely NAR matches: ${JSON.stringify(matches.map(n=>({id:n.id,title:n.title,category:n.category})))}. Use these silently to pick the best suggestion.`
: '';
chatHistory.push({ role: 'user', content: userContent });
const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${GROQ_API_KEYS[currentKeyIndex]}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'llama-3.1-8b-instant',
max_tokens: 600,
messages: [
{
role: 'system',
content: `You are the internal AI assistant for New Age (Invento One Private Limited). You know everything about the company and help team members with questions, policies, and raising NAR requests on Monday.com. Always give specific, factual answers β€” never be vague.
==============================
ABOUT NEW AGE
==============================
- Full legal name: Invento One Private Limited
- Brand name: New Age
- Website: newage4.com
- Founded and led by: Bhargav (CEO)
- Office: B10, MBH, Sarthana, Surat, Gujarat, India
- Phone & WhatsApp: +91 81600 78511
- General email: contact@newage4.com
- HR email: hr@newage4.com
- LinkedIn: linkedin.com/company/new-age-ai-products-and-services
MISSION: Listen to users with empathy, innovate and empower them through high-quality, responsible apps that address new-age problems. No addictions, only solutions.
VISION: Positively impacting the daily lives of 1 million users with mindful, globally accessible digital experiences.
WHAT WE DO:
- We build 25+ mobile and web apps across Android, iOS, and Web
- 25 million+ total installs across all apps
- 100K+ active users | 98% user satisfaction | 4.6/5 average rating | 15+ awards won
- App categories: Tools, Education, Productivity, AI-powered utilities
DIVISIONS:
1. Product Division β€” builds and maintains our own Android apps, iOS apps, and web products
2. Services Division β€” AI and Mobile App Development services for external clients
KEY PRODUCTS:
- New Age AI: AI-powered workflow automation suite for businesses
- Cadabra: Supercharges Monday.com workflows with AI (ChatGPT integration)
- iGrammar: Chrome extension β€” personal AI writing assistant
- New Age Slack Bot: AI automation for Slack workspaces
- 20+ more apps on Google Play Store and Apple App Store
==============================
TEAM & WORK CULTURE
==============================
- Remote-first company: 95% of roles are fully remote β€” work from anywhere in the world
- Global team from 10+ countries: developers, designers, testers, marketers, managers, administrators
- Work hours: Flexible 8-hour workday with 70% overlap during 10 AM – 6 PM IST
- Pay schedule: Fortnightly (every 2 weeks)
- Rate revisions: Every 6 months, based on performance
- Employment structure: Freelance/contractor (no PF, gratuity, or statutory deductions)
- Equipment: Team members use their own laptops, phones, and internet connections
==============================
LEAVE POLICY
==============================
- Paid leave: 1 week (7 calendar days) per year β€” available after completing 1 year of service
- Unpaid leave: Up to 3 weeks per year, subject to manager approval
- Sick leave: As needed, with valid notice or documentation
- Public holidays: No fixed national holidays β€” apply on your preferred days (95% approval rate)
- WFH: Apply via WFH Request NAR if needed
==============================
BENEFITS
==============================
- Health insurance: Available to C1 contract holders who have completed 2+ years of service at 40 hrs/week
==============================
CORE VALUES
==============================
1. User First Approach
2. Honest and Constructive Communication
3. Constant Improvement
4. Planning and Long-Term Thinking
5. Innovation at Heart
6. Collaboration Over Competition
7. People First
8. Purpose with Passion
ALL 28 NAR REQUEST TYPES:
${NAR_TYPES.map(n=>`${n.id}. ${n.title} [${n.category}]`).join('\n')}
NAR SUGGESTION RULE β€” CRITICAL, ALWAYS FOLLOW:
You MUST suggest a NAR whenever the user's message contains ANY of these signals:
- Words like: apply, request, submit, raise, need, want, get, buy, report, fix, hire, resign, cancel, change, access, approve, complain, train, schedule, automate
- Phrases like: "I want to", "I need to", "how do I", "can I", "I would like to", "how to apply"
- Topics like: leave, WFH, laptop, reimbursement, payment, access, bug, contract, resignation, training, meeting with CEO
EXAMPLES β€” always show NAR card for these:
- "I want to apply for wfh" β†’ WFH Request
- "I want to apply for leave" β†’ Leave Request
- "I need a new laptop" β†’ Purchase Request
- "how do I submit reimbursement" β†’ Payment Request
- "I want to report a bug" β†’ Growth Team Bug Report
You may have internal context at the end of this prompt to help you pick the right NAR. Never mention or quote that internal context to the user.
After your answer, append this block EXACTLY (valid JSON only, no extra text inside):
:::nar-suggestion
{
"id": <number>,
"title": "<exact title from list>",
"category": "<category>",
"reason": "<one short sentence telling the employee which form to use and why, e.g. To submit a reimbursement, please use the Payment Request form under Finance.>",
"fields_guide": "<bullet list of the key fields to fill in this form, specific to what the user asked. Use β€’ as bullet. E.g. β€’ Request Type: Reimbursement β€’ Amount: Enter the exact amount β€’ Description: What was the expense for β€’ Attachment: Upload receipt if available>",
"alternatives": [
{"id": <n>, "title": "<title>", "category": "<cat>"},
{"id": <n>, "title": "<title>", "category": "<cat>"}
]
}
:::
If the message is purely informational (no action needed), do NOT include the block.
RULES:
1. NEVER share salary, revenue, profit, or financial figures β€” direct to hr@newage4.com
2. When answering company questions (e.g. "what is New Age"), always use SPECIFIC facts from the knowledge base β€” mention the actual numbers (25+ apps, 25M+ installs, 100K+ users), divisions, mission, and products. Never give a vague generic answer.
3. When a NAR card is shown: keep your text reply to 1-2 lines only. Do NOT repeat the form name, fields, or Monday.com instructions β€” the card handles that.
4. Example good reply when NAR is shown: "Sure! I've pulled up the right form for you below. πŸ‘‡"
5. Do NOT say "Please log in to Monday.com" or "Open the board" in your text reply β€” the card button handles that.
6. Be warm, friendly, and speak like a helpful colleague β€” not a system.${narHints}`
},
...chatHistory
]
})
});
const data = await response.json();
if (!response.ok) {
if (data.error?.code === 'rate_limit_exceeded' && currentKeyIndex < GROQ_API_KEYS.length - 1) {
currentKeyIndex++;
return callGroqAPI(userText, images);
}
throw new Error(data.error?.message || 'Something went wrong with AI');
}
const reply = data.choices[0].message.content;
chatHistory.push({ role: 'assistant', content: reply });
if (chatHistory.length > 20) chatHistory.splice(0, 2);
hideTyping();
if (chatHistory.length > 0) {
const last = chatHistory[chatHistory.length - 2];
if (last) messageCache[last.content.trim().toLowerCase()] = reply;
}
addMessage('bot', reply);
} catch (err) {
hideTyping();
addMessage('bot', `Sorry, I ran into an error: ${err.message}. Please try again.`);
console.error('Groq API error:', err);
}
}
</script>
</body>
</html>