<template>
  <div class="p-4">
    <h1 class="text-2xl font-bold mb-4">Nuxt 3 WebSocket Client Example</h1>
    <p>
      Status:
      <span :class="isConnected ? 'text-green-600' : 'text-red-600'">{{
        isConnected ? "Connected" : "Disconnected"
      }}</span>
    </p>

    <div class="mt-4">
      <input
        v-model="inputMessage"
        placeholder="Type a message"
        class="border p-2 rounded w-full"
      />
      <button
        @click="send"
        class="mt-2 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
      >
        Send
      </button>
    </div>

    <div class="mt-6">
      <h2 class="text-xl font-semibold mb-2">Messages</h2>
      <ul class="list-disc pl-5 max-h-64 overflow-y-auto">
        <li v-for="(msg, index) in messages" :key="index">
          <pre>{{ msg }}</pre>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { useRuntimeConfig } from "#app";
import { useWebSocket } from "~/composables/useWebSocket";

const config = useRuntimeConfig();
const wsUrl = config.public.websocketUrl;

const { messages, isConnected, sendMessage } = useWebSocket(wsUrl);

const inputMessage = ref("");

function send() {
  if (inputMessage.value.trim() !== "") {
    sendMessage({ type: "message", data: inputMessage.value });
    inputMessage.value = "";
  }
}
</script>

<style scoped>
pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>
