<template>
  <div class="page">
    <section class="card hero glass">
      <div>
        <p class="eyebrow">Atlas AI</p>
        <h1>Chat</h1>
        <p class="lede">
          Talk with Atlas AI. It knows a surprising amount about technology!
        </p>
        <div class="pill mono pill-live">Online</div>
      </div>
      <div class="hero-facts">
        <div class="fact">
          <span class="label mono">Model</span>
          <span class="value mono">{{ meta.model }}</span>
        </div>
        <div class="fact">
          <span class="label mono">GPU</span>
          <span class="value mono">{{ meta.gpu }}</span>
        </div>
        <div class="fact">
          <span class="label mono">Endpoint</span>
          <button class="endpoint-copy mono" type="button" @click="copyCurl">
            {{ meta.endpoint || apiDisplay }}
            <span v-if="copied" class="copied">copied</span>
          </button>
        </div>
      </div>
    </section>

    <section class="card chat-card">
      <div class="chat-window" ref="chatWindow">
        <div v-for="(msg, idx) in messages" :key="idx" :class="['chat-row', msg.role]">
          <div class="bubble" :class="{ streaming: msg.streaming }">
            <div class="role mono">{{ msg.role === 'assistant' ? 'Atlas AI' : 'you' }}</div>
            <p>{{ msg.content }}</p>
            <div v-if="msg.streaming" class="meta mono typing">streaming…</div>
            <div v-else-if="msg.latency_ms" class="meta mono">{{ msg.latency_ms }} ms</div>
          </div>
        </div>
        <div v-if="error" class="chat-row error">
          <div class="bubble">
            <div class="role mono">error</div>
            <p>{{ error }}</p>
          </div>
        </div>
      </div>
      <form class="chat-form" @submit.prevent="sendMessage">
        <textarea
          v-model="draft"
          placeholder="Ask anything about the lab or general topics..."
          rows="3"
          @keydown="handleKeydown"
          :disabled="sending"
        />
        <div class="actions">
          <span class="hint mono">Enter to send · Shift+Enter for newline</span>
          <button class="primary" type="submit" :disabled="sending || !draft.trim()">
            {{ sending ? "Sending..." : "Send" }}
          </button>
        </div>
      </form>
    </section>
  </div>
</template>

<script setup>
import { onMounted, onUpdated, ref } from "vue";

const API_URL = (import.meta.env.VITE_AI_ENDPOINT || "/api/chat").trim();
const apiUrl = new URL(API_URL, window.location.href);
const apiDisplay = apiUrl.host + apiUrl.pathname;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const meta = ref({
  model: "loading...",
  gpu: "local GPU (dynamic)",
  node: "unknown",
  endpoint: apiUrl.toString(),
});
const messages = ref([
  {
    role: "assistant",
    content: "Hi! I'm Atlas AI. How can I help?",
  },
]);
const draft = ref("");
const sending = ref(false);
const error = ref("");
const chatWindow = ref(null);
const copied = ref(false);

onMounted(fetchMeta);

onUpdated(() => {
  if (chatWindow.value) {
    chatWindow.value.scrollTop = chatWindow.value.scrollHeight;
  }
});

async function fetchMeta() {
  try {
    const resp = await fetch("/api/ai/info");
    if (!resp.ok) return;
    const data = await resp.json();
    meta.value = {
      model: data.model || meta.value.model,
      gpu: data.gpu || meta.value.gpu,
      node: data.node || meta.value.node,
      endpoint: data.endpoint || meta.value.endpoint || apiDisplay,
    };
  } catch {
    // swallow
  }
}

async function sendMessage() {
  if (!draft.value.trim() || sending.value) return;
  const text = draft.value.trim();
  draft.value = "";
  error.value = "";
  const userEntry = { role: "user", content: text };
  messages.value.push(userEntry);
  const assistantEntry = { role: "assistant", content: "", streaming: true };
  messages.value.push(assistantEntry);
  sending.value = true;

  try {
    const history = messages.value.filter((m) => !m.streaming).map((m) => ({ role: m.role, content: m.content }));
    const start = performance.now();
    const resp = await fetch(API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ message: text, history }),
    });
    const contentType = resp.headers.get("content-type") || "";

    if (!resp.ok) {
      const data = await resp.json().catch(() => ({}));
      throw new Error(data.error || resp.statusText || "Request failed");
    }

    // Prefer streaming if the server sends a stream; otherwise fall back to JSON body.
    if (resp.body && !contentType.includes("application/json")) {
      const reader = resp.body.getReader();
      const decoder = new TextDecoder();
      let firstChunk = true;
      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        const chunk = decoder.decode(value, { stream: true });
        assistantEntry.content += chunk;
        if (firstChunk) {
          assistantEntry.latency_ms = Math.round(performance.now() - start);
          firstChunk = false;
        }
      }
      assistantEntry.latency_ms = assistantEntry.latency_ms || Math.round(performance.now() - start);
      assistantEntry.streaming = false;
    } else {
      const data = await resp.json();
      const textReply = data.reply || "(empty response)";
      assistantEntry.latency_ms = data.latency_ms ?? Math.round(performance.now() - start);
      await typeReveal(assistantEntry, textReply);
    }
  } catch (err) {
    error.value = err.message || "Unexpected error";
    assistantEntry.content = assistantEntry.content || "(no response)";
    assistantEntry.streaming = false;
  } finally {
    sending.value = false;
  }
}

async function typeReveal(entry, text) {
  entry.content = "";
  entry.streaming = true;
  const chunks = text.match(/.{1,14}/g) || [text];
  for (const chunk of chunks) {
    entry.content += chunk;
    await sleep(15);
  }
  entry.streaming = false;
}

function handleKeydown(e) {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
}

async function copyCurl() {
  const target = meta.value.endpoint || apiUrl.toString();
  const curl = `curl -X POST ${target} -H 'content-type: application/json' -d '{\"message\":\"hi\"}'`;
  try {
    await navigator.clipboard.writeText(curl);
    copied.value = true;
    setTimeout(() => (copied.value = false), 1400);
  } catch {
    copied.value = false;
  }
}
</script>

<style scoped>
.page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 32px 22px 72px;
}

.hero {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 18px;
  align-items: start;
}

.hero-facts {
  display: grid;
  gap: 10px;
  align-content: start;
}

.fact {
  border: 1px solid var(--card-border);
  border-radius: 10px;
  padding: 10px 12px;
  background: rgba(255, 255, 255, 0.02);
}

.label {
  color: var(--text-muted);
  font-size: 12px;
}

.value {
  display: block;
  margin-top: 4px;
}

.endpoint-copy {
  background: none;
  color: inherit;
  border: 1px solid var(--card-border);
  border-radius: 8px;
  padding: 6px 8px;
  width: 100%;
  text-align: left;
  cursor: pointer;
}
.endpoint-copy .copied {
  float: right;
  color: var(--accent-cyan);
  font-size: 11px;
}

.pill-live {
  display: inline-block;
  margin-top: 8px;
}

.chat-card {
  margin-top: 18px;
  display: grid;
  grid-template-rows: 1fr auto;
  gap: 12px;
  min-height: 60vh;
}

.chat-window {
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid var(--card-border);
  border-radius: 12px;
  padding: 14px;
  min-height: 360px;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.chat-row {
  display: flex;
}

.chat-row.user {
  justify-content: flex-end;
}

.bubble {
  max-width: 85%;
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid var(--card-border);
  background: rgba(255, 255, 255, 0.04);
}
.bubble.streaming {
  border-color: rgba(0, 229, 197, 0.4);
  box-shadow: var(--glow-soft);
}

.chat-row.assistant .bubble {
  background: rgba(80, 163, 255, 0.08);
}

.chat-row.user .bubble {
  background: rgba(255, 255, 255, 0.06);
}

.chat-row.error .bubble {
  background: rgba(255, 87, 87, 0.1);
  border-color: rgba(255, 87, 87, 0.5);
}

.role {
  font-size: 12px;
  color: var(--text-muted);
  margin-bottom: 4px;
}

.meta {
  color: var(--text-muted);
  font-size: 12px;
  margin-top: 6px;
}
.meta.typing {
  color: var(--accent-cyan);
}

.chat-form {
  margin-top: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

textarea {
  width: 100%;
  border-radius: 12px;
  border: 1px solid var(--card-border);
  background: rgba(255, 255, 255, 0.03);
  color: var(--text-primary);
  padding: 10px 12px;
  resize: vertical;
}

.actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.hint {
  color: var(--text-muted);
}

button.primary {
  background: linear-gradient(90deg, #4f8bff, #7dd0ff);
  color: #0b1222;
  padding: 10px 16px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 700;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 820px) {
  .hero {
    grid-template-columns: 1fr;
  }
  .chat-card {
    min-height: 50vh;
  }
  .actions {
    align-items: flex-start;
    flex-direction: column;
  }
}

@media (min-width: 1100px) {
  .chat-card {
    min-height: calc(100vh - 260px);
  }
  .chat-window {
    min-height: 480px;
  }
}
</style>
