<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">{{ current.meta.model }}</span>
        </div>
        <div class="fact">
          <span class="label mono">GPU</span>
          <span class="value mono">{{ current.meta.gpu }}</span>
        </div>
        <div class="fact">
          <span class="label mono">Endpoint</span>
          <button class="endpoint-copy mono" type="button" @click="copyCurl">
            {{ current.meta.endpoint || apiDisplay }}
            <span v-if="copied" class="copied">copied</span>
          </button>
        </div>
      </div>
    </section>

    <section class="card chat-card">
      <div class="profile-tabs">
        <button
          v-for="profile in profiles"
          :key="profile.id"
          type="button"
          class="profile-tab mono"
          :class="{ active: activeProfile === profile.id }"
          @click="activeProfile = profile.id"
        >
          {{ profile.label }}
        </button>
      </div>
      <div class="chat-window" ref="chatWindow">
        <div v-for="(msg, idx) in current.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 class="message">{{ 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="current.error" class="chat-row error">
          <div class="bubble">
            <div class="role mono">error</div>
            <p>{{ current.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 { computed, onMounted, onUpdated, reactive, ref, watch } 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 profiles = [
  { id: "atlas-quick", label: "Atlas Quick" },
  { id: "atlas-smart", label: "Atlas Smart" },
  { id: "stock-ai", label: "Stock AI" },
];
const activeProfile = ref("atlas-quick");
const profileState = reactive(
  Object.fromEntries(
    profiles.map((profile) => [
      profile.id,
      {
        meta: {
          model: "loading...",
          gpu: "local GPU (dynamic)",
          node: "unknown",
          endpoint: apiUrl.toString(),
        },
        messages: [
          {
            role: "assistant",
            content: "Hi! I'm Atlas AI. How can I help?",
          },
        ],
        error: "",
      },
    ])
  )
);
const current = computed(() => profileState[activeProfile.value]);
const draft = ref("");
const sending = ref(false);
const chatWindow = ref(null);
const copied = ref(false);
const conversationIds = reactive({});

function ensureConversationId(profile) {
  if (conversationIds[profile]) return conversationIds[profile];
  const key = `atlas-ai-conversation:${profile}`;
  let value = localStorage.getItem(key);
  if (!value) {
    const suffix =
      typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `${Math.random()}`.slice(2);
    value = `${profile}-${Date.now()}-${suffix}`;
    localStorage.setItem(key, value);
  }
  conversationIds[profile] = value;
  return value;
}

onMounted(() => fetchMeta(activeProfile.value));
watch(activeProfile, (profile) => fetchMeta(profile));

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

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

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

  try {
    const history = state.messages.filter((m) => !m.streaming).map((m) => ({ role: m.role, content: m.content }));
    const conversation_id = ensureConversationId(activeProfile.value);
    const start = performance.now();
    const resp = await fetch(API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ message: text, history, profile: activeProfile.value, conversation_id }),
    });
    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) {
    state.error = 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 = current.value.meta.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: auto 1fr auto;
  gap: 12px;
  min-height: 60vh;
}

.profile-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.profile-tab {
  border: 1px solid var(--card-border);
  background: rgba(255, 255, 255, 0.03);
  color: var(--text-muted);
  padding: 6px 12px;
  border-radius: 999px;
  cursor: pointer;
  transition: border-color 0.2s ease, color 0.2s ease, background 0.2s ease;
}

.profile-tab.active {
  border-color: rgba(0, 229, 197, 0.6);
  color: var(--text-primary);
  background: rgba(0, 229, 197, 0.12);
  box-shadow: var(--glow-soft);
}

.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);
}
.message {
  white-space: pre-wrap;
  word-break: break-word;
}
.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>
