<template>
  <div class="chat-input-container">
    <input
      v-model="message"
      :type="inputType"
      :placeholder="inputPlaceholder"
      @keyup.enter="sendMessage"
    />
    <button @click="sendMessage">{{ $t('button_send') }}</button>
    <button class="no-style" @click="showSmileys = !showSmileys" title="Add a smiley">
      <img src="/smileys.png" alt="Smileys" />
    </button>
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleImageUpload"
    />
    <button
      class="no-style"
      @click="$refs.fileInput.click()"
      :title="$t('tooltip_send_image')"
      :disabled="!hasConversation"
    >
      <img src="/image.png" alt="Image" />
    </button>
    
    <div v-if="showSmileys" class="smiley-bar">
      <span
        v-for="(smiley, code) in smileys"
        :key="code"
        class="smiley-item"
        :title="smiley.tooltip"
        v-html="'&#x' + smiley.code + ';'"
        @click="insertSmiley(code)"
      ></span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useChatStore } from '../stores/chat';

const chatStore = useChatStore();
const message = ref('');
const showSmileys = ref(false);
const hasConversation = computed(() => !!chatStore.currentConversation);
const isAwaitingUsername = computed(() => chatStore.awaitingLoginUsername);
const isAwaitingPassword = computed(() => chatStore.awaitingLoginPassword);

const inputPlaceholder = computed(() => {
  if (isAwaitingUsername.value) {
    return 'Admin-Username eingeben';
  }
  if (isAwaitingPassword.value) {
    return 'Admin-Passwort eingeben';
  }
  return hasConversation.value
    ? 'Nachricht senden oder /Befehl eingeben'
    : 'Nur /Befehle eingeben (z.B. /login, /stat help)';
});

const inputType = computed(() => (isAwaitingPassword.value ? 'password' : 'text'));

// Smiley-Definitionen (wie im Original)
const smileys = {
  ':)': { code: '1F642', emoji: '🙂', tooltip: 'Smile' },
  ':D': { code: '1F600', emoji: '😀', tooltip: 'Laugh' },
  ':(': { code: '1F641', emoji: '🙁', tooltip: 'Sad' },
  ';)': { code: '1F609', emoji: '😉', tooltip: 'Twinkle' },
  ':p': { code: '1F60B', emoji: '😋', tooltip: 'Tongue' },
  ';p': { code: '1F61C', emoji: '😜', tooltip: 'Twinkle tongue' },
  'O)': { code: '1F607', emoji: '😇', tooltip: 'Angel' },
  ':*': { code: '1F617', emoji: '😗', tooltip: 'Kiss' },
  '(h)': { code: '1FA77', emoji: '🩷', tooltip: 'Heart' },
  'xD': { code: '1F602', emoji: '😂', tooltip: 'Laughing hard' },
  ':@': { code: '1F635', emoji: '😵', tooltip: 'Confused' },
  ':O': { code: '1F632', emoji: '😲', tooltip: 'Surprised' },
  ':3': { code: '1F63A', emoji: '😺', tooltip: 'Cat face' },
  ':|': { code: '1F610', emoji: '😐', tooltip: 'Neutral' },
  ':/': { code: '1FAE4', emoji: '🫤', tooltip: 'Skeptical' },
  ':#': { code: '1F912', emoji: '🤒', tooltip: 'Sick' },
  '#)': { code: '1F973', emoji: '🥳', tooltip: 'Partied' },
  '%)': { code: '1F974', emoji: '🥴', tooltip: 'Drunk' },
  '(t)': { code: '1F44D', emoji: '👍', tooltip: 'Thumbs up' },
  ":'(": { code: '1F622', emoji: '😢', tooltip: 'Cry' }
};

function sendMessage() {
  const trimmed = message.value.trim();
  if (!trimmed) return;
  const isCommand = trimmed.startsWith('/');
  const canSendPlain =
    hasConversation.value || isAwaitingUsername.value || isAwaitingPassword.value;

  if (!isCommand && !canSendPlain) {
    chatStore.errorMessage = 'Ohne aktive Konversation sind nur /Befehle erlaubt.';
    setTimeout(() => {
      if (chatStore.errorMessage === 'Ohne aktive Konversation sind nur /Befehle erlaubt.') {
        chatStore.errorMessage = null;
      }
    }, 4000);
    return;
  }

  const suppressLocal = isCommand || isAwaitingUsername.value || isAwaitingPassword.value;
  chatStore.sendMessage(chatStore.currentConversation, trimmed, { suppressLocal });
  message.value = '';
}

function insertSmiley(code) {
  message.value += code;
  showSmileys.value = false;
}

async function handleImageUpload(event) {
  const file = event.target.files[0];
  if (!file) return;
  
  if (!chatStore.currentConversation) {
    console.error('Keine Konversation ausgewählt');
    return;
  }
  
  // Prüfe Dateigröße (max. 5MB)
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    alert('Bild ist zu groß. Maximale Größe: 5MB');
    return;
  }
  
  try {
    // Erstelle FormData für Upload
    const formData = new FormData();
    formData.append('image', file);
    
    // Lade Bild hoch
    const response = await fetch('/api/upload-image', {
      method: 'POST',
      body: formData,
      credentials: 'include' // Wichtig für Session-Cookies
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ error: 'Unbekannter Fehler' }));
      throw new Error(errorData.error || 'Fehler beim Hochladen des Bildes');
    }
    
    const data = await response.json();
    
    if (data.success && data.code) {
      // Sende nur den Code über Socket.IO
      chatStore.sendImage(chatStore.currentConversation, data.code, data.url);
    } else {
      throw new Error('Ungültige Antwort vom Server');
    }
  } catch (error) {
    console.error('Fehler beim Bild-Upload:', error);
    alert('Fehler beim Bild-Upload: ' + error.message);
  }
  
  // Input zurücksetzen, damit das gleiche Bild erneut ausgewählt werden kann
  event.target.value = '';
}
</script>


