<script lang="ts">
  import Popup from "./ui/Popup.svelte";
  import { type Packet, PacketType } from "../protocol.ts";
  import { sendPacket } from "../hub.ts";
  import { global } from "../globals.js";
  import { afterUpdate } from "svelte";
  import TextInput from "./ui/TextInput.svelte";

  interface Message {
    classname: string;
    message: string;
  }

  let messages: Message[] = [];
  let chatbox: HTMLDivElement | null;
  let value = "";

  export function addMessage(classname: string, message: string) {
    messages.push({ classname: classname, message: message });
    messages = messages; // Trigger Svelte reactivity
  }

  afterUpdate(() => {
    if (chatbox !== null) {
      chatbox.scrollTo(0, chatbox.scrollHeight);
    }
  });

  function onkeydown(e: KeyboardEvent) {
    if (e.key === "Enter") {
      if (value.startsWith(".msg")) {
        let args = value.split(" ");
        if (args.length < 3) {
          addMessage("server-error", "Command error");

          value = "";
          return;
        }
        let target = args[1];
        let message = args.slice(2).join(" ");
        let chat_packet: Packet = {
          t: PacketType.SendMessage,
          c: {
            target: target,
            content: message,
          },
        };
        sendPacket(global.client!, chat_packet);

        addMessage("direct-message", `you -> ${target}: ${message}`);
      } else if (value.startsWith(".save")) {
        value = "";
        addMessage(
          "server-message",
          "[Save][1/3] Requesting save from the server...",
        );
        if (!global.saveEligible) {
          addMessage(
            "server-error",
            "[Save] Not eligible to save, please get closer to a planet",
          );
          return;
        }
        let req_packet: Packet = {
          t: PacketType.RequestSave,
          c: {
            old_save: window.localStorage.getItem("save"),
          },
        };
        sendPacket(global.client!, req_packet);
      } else {
        let chat_packet: Packet = {
          t: PacketType.SendMessage,
          c: {
            target: null,
            content: value,
          },
        };
        sendPacket(global.client!, chat_packet);
      }
      value = "";
    }
  }
</script>

<Popup draggable minimizable title="Chat" class="chat-container" id="chat">
  <div bind:this={chatbox} id="chatbox" class="chat-table mono">
    {#each messages as message}
      <p class="message {message.classname}">{message.message}</p>
    {/each}
  </div>
  <TextInput
    bind:value
    on:keydown={onkeydown}
    placeholder="Enter message or command here..."
    class="chat-box"
    id="chatentry"
    required
    autocomplete="off" />
</Popup>
