<template>
  <div id="chat-container" :class="{ inactive: !chatActive, active: chatActive }">
    <div id="chat-wrapper">
      <div id="chat-messages" ref="messagesContainer">
        <div v-for="(msg, index) in chatMessages" :key="index" class="chat-message" v-html="formatMessage(msg)"></div>
      </div>
    </div>
    <div id="chat-input-container" :class="{ active: inputActive }">
      <span id="chat-prefix">{{ chatPrefix }}</span>
      <input 
        type="text" 
        id="chat-input" 
        ref="chatInput" 
        v-model="inputValue" 
        @keydown="handleKeyDown" 
        maxlength="128" 
        autocomplete="off" 
        spellcheck="false" 
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { Rpc } from '@entityseven/rage-fw-rpc';

const chatRpc = new Rpc();

// State
const chatMessages = ref<any[]>([]);
const chatActive = ref(false);
const inputActive = ref(false);
const inputValue = ref('');
const chatPrefix = ref('Say:');
const messagesContainer = ref<HTMLElement | null>(null);
const chatInput = ref<HTMLInputElement | null>(null);

let inactiveTimer: ReturnType<typeof setTimeout> | null = null;
const MAX_MESSAGES = 6;
const INACTIVE_TIMEOUT = 6000;

const setInactive = () => {
  if (!inputActive.value) {
    chatActive.value = false;
  }
};

const setActive = () => {
  chatActive.value = true;
  if (inactiveTimer) {
    clearTimeout(inactiveTimer);
    inactiveTimer = null;
  }
};

const resetInactiveTimer = () => {
  setActive();
  if (inactiveTimer) clearTimeout(inactiveTimer);
  if (!inputActive.value) {
    inactiveTimer = setTimeout(() => {
      setInactive();
    }, INACTIVE_TIMEOUT);
  }
};

const openChat = (withSlash = false) => {
  if (inputActive.value) return;
  chatActive.value = true;
  inputActive.value = true;
  
  if (withSlash) {
    inputValue.value = '/';
    chatPrefix.value = 'Cmd:';
  } else {
    inputValue.value = '';
    chatPrefix.value = 'Say:';
  }
  
  nextTick(() => {
    chatInput.value?.focus();
  });
  
  if (typeof (window as any).mp !== 'undefined') {
    (window as any).mp.invoke('focus', true);
  }
  chatRpc.callClient('chat:toggleInput', [true]);
};

const closeChat = () => {
  if (!inputActive.value) return;
  inputActive.value = false;
  inputValue.value = '';
  chatInput.value?.blur();
  
  if (typeof (window as any).mp !== 'undefined') {
    (window as any).mp.invoke('focus', false);
  }
  
  chatRpc.callClient('chat:toggleInput', [false]);
  resetInactiveTimer();
};

const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Enter') {
    e.preventDefault();
    sendMessage();
  } else if (e.key === 'Escape') {
    e.preventDefault();
    closeChat();
  }
};

const sendMessage = () => {
  const msg = inputValue.value.trim();
  if (msg.length > 0) {
    chatRpc.callClient('chat:sendMessage', [msg]);
  }
  closeChat();
};

const addMessage = (data: any) => {
  resetInactiveTimer();
  chatMessages.value.push(data);
  if (chatMessages.value.length > MAX_MESSAGES) {
    chatMessages.value.shift();
  }
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

const clearChat = () => {
  chatMessages.value = [];
};

const escapeHtml = (text: string) => {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
};

const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

const formatMessage = (data: any) => {
  let html = '';
  switch (data.type) {
    case 'player': {
      const time = formatTime(data.timestamp || Date.now());
      html = `
        <span class="msg-timestamp">[${time}]</span>
        <span class="msg-name player">${escapeHtml(data.name)}</span>
        <span class="msg-id">(${data.id})</span>
        <span class="msg-separator">>></span>
        <span class="msg-text">${escapeHtml(data.text)}</span>
      `;
      break;
    }
    case 'global':
      html = `
        <span class="msg-global-tag">[GLOBAL]</span>
        <span class="msg-name global">${escapeHtml(data.name)}</span>
        <span class="msg-id global">(${data.id})</span>
        <span class="msg-separator" style="color: #ff3333;">>></span>
        <span class="msg-text global">${escapeHtml(data.text)}</span>
      `;
      break;
    case 'admin': {
      let tagClass = '';
      let tag = '';
      if (data.adminLevel >= 10) {
          tagClass = 'owner';
          tag = 'OWNER';
      } else if (data.adminLevel === 9) {
          tagClass = 'admin';
          tag = 'ADMIN';
      } else {
          tagClass = 'mod';
          tag = 'ADMIN';
      }
      html = `
        <span class="msg-admin-tag ${tagClass}">${tag}</span>
        <span class="msg-name ${tagClass}">${escapeHtml(data.name)}</span>
        <span class="msg-separator" style="color: inherit;">>></span>
        <span class="msg-text ${tagClass}">${escapeHtml(data.text)}</span>
      `;
      break;
    }
    case 'system':
      html = `<span class="msg-system">${escapeHtml(data.text)}</span>`;
      break;
    case 'error':
      html = `<span class="msg-error">${escapeHtml(data.text)}</span>`;
      break;
    case 'success':
      html = `<span class="msg-success">${escapeHtml(data.text)}</span>`;
      break;
    default:
      html = `<span class="msg-text">${escapeHtml(data.text)}</span>`;
  }
  return html;
};

// Expose legacy API for compatibility but also register via RPC
onMounted(() => {
  (window as any).openChat = openChat;
  (window as any).closeChat = closeChat;
  (window as any).addMessage = addMessage;
  (window as any).clearChat = clearChat;

  chatRpc.register('chat:addMessage', (data: any) => {
    addMessage(data);
  });
  
  chatRpc.register('chat:clear', () => {
    clearChat();
  });

  window.addEventListener('keydown', (e) => {
    if ((e.key === 't' || e.key === 'T') && !inputActive.value) {
      e.preventDefault();
      openChat(false);
    } else if (e.key === '/' && !inputActive.value) {
      e.preventDefault();
      openChat(true);
    }
  });

  setInactive();
});
</script>

<style scoped>
#chat-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 420px;
    font-family: 'Rajdhani', sans-serif;
    font-weight: 500;
    transition: opacity 0.3s ease;
    pointer-events: none;
}

#chat-container.inactive {
    opacity: 0.15;
}

#chat-container.active {
    opacity: 1;
}

#chat-wrapper {
    min-height: 140px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}

#chat-messages {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    padding: 6px 10px;
    background: linear-gradient(180deg, rgba(0, 0, 0, 0.6) 0%, rgba(0, 0, 0, 0.3) 100%);
    pointer-events: none;
}

::v-deep(.chat-message) {
    padding: 1px 4px;
    margin: 0;
    font-size: 13px;
    line-height: 1.2;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.9), 0 0 8px rgba(0, 0, 0, 0.6);
    animation: messageIn 0.15s ease-out;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

@keyframes messageIn {
    from {
        opacity: 0;
        transform: translateX(-10px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

::v-deep(.msg-timestamp) {
    color: #888888;
    font-size: 10px;
    font-family: 'Orbitron', sans-serif;
    margin-right: 4px;
}

::v-deep(.msg-global-tag) {
    color: #ff3333;
    font-weight: 700;
    font-family: 'Orbitron', sans-serif;
    font-size: 11px;
    text-transform: uppercase;
    margin-right: 3px;
}

::v-deep(.msg-admin-tag) {
    font-weight: 700;
    font-family: 'Orbitron', sans-serif;
    font-size: 11px;
    text-transform: uppercase;
    margin-right: 3px;
}

::v-deep(.msg-admin-tag.owner) {
    color: #ff3333;
}

::v-deep(.msg-admin-tag.admin) {
    color: #ff8c00;
}

::v-deep(.msg-admin-tag.mod) {
    color: #33ff33;
}

::v-deep(.msg-name) {
    font-weight: 600;
}

::v-deep(.msg-name.player) {
    color: #aaaaaa;
}

::v-deep(.msg-name.owner) {
    color: #ff3333;
}

::v-deep(.msg-name.admin) {
    color: #ff8c00;
}

::v-deep(.msg-name.mod) {
    color: #33ff33;
}

::v-deep(.msg-name.global) {
    color: #ff3333;
}

::v-deep(.msg-id) {
    color: #888888;
    font-size: 10px;
}

::v-deep(.msg-id.global) {
    color: #ff3333;
}

::v-deep(.msg-separator) {
    color: #666666;
    margin: 0 4px;
    font-weight: 700;
}

::v-deep(.msg-text) {
    color: #ffffff;
}

::v-deep(.msg-text.owner) {
    color: #ff3333;
}

::v-deep(.msg-text.admin) {
    color: #ff8c00;
}

::v-deep(.msg-text.mod) {
    color: #33ff33;
}

::v-deep(.msg-text.global) {
    color: #ff3333;
}

::v-deep(.msg-system) {
    color: #ffcc00;
    font-style: italic;
}

::v-deep(.msg-error) {
    color: #ff4444;
}

::v-deep(.msg-success) {
    color: #44ff44;
}

#chat-input-container {
    display: none;
    align-items: center;
    background: rgba(0, 0, 0, 0.9);
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    padding: 8px 10px;
    pointer-events: auto;
}

#chat-input-container.active {
    display: flex;
}

#chat-prefix {
    color: #ffffff;
    font-family: 'Orbitron', sans-serif;
    font-size: 11px;
    font-weight: 600;
    margin-right: 8px;
    text-transform: uppercase;
}

#chat-input {
    flex: 1;
    background: rgba(255, 255, 255, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 3px;
    padding: 6px 10px;
    color: #ffffff;
    font-family: 'Rajdhani', sans-serif;
    font-size: 13px;
    font-weight: 500;
    outline: none;
    transition: all 0.2s ease;
}

#chat-input:focus {
    background: rgba(255, 255, 255, 0.12);
    border-color: rgba(255, 255, 255, 0.25);
}

#chat-input::placeholder {
    color: rgba(255, 255, 255, 0.3);
}
</style>
