<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>
    <button
      class="camera-button"
      type="button"
      @click="openCamera"
      title="Foto aufnehmen"
      :disabled="!hasConversation || isCameraStarting"
    >
      <span aria-hidden="true">📷</span>
    </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 v-if="cameraModalOpen" class="camera-modal-overlay" @click="closeCamera">
      <div class="camera-modal" @click.stop>
        <div class="camera-modal-header">
          <h3>Foto aufnehmen</h3>
          <button type="button" class="camera-close" @click="closeCamera" title="Schließen">×</button>
        </div>

        <div v-if="cameraError" class="camera-error">
          {{ cameraError }}
        </div>

        <div class="camera-preview">
          <video
            v-show="!capturedImageUrl && !cameraError"
            ref="videoRef"
            autoplay
            playsinline
            muted
          ></video>
          <img
            v-if="capturedImageUrl"
            :src="capturedImageUrl"
            alt="Aufgenommenes Foto"
          />
          <div v-if="isCameraStarting && !cameraError" class="camera-loading">
            Kamera wird gestartet ...
          </div>
        </div>

        <canvas ref="canvasRef" class="camera-canvas" aria-hidden="true"></canvas>

        <div class="camera-actions">
          <button
            v-if="!capturedImageUrl"
            type="button"
            @click="capturePhoto"
            :disabled="isCameraStarting || !!cameraError"
          >
            Foto machen
          </button>
          <button
            v-if="capturedImageUrl"
            type="button"
            class="secondary"
            @click="retakePhoto"
            :disabled="isUploadingPhoto"
          >
            Neu aufnehmen
          </button>
          <button
            v-if="capturedImageUrl"
            type="button"
            @click="sendCapturedPhoto"
            :disabled="isUploadingPhoto"
          >
            {{ isUploadingPhoto ? 'Sende ...' : 'Foto senden' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

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

const chatStore = useChatStore();
const message = ref('');
const showSmileys = ref(false);
const cameraModalOpen = ref(false);
const isCameraStarting = ref(false);
const isUploadingPhoto = ref(false);
const cameraError = ref('');
const videoRef = ref(null);
const canvasRef = ref(null);
const cameraStream = ref(null);
const capturedImageUrl = ref('');
const capturedPhotoBlob = ref(null);
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;
}

function showTemporaryError(text) {
  chatStore.errorMessage = text;
  setTimeout(() => {
    if (chatStore.errorMessage === text) {
      chatStore.errorMessage = null;
    }
  }, 4000);
}

async function handleImageUpload(event) {
  const file = event.target.files[0];
  if (!file) return;

  try {
    await uploadAndSendImage(file);
  } 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 = '';
}

async function uploadAndSendImage(file) {
  if (!chatStore.currentConversation) {
    throw new Error('Keine Konversation ausgewählt');
  }

  // Prüfe Dateigröße (max. 5MB)
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    throw new Error('Bild ist zu groß. Maximale Größe: 5MB');
  }

  const formData = new FormData();
  formData.append('image', file);

  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) {
    chatStore.sendImage(chatStore.currentConversation, data.code, data.url);
  } else {
    throw new Error('Ungültige Antwort vom Server');
  }
}

async function openCamera() {
  if (!hasConversation.value) {
    showTemporaryError('Bitte zuerst eine Unterhaltung auswählen.');
    return;
  }
  if (!navigator.mediaDevices?.getUserMedia) {
    showTemporaryError('Kamera wird von diesem Browser nicht unterstützt.');
    return;
  }

  cameraModalOpen.value = true;
  cameraError.value = '';
  capturedImageUrl.value = '';
  capturedPhotoBlob.value = null;
  isCameraStarting.value = true;

  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        facingMode: 'user',
        width: { ideal: 1280 },
        height: { ideal: 1280 }
      },
      audio: false
    });

    cameraStream.value = stream;
    if (videoRef.value) {
      videoRef.value.srcObject = stream;
      await videoRef.value.play();
    }
  } catch (error) {
    console.error('Kamera konnte nicht gestartet werden:', error);
    cameraError.value = 'Kamera konnte nicht gestartet werden. Bitte Berechtigung prüfen.';
    stopCameraStream();
  } finally {
    isCameraStarting.value = false;
  }
}

function stopCameraStream() {
  if (cameraStream.value) {
    cameraStream.value.getTracks().forEach(track => track.stop());
    cameraStream.value = null;
  }
  if (videoRef.value) {
    videoRef.value.srcObject = null;
  }
}

function closeCamera() {
  stopCameraStream();
  cameraModalOpen.value = false;
  cameraError.value = '';
  isCameraStarting.value = false;
  isUploadingPhoto.value = false;
  clearCapturedPhoto();
}

function clearCapturedPhoto() {
  if (capturedImageUrl.value) {
    URL.revokeObjectURL(capturedImageUrl.value);
  }
  capturedImageUrl.value = '';
  capturedPhotoBlob.value = null;
}

function capturePhoto() {
  if (!videoRef.value || !canvasRef.value) return;

  const video = videoRef.value;
  const canvas = canvasRef.value;
  const sourceWidth = video.videoWidth || 1280;
  const sourceHeight = video.videoHeight || 720;
  const maxSide = 1280;
  const scale = Math.min(1, maxSide / Math.max(sourceWidth, sourceHeight));
  const targetWidth = Math.round(sourceWidth * scale);
  const targetHeight = Math.round(sourceHeight * scale);

  canvas.width = targetWidth;
  canvas.height = targetHeight;
  const context = canvas.getContext('2d');
  context.drawImage(video, 0, 0, targetWidth, targetHeight);

  canvas.toBlob((blob) => {
    if (!blob) {
      cameraError.value = 'Foto konnte nicht verarbeitet werden.';
      return;
    }

    clearCapturedPhoto();
    capturedPhotoBlob.value = blob;
    capturedImageUrl.value = URL.createObjectURL(blob);
    stopCameraStream();
  }, 'image/jpeg', 0.86);
}

async function retakePhoto() {
  clearCapturedPhoto();
  await openCamera();
}

async function sendCapturedPhoto() {
  if (!capturedPhotoBlob.value) return;

  isUploadingPhoto.value = true;
  try {
    const file = new File([capturedPhotoBlob.value], `singlechat-photo-${Date.now()}.jpg`, {
      type: 'image/jpeg'
    });
    await uploadAndSendImage(file);
    closeCamera();
  } catch (error) {
    console.error('Fehler beim Foto-Versand:', error);
    cameraError.value = 'Foto konnte nicht gesendet werden: ' + error.message;
  } finally {
    isUploadingPhoto.value = false;
  }
}

onBeforeUnmount(() => {
  stopCameraStream();
  clearCapturedPhoto();
});
</script>

<style scoped>
.camera-button {
  width: 35px;
  height: 35px;
  border: 1px solid #cdd8d0;
  border-radius: 8px;
  background: #ffffff;
  display: inline-grid;
  place-items: center;
  cursor: pointer;
  font-size: 18px;
}

.camera-button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.camera-modal-overlay {
  position: fixed;
  inset: 0;
  z-index: 1200;
  padding: 18px;
  background: rgba(12, 18, 14, 0.78);
  display: flex;
  align-items: center;
  justify-content: center;
}

.camera-modal {
  width: min(560px, 100%);
  max-height: calc(100vh - 36px);
  border-radius: 10px;
  border: 1px solid #d7dfd9;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.camera-modal-header {
  min-height: 54px;
  padding: 0 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e4ebe6;
}

.camera-modal-header h3 {
  margin: 0;
  color: #18201b;
  font-size: 17px;
}

.camera-close {
  width: 36px;
  height: 36px;
  border: 0;
  border-radius: 8px;
  background: #edf2ee;
  color: #253027;
  font-size: 24px;
  line-height: 1;
  cursor: pointer;
}

.camera-error {
  margin: 14px 14px 0;
  border: 1px solid #e5b7b7;
  border-radius: 8px;
  padding: 10px 12px;
  background: #fff0f0;
  color: #7d2525;
  font-size: 14px;
}

.camera-preview {
  position: relative;
  margin: 14px;
  aspect-ratio: 4 / 3;
  border-radius: 10px;
  background: #101510;
  overflow: hidden;
  display: grid;
  place-items: center;
}

.camera-preview video,
.camera-preview img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.camera-preview video {
  transform: scaleX(-1);
}

.camera-loading {
  position: absolute;
  inset: 0;
  display: grid;
  place-items: center;
  color: #ffffff;
  background: rgba(0, 0, 0, 0.35);
  font-weight: 700;
}

.camera-canvas {
  display: none;
}

.camera-actions {
  padding: 0 14px 14px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.camera-actions button {
  min-height: 40px;
  border: 0;
  border-radius: 8px;
  padding: 0 16px;
  background: #245c3a;
  color: #ffffff;
  font-weight: 800;
  cursor: pointer;
}

.camera-actions button.secondary {
  background: #edf2ee;
  color: #245c3a;
  border: 1px solid #bfd5c4;
}

.camera-actions button:disabled {
  opacity: 0.55;
  cursor: not-allowed;
}

@media (max-width: 620px) {
  .camera-modal-overlay {
    padding: 10px;
  }

  .camera-actions {
    flex-direction: column;
  }
}
</style>
