Spaces:
Configuration error

File size: 6,372 Bytes
ddde4e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const API_URL = "/analyze";
console.log("JS LOADED");
console.log("API URL NOW =", API_URL)
const chatMessages = document.getElementById("chatMessages");
const chatForm = document.getElementById("chatForm");
const chatInput = document.getElementById("chatInput");
const choicePanel = document.getElementById("choicePanel");
const writeOwnBtn = document.getElementById("writeOwnBtn");
const choiceButtons = document.querySelectorAll(".choice-btn[data-example]");
const sendBtn = document.getElementById("sendBtn");
const typingIndicator = document.getElementById("typingIndicator");

let pendingClarification = false;
let currentComplaint = "";

/**
 * Escapes HTML characters to prevent XSS.
 */
function escapeHtml(text) {
    if (text === null || text === undefined) return "";
    return String(text)
        .replaceAll("&", "&")
        .replaceAll("<", "&lt;")
        .replaceAll(">", "&gt;");
}

/**
 * Auto-scroll to the bottom of the chat container.
 */
function scrollToBottom() {
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

/**
 * Appends a user message to the chat.
 */
function appendUserMessage(text) {
    const msgDiv = document.createElement("div");
    msgDiv.className = "message user";
    const contentDiv = document.createElement("div");
    contentDiv.className = "message-content";
    contentDiv.innerText = text;
    msgDiv.appendChild(contentDiv);
    chatMessages.appendChild(msgDiv);
    scrollToBottom();
}

/**
 * Appends a bot message (HTML supported) to the chat.
 */
function appendBotMessage(htmlContent) {
    const msgDiv = document.createElement("div");
    msgDiv.className = "message bot";
    const contentDiv = document.createElement("div");
    contentDiv.className = "message-content";
    contentDiv.innerHTML = htmlContent;
    msgDiv.appendChild(contentDiv);
    chatMessages.appendChild(msgDiv);
    scrollToBottom();
}

function showTyping() {
    typingIndicator.classList.remove("hidden");
    scrollToBottom();
}

function hideTyping() {
    typingIndicator.classList.add("hidden");
}

/**
 * Builds the HTML content for the bot's response incorporating result cards.
 */
function buildResultUI(data) {
    let html = "";
    
    // 1. Check if clarification is needed
    if (data.clarification_needed && data.clarification_question) {
        html += `<p>I need one quick detail before proceeding:</p>
         <p><strong>${escapeHtml(data.clarification_question)}</strong></p>`;
         pendingClarification = true;
        return html;
    }

    // Reset clarification state if not needed
    pendingClarification = false;

    // 2. Normal Response Report
    html += `<p style="margin-bottom: 0.5rem; font-weight: 500;"> Here’s what I found based on your complaint:</p>`;

    if (Array.isArray(data.issues) && data.issues.length > 0) {
        data.issues.forEach(issue => {
            const urgencyClass = issue.urgency ? issue.urgency.toLowerCase() : "default";
            
            html += `
            <div class="result-card">
                <div class="result-header">
                    <div class="result-title">${escapeHtml(issue.title)}</div>
                    <div class="tag ${urgencyClass}">${escapeHtml(issue.urgency || "UNKNOWN URGENCY")}</div>
                </div>
                <div class="authority-highlight">
                    Assigned Authority: ${escapeHtml(issue.authority || "General Administration")}
                </div>
                <div class="reason-text">
                    ${escapeHtml(issue.reason)}
                </div>`;
            
            const rec = data.final_recommendation || issue.recommendation;
            if (rec) {
                html += `
                <div class="recommendation-box">
                    <strong>Recommendation Action</strong>
                    ${escapeHtml(rec)}
                </div>`;
            }
            
            html += `</div>`;
        });
    } else {
        html += `<p>We could not identify a valid issue from the request. Please provide more detailed information.</p>`;
    }



    return html;
}

/**
 * Handle form submission
 */
choiceButtons.forEach(button => {
    button.addEventListener("click", () => {
        const example = button.dataset.example;
        chatInput.value = example;
        chatForm.classList.remove("hidden");
        choicePanel.classList.add("hidden");
        chatInput.focus();
    });
});

writeOwnBtn.addEventListener("click", () => {
    chatInput.value = "";
    chatForm.classList.remove("hidden");
    choicePanel.classList.add("hidden");
    chatInput.focus();
});
chatForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    
    const text = chatInput.value.trim();
    if (!text) return;

    // Render User Message
    appendUserMessage(text);
    
    // Clear & Disable Input
    chatInput.value = "";
    chatInput.disabled = true;
    sendBtn.disabled = true;

    // Show Typing UI
    showTyping();

    try {
        let payload = {};
        if (pendingClarification) {
            payload = {
                complaint: currentComplaint,
                clarification: text,
                task_id: ""
            };
        } else {
            currentComplaint = text; // Keep track of the original context
            payload = {
                complaint: text,
                task_id: ""
            };
        }

        // Optional delay for a natural feel
        await new Promise(res => setTimeout(res, 600));

        const response = await fetch(API_URL, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({complaint: currentComplaint || text,
             clarification: pendingClarification ? text: "",
             task_id: "demo-task"
          })
        });

        if (!response.ok) {
            throw new Error("Server response was not OK.");
        }

        const data = await response.json();
        
        hideTyping();
        const botHtml = buildResultUI(data);
        appendBotMessage(botHtml);

    } catch (err) {
        console.error("API Error:", err);
        hideTyping();
        appendBotMessage(`<p>Frontend error: ${escapeHtml(err.message)}</p>`);
    } finally {
        chatInput.disabled = false;
        sendBtn.disabled = false;
        chatInput.focus();
    }
});