{% extends "base.html.j2" %}
{% block title %}Chat — {{ project_name }}{% endblock %}
{% block extra_styles %}
.chat-container { display: flex; flex-direction: column; height: calc(100vh - 120px); }
.messages { flex: 1; overflow-y: auto; padding: 1rem 0; }
.message { display: flex; margin-bottom: 1rem; gap: 0.75rem; }
.message.user { justify-content: flex-end; }
.message .bubble { max-width: 70%; padding: 0.75rem 1rem; border-radius: 12px; font-size: 0.9rem; line-height: 1.5; }
.message.user .bubble { background: #4c51bf; color: #fff; border-bottom-right-radius: 4px; }
.message.assistant .bubble { background: #fff; border: 1px solid #e2e8f0; border-bottom-left-radius: 4px; }
.message .tool-info { font-size: 0.75rem; color: #718096; margin-top: 0.25rem; font-style: italic; }
.input-area { display: flex; gap: 0.75rem; padding: 1rem 0; border-top: 1px solid #e2e8f0; }
.input-area input[type="text"] { flex: 1; }
.domain-selector { display: flex; gap: 0.5rem; margin-bottom: 0.75rem; flex-wrap: wrap; }
.domain-chip { padding: 0.3rem 0.75rem; border-radius: 9999px; font-size: 0.8rem; cursor: pointer; border: 1px solid #cbd5e0; background: #fff; }
.domain-chip.active { background: #4c51bf; color: #fff; border-color: #4c51bf; }
.typing-indicator { display: none; padding: 0.5rem; color: #718096; font-size: 0.85rem; }
.file-upload-area { display: flex; align-items: center; }
{% endblock %}

{% block content %}
<div class="chat-container">
  <div class="domain-selector">
    <span style="font-size: 0.85rem; font-weight: 600; padding: 0.3rem 0;">Domain:</span>
    {% for domain in domains %}
    <button class="domain-chip{% if loop.first %} active{% endif %}" data-domain="{{ domain.name }}" onclick="selectDomain(this)" title="{{ domain.description }}">
      {{ domain.name }}
    </button>
    {% endfor %}
  </div>

  <div class="messages" id="messages"></div>
  <div class="typing-indicator" id="typing">Agent is thinking...</div>

  <div class="input-area">
    <div class="file-upload-area">
      <label for="file-upload" style="cursor: pointer;" title="Upload file">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#718096" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>
      </label>
      <input type="file" id="file-upload" style="display: none;" onchange="handleFileUpload(this)">
    </div>
    <input type="text" id="chat-input" placeholder="Ask the agent..." onkeydown="if(event.key==='Enter')sendMessage()">
    <button class="btn btn-primary" onclick="sendMessage()">Send</button>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script>
const GQL_ENDPOINT = "{{ gql_endpoint }}";
let activeDomain = "{{ domains[0].name if domains else '' }}";
let uploadedFile = null;

function selectDomain(btn) {
  document.querySelectorAll(".domain-chip").forEach(c => c.classList.remove("active"));
  btn.classList.add("active");
  activeDomain = btn.dataset.domain;
}

function addMessage(role, text, toolInfo) {
  const container = document.getElementById("messages");
  const div = document.createElement("div");
  div.className = `message ${role}`;
  let html = `<div class="bubble">${escapeHtml(text)}`;
  if (toolInfo) {
    html += `<div class="tool-info">Consulted: ${escapeHtml(toolInfo)}</div>`;
  }
  html += `</div>`;
  div.innerHTML = html;
  container.appendChild(div);
  container.scrollTop = container.scrollHeight;
}

async function sendMessage() {
  const input = document.getElementById("chat-input");
  const text = input.value.trim();
  if (!text) return;

  addMessage("user", text);
  input.value = "";

  document.getElementById("typing").style.display = "block";

  const query = `query { ask_${activeDomain.toLowerCase()}(query: "${text.replace(/"/g, '\\"')}") }`;
  const data = await gqlQuery(query);
  document.getElementById("typing").style.display = "none";

  const result = data?.data?.[`ask_${activeDomain.toLowerCase()}`];
  if (result) {
    const parsed = typeof result === "string" ? tryParseJson(result) : result;
    const answer = parsed?.answer || parsed?.response || String(result);
    const tools = parsed?.agents_consulted || parsed?.tools_used;
    addMessage("assistant", answer, tools ? tools.join(", ") : null);
  } else {
    const errMsg = data?.errors?.[0]?.message || "No response from agent.";
    addMessage("assistant", errMsg);
  }
}

async function gqlQuery(query) {
  const res = await fetch(GQL_ENDPOINT, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query }),
  });
  return res.json();
}

function handleFileUpload(input) {
  const file = input.files[0];
  if (file) {
    uploadedFile = file;
    addMessage("user", `[Uploaded file: ${file.name}]`);
  }
}

function tryParseJson(text) {
  try { return JSON.parse(text); } catch { return null; }
}

function escapeHtml(text) {
  const d = document.createElement("div");
  d.textContent = text;
  return d.innerHTML;
}
</script>
{% endblock %}
