<template>
  <div class="chat-window">

    <!-- ── EMPTY STATE ────────────────────────────────────────────────── -->
    <div v-if="!conversation" class="chat-empty">
      <div class="empty-logo">
        <svg viewBox="0 0 64 64" width="72" height="72">
          <circle cx="32" cy="32" r="32" fill="rgba(37,211,102,0.12)"/>
          <path d="M32 14C22.06 14 14 22.06 14 32c0 3.52.96 6.81 2.63 9.64L14 50l8.64-2.58A17.93 17.93 0 0032 50c9.94 0 18-8.06 18-18S41.94 14 32 14z" fill="#25d366" opacity=".7"/>
        </svg>
      </div>
      <h3>WhatsApp Business Inbox</h3>
      <p>Select a conversation from the left to start chatting</p>
    </div>

    <!-- ── ACTIVE CHAT ────────────────────────────────────────────────── -->
    <template v-else>

      <!-- Header -->
      <div class="cw-header">
        <div class="cw-avatar" :style="avatarStyle">{{ conversation.initials }}</div>
        <div class="cw-info">
          <div class="cw-name">{{ conversation.contact_name || conversation.contact_phone }}</div>
          <div class="cw-phone">{{ conversation.contact_phone }}</div>
        </div>

        <div class="cw-toolbar">
          <span v-if="conversation.hours_left !== null" class="hours-badge"
            :class="{ urgent: conversation.hours_left < 3 }">
            {{ conversation.hours_left > 0
              ? `⏱ ${conversation.hours_left}h`
              : '⚠ Window closed' }}
          </span>

          <!-- Label -->
          <div class="dropdown-wrap" ref="labelWrap">
            <button class="tool-btn" @click="showLabelMenu = !showLabelMenu">
              🏷 {{ conversation.label || 'Label' }}
            </button>
            <div v-if="showLabelMenu" class="dropdown-menu">
              <div v-for="lbl in LABELS" :key="lbl.v" class="drop-item" @click="setLabel(lbl.v)">
                <span :style="{ color: lbl.c }">●</span> {{ lbl.name }}
              </div>
              <div class="drop-item red" @click="setLabel(null)">✕ Remove label</div>
            </div>
          </div>

          <!-- Status -->
          <button class="tool-btn"
            :class="conversation.status === 'closed' ? 'btn-reopen' : 'btn-close'"
            @click="$emit('statusChange', conversation.status === 'closed' ? 'open' : 'closed')">
            {{ conversation.status === 'closed' ? '↩ Reopen' : '✓ Close' }}
          </button>
        </div>
      </div>

      <!-- Messages area -->
      <div class="messages-area" ref="msgArea">
        <template v-for="(group, date) in groupedMessages" :key="date">
          <div class="day-sep"><span>{{ date }}</span></div>
          <MessageBubble v-for="msg in group" :key="msg.id" :message="msg" />
        </template>
        <div v-if="messages.length === 0" class="no-msgs">No messages yet</div>
        <div ref="bottom"></div>
      </div>

      <!-- ── Location form overlay ──────────────────────────────────── -->
      <div v-if="showLocationForm" class="location-overlay" @click.self="showLocationForm = false">
        <div class="location-card">
          <div class="loc-title">📍 Send Location</div>
          <button class="loc-detect" @click="detectLocation" :disabled="detectingLoc">
            {{ detectingLoc ? '⏳ Detecting...' : '🎯 Use my current location' }}
          </button>
          <div class="loc-divider">or enter manually</div>
          <div class="loc-grid">
            <div class="loc-field">
              <label>Latitude</label>
              <input type="number" v-model="locData.lat" step="any" placeholder="24.8607" />
            </div>
            <div class="loc-field">
              <label>Longitude</label>
              <input type="number" v-model="locData.lng" step="any" placeholder="67.0011" />
            </div>
            <div class="loc-field loc-full">
              <label>Name (optional)</label>
              <input type="text" v-model="locData.name" placeholder="Office, Home…" />
            </div>
            <div class="loc-field loc-full">
              <label>Address (optional)</label>
              <input type="text" v-model="locData.address" placeholder="Street, City" />
            </div>
          </div>
          <div class="loc-actions">
            <button class="loc-cancel" @click="showLocationForm = false">Cancel</button>
            <button class="loc-send" :disabled="!locData.lat || !locData.lng || sending"
              @click="$emit('sendLocation', locData); showLocationForm = false">
              Send Location
            </button>
          </div>
        </div>
      </div>

      <!-- ── Input bar ──────────────────────────────────────────────── -->
      <div class="input-bar">

        <!-- Recording state -->
        <div v-if="isRecording" class="recording-bar">
          <span class="rec-dot"></span>
          <span class="rec-time">{{ formatRecTime(recordingSecs) }}</span>
          <span class="rec-label">Recording…</span>
          <button class="rec-cancel" @click="cancelRecording" title="Cancel">✕</button>
          <button class="rec-stop" @click="stopRecording" title="Send recording">
            <i class="fas fa-paper-plane"></i>
          </button>
        </div>

        <!-- Normal input -->
        <template v-else>
          <!-- Attach button -->
          <div class="dropdown-wrap" ref="attachWrap">
            <button class="input-icon-btn" @click="showAttachMenu = !showAttachMenu" title="Attach">
              <i class="fas fa-paperclip"></i>
            </button>
            <div v-if="showAttachMenu" class="attach-menu">
              <div class="attach-item" @click="triggerFile('image')">
                <span class="att-icon" style="background:#3b82f6">🖼️</span> Photo / Image
              </div>
              <div class="attach-item" @click="triggerFile('video')">
                <span class="att-icon" style="background:#8b5cf6">🎥</span> Video
              </div>
              <div class="attach-item" @click="triggerFile('audio')">
                <span class="att-icon" style="background:#f59e0b">🎵</span> Audio File
              </div>
              <div class="attach-item" @click="triggerFile('document')">
                <span class="att-icon" style="background:#ef4444">📄</span> Document
              </div>
              <div class="attach-item" @click="triggerFile('sticker')">
                <span class="att-icon" style="background:#ec4899">🎭</span> Sticker
              </div>
              <div class="attach-item" @click="openLocation">
                <span class="att-icon" style="background:#25d366">📍</span> Location
              </div>
            </div>
          </div>

          <!-- Hidden file inputs -->
          <input ref="fileImage"    type="file" accept="image/*"            hidden @change="onFile('image', $event)" />
          <input ref="fileVideo"    type="file" accept="video/*"            hidden @change="onFile('video', $event)" />
          <input ref="fileAudio"    type="file" accept="audio/*"            hidden @change="onFile('audio', $event)" />
          <input ref="fileDocument" type="file" accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip" hidden @change="onFile('document', $event)" />
          <input ref="fileSticker"  type="file" accept="image/webp"         hidden @change="onFile('sticker', $event)" />

          <!-- Textarea -->
          <textarea
            ref="textInput"
            v-model="text"
            class="msg-textarea"
            placeholder="Type a message…"
            rows="1"
            :disabled="sending"
            @keydown.enter.exact.prevent="sendText"
            @input="autoResize"
          ></textarea>

          <!-- Mic button -->
          <button class="input-icon-btn mic-btn" @click="startRecording" title="Record audio" :disabled="sending">
            <i class="fas fa-microphone"></i>
          </button>

          <!-- Send button -->
          <button class="send-btn" :disabled="!text.trim() || sending" @click="sendText" title="Send">
            <i class="fas fa-paper-plane"></i>
          </button>
        </template>
      </div>

    </template>
  </div>
</template>

<script>
import MessageBubble from './MessageBubble.vue';

const LABELS = [
  { v: 'sales',    name: 'Sales',     c: '#25d366' },
  { v: 'support',  name: 'Support',   c: '#60a5fa' },
  { v: 'urgent',   name: 'Urgent',    c: '#f87171' },
  { v: 'followup', name: 'Follow Up', c: '#fbbf24' },
  { v: 'vip',      name: 'VIP',       c: '#a78bfa' },
];

export default {
  name: 'ChatWindow',
  components: { MessageBubble },

  props: {
    conversation: { type: Object, default: null },
    messages:     { type: Array,  default: () => [] },
    sending:      { type: Boolean, default: false },
  },

  emits: ['send', 'sendMedia', 'sendLocation', 'statusChange', 'labelChange'],

  data() {
    return {
      text:            '',
      showAttachMenu:  false,
      showLabelMenu:   false,
      showLocationForm:false,
      isRecording:     false,
      recordingSecs:   0,
      recordingTimer:  null,
      mediaRecorder:   null,
      audioChunks:     [],
      locData:         { lat: '', lng: '', name: '', address: '' },
      detectingLoc:    false,
      LABELS,
    };
  },

  computed: {
    avatarStyle() {
      if (!this.conversation) return {};
      const hue = [...this.conversation.contact_phone]
        .reduce((a, c) => a + c.charCodeAt(0), 0) % 360;
      return { background: `hsl(${hue},40%,28%)` };
    },
    groupedMessages() {
      const groups = {};
      for (const msg of this.messages) {
        const d   = new Date(msg.created_at);
        const key = d.toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric' });
        if (!groups[key]) groups[key] = [];
        groups[key].push(msg);
      }
      return groups;
    },
  },

  watch: {
    messages() { this.$nextTick(this.scrollBottom); },
    conversation(n, o) {
      if (n?.id !== o?.id) {
        this.text = '';
        this.showAttachMenu  = false;
        this.showLabelMenu   = false;
        this.showLocationForm= false;
        this.$nextTick(this.scrollBottom);
      }
    },
  },

  mounted() {
    document.addEventListener('click', this.onDocClick);
  },
  beforeUnmount() {
    document.removeEventListener('click', this.onDocClick);
    this.clearRecTimer();
  },

  methods: {
    // ── Text send ────────────────────────────────────────────────────
    sendText() {
      const t = this.text.trim();
      if (!t || this.sending) return;
      this.$emit('send', t);
      this.text = '';
      this.$nextTick(() => {
        if (this.$refs.textInput) this.$refs.textInput.style.height = 'auto';
      });
    },
    autoResize() {
      const el = this.$refs.textInput;
      if (!el) return;
      el.style.height = 'auto';
      el.style.height = Math.min(el.scrollHeight, 120) + 'px';
    },

    // ── Attach / file ─────────────────────────────────────────────
    triggerFile(type) {
      this.showAttachMenu = false;
      const refs = { image: 'fileImage', video: 'fileVideo', audio: 'fileAudio', document: 'fileDocument', sticker: 'fileSticker' };
      this.$refs[refs[type]]?.click();
    },
    onFile(type, event) {
      const file = event.target.files[0];
      if (!file) return;
      event.target.value = '';
      this.$emit('sendMedia', file, type, '');
    },

    // ── Location ─────────────────────────────────────────────────
    openLocation() {
      this.showAttachMenu  = false;
      this.showLocationForm = true;
      this.locData = { lat: '', lng: '', name: '', address: '' };
    },
    detectLocation() {
      if (!navigator.geolocation) { alert('Geolocation not supported.'); return; }
      this.detectingLoc = true;
      navigator.geolocation.getCurrentPosition(
        pos => {
          this.locData.lat = pos.coords.latitude.toFixed(6);
          this.locData.lng = pos.coords.longitude.toFixed(6);
          this.detectingLoc = false;
        },
        () => { this.detectingLoc = false; alert('Could not detect location.'); }
      );
    },

    // ── Audio recording ──────────────────────────────────────────
    async startRecording() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        this.audioChunks  = [];
        this.mediaRecorder = new MediaRecorder(stream);
        this.mediaRecorder.ondataavailable = e => { if (e.data.size > 0) this.audioChunks.push(e.data); };
        this.mediaRecorder.onstop = () => {
          const mime = this.mediaRecorder.mimeType || 'audio/webm';
          const ext  = mime.includes('ogg') ? 'ogg' : (mime.includes('mp4') ? 'm4a' : 'webm');
          const blob = new Blob(this.audioChunks, { type: mime });
          const file = new File([blob], `voice_${Date.now()}.${ext}`, { type: mime });
          this.$emit('sendMedia', file, 'audio', '');
          stream.getTracks().forEach(t => t.stop());
        };
        this.mediaRecorder.start();
        this.isRecording  = true;
        this.recordingSecs = 0;
        this.recordingTimer = setInterval(() => this.recordingSecs++, 1000);
      } catch (e) {
        alert('Microphone access denied.');
      }
    },
    stopRecording() {
      this.isRecording = false;
      this.clearRecTimer();
      this.mediaRecorder?.stop();
    },
    cancelRecording() {
      this.isRecording = false;
      this.clearRecTimer();
      if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
        this.mediaRecorder.ondataavailable = null;
        this.mediaRecorder.onstop = null;
        this.mediaRecorder.stop();
        this.mediaRecorder.stream?.getTracks().forEach(t => t.stop());
      }
    },
    clearRecTimer() {
      clearInterval(this.recordingTimer);
      this.recordingTimer = null;
    },
    formatRecTime(secs) {
      const m = String(Math.floor(secs / 60)).padStart(2, '0');
      const s = String(secs % 60).padStart(2, '0');
      return `${m}:${s}`;
    },

    // ── Label / Status ───────────────────────────────────────────
    setLabel(v) {
      this.showLabelMenu = false;
      this.$emit('labelChange', v);
    },

    // ── Helpers ──────────────────────────────────────────────────
    scrollBottom() {
      this.$refs.bottom?.scrollIntoView({ behavior: 'smooth' });
    },
    onDocClick(e) {
      if (!e.target.closest('[data-attach]') && !e.target.closest('.attach-menu'))  this.showAttachMenu  = false;
      if (!e.target.closest('[data-label]')  && !e.target.closest('.dropdown-menu')) this.showLabelMenu  = false;
    },
  },
};
</script>

<style scoped>
/* ── Layout ─────────────────────────────────────────────────────────── */
.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  position: relative;
  /* WhatsApp dark background */
  background-color: #0b141a;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='80'%3E%3Cg fill='%23ffffff' fill-opacity='0.025'%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Ccircle cx='30' cy='10' r='1.5'/%3E%3Ccircle cx='50' cy='10' r='2'/%3E%3Ccircle cx='70' cy='10' r='1.5'/%3E%3Ccircle cx='20' cy='30' r='1.5'/%3E%3Ccircle cx='40' cy='30' r='2'/%3E%3Ccircle cx='60' cy='30' r='1.5'/%3E%3Ccircle cx='10' cy='50' r='1.5'/%3E%3Ccircle cx='30' cy='50' r='2'/%3E%3Ccircle cx='50' cy='50' r='1.5'/%3E%3Ccircle cx='70' cy='50' r='2'/%3E%3Ccircle cx='20' cy='70' r='2'/%3E%3Ccircle cx='40' cy='70' r='1.5'/%3E%3Ccircle cx='60' cy='70' r='2'/%3E%3C/g%3E%3C/svg%3E");
  background-repeat: repeat;
}

/* ── Empty state ──────────────────────────────────────────────────── */
.chat-empty {
  flex: 1; display: flex; flex-direction: column;
  align-items: center; justify-content: center;
  gap: 12px; color: #5a7a6a;
}
.empty-logo { opacity: .7; }
.chat-empty h3 { font-size: 20px; color: #7da898; font-weight: 600; margin: 0; }
.chat-empty p  { font-size: 14px; margin: 0; }

/* ── Header ──────────────────────────────────────────────────────── */
.cw-header {
  display: flex; align-items: center; gap: 12px;
  padding: 10px 16px;
  background: #1f2c34;
  border-bottom: 1px solid #2a3942;
  flex-shrink: 0; flex-wrap: wrap; z-index: 2;
}
.cw-avatar {
  width: 40px; height: 40px; min-width: 40px;
  border-radius: 50%; display: flex;
  align-items: center; justify-content: center;
  font-size: 15px; font-weight: 700; color: #fff;
}
.cw-info { flex: 1; min-width: 0; }
.cw-name  { font-size: 15px; font-weight: 600; color: #e9edef; }
.cw-phone { font-size: 11px; color: #8696a0; }

.cw-toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }

.hours-badge {
  font-size: 11px; padding: 3px 10px; border-radius: 20px;
  background: rgba(37,211,102,.15); color: #25d366; white-space: nowrap;
}
.hours-badge.urgent { background: rgba(239,68,68,.15); color: #ef4444; }

.tool-btn {
  background: #2a3942; border: 1px solid #3b4a54;
  color: #aebac1; font-size: 12px; padding: 5px 12px;
  border-radius: 8px; cursor: pointer; white-space: nowrap;
  transition: background .12s;
}
.tool-btn:hover { background: #3b4a54; color: #e9edef; }
.btn-close  { background: rgba(239,68,68,.12); color: #f87171; border-color: rgba(239,68,68,.25); }
.btn-reopen { background: rgba(37,211,102,.12); color: #25d366; border-color: rgba(37,211,102,.25); }

/* ── Dropdown menus ──────────────────────────────────────────────── */
.dropdown-wrap { position: relative; }
.dropdown-menu {
  position: absolute; top: calc(100% + 6px); right: 0;
  background: #233138; border: 1px solid #2a3942;
  border-radius: 10px; padding: 4px;
  min-width: 150px; z-index: 100;
  box-shadow: 0 8px 32px rgba(0,0,0,.5);
}
.drop-item {
  padding: 8px 14px; font-size: 13px; color: #e9edef;
  cursor: pointer; border-radius: 7px; display: flex;
  align-items: center; gap: 8px; transition: background .1s;
}
.drop-item:hover { background: #2a3942; }
.drop-item.red   { color: #f87171; }

/* ── Messages ────────────────────────────────────────────────────── */
.messages-area {
  flex: 1; overflow-y: auto;
  padding: 12px 0 8px; position: relative; z-index: 1;
}
.messages-area::-webkit-scrollbar { width: 5px; }
.messages-area::-webkit-scrollbar-thumb { background: #2a3942; border-radius: 3px; }

.day-sep { text-align: center; margin: 12px 0; }
.day-sep span {
  background: rgba(17,27,33,.7); backdrop-filter: blur(4px);
  color: #8696a0; font-size: 11.5px; padding: 4px 14px; border-radius: 8px;
}

.no-msgs { text-align: center; color: #556770; padding: 40px; font-size: 14px; }

/* ── Location overlay ────────────────────────────────────────────── */
.location-overlay {
  position: absolute; inset: 0; background: rgba(0,0,0,.7);
  display: flex; align-items: center; justify-content: center;
  z-index: 50; backdrop-filter: blur(4px);
}
.location-card {
  background: #233138; border-radius: 16px; padding: 24px;
  width: 380px; max-width: 90%;
  box-shadow: 0 20px 60px rgba(0,0,0,.6);
}
.loc-title    { font-size: 16px; font-weight: 700; color: #e9edef; margin-bottom: 16px; }
.loc-detect   {
  width: 100%; padding: 10px; border-radius: 10px;
  background: rgba(37,211,102,.15); border: 1px solid rgba(37,211,102,.3);
  color: #25d366; font-size: 13px; font-weight: 600; cursor: pointer;
  transition: background .15s; margin-bottom: 12px;
}
.loc-detect:hover:not(:disabled) { background: rgba(37,211,102,.25); }
.loc-detect:disabled { opacity: .5; cursor: not-allowed; }
.loc-divider  { text-align: center; font-size: 11px; color: #556770; margin: 8px 0 12px; }
.loc-grid     { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.loc-field    { display: flex; flex-direction: column; gap: 4px; }
.loc-field.loc-full { grid-column: 1 / -1; }
.loc-field label { font-size: 11px; color: #8696a0; font-weight: 600; text-transform: uppercase; letter-spacing: .5px; }
.loc-field input {
  padding: 8px 12px; background: #1f2c34; border: 1px solid #2a3942;
  border-radius: 8px; color: #e9edef; font-size: 13px; outline: none;
}
.loc-field input:focus { border-color: #25d366; }
.loc-actions  { display: flex; justify-content: flex-end; gap: 10px; margin-top: 16px; }
.loc-cancel   { background: #2a3942; border: none; color: #aebac1; padding: 8px 16px; border-radius: 8px; cursor: pointer; font-size: 13px; }
.loc-send     {
  background: #25d366; border: none; color: #000; padding: 8px 20px;
  border-radius: 8px; cursor: pointer; font-size: 13px; font-weight: 700;
}
.loc-send:disabled { opacity: .4; cursor: not-allowed; }

/* ── Input bar ───────────────────────────────────────────────────── */
.input-bar {
  display: flex; align-items: flex-end; gap: 8px;
  padding: 10px 14px;
  background: #1f2c34;
  border-top: 1px solid #2a3942;
  flex-shrink: 0; z-index: 2;
}

.input-icon-btn {
  width: 38px; height: 38px; min-width: 38px;
  background: transparent; border: none; color: #8696a0;
  font-size: 17px; cursor: pointer; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  transition: color .15s, background .15s;
}
.input-icon-btn:hover { color: #e9edef; background: rgba(255,255,255,.06); }
.input-icon-btn:disabled { opacity: .4; cursor: not-allowed; }

.msg-textarea {
  flex: 1; background: #2a3942; border: none;
  border-radius: 10px; color: #e9edef; font-size: 14px;
  padding: 9px 14px; resize: none; outline: none;
  max-height: 120px; min-height: 38px; line-height: 1.45;
  font-family: inherit;
}
.msg-textarea::placeholder { color: #556770; }

.send-btn {
  width: 38px; height: 38px; min-width: 38px;
  background: #25d366; border: none; border-radius: 50%;
  color: #000; font-size: 15px; cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  transition: background .15s, transform .1s;
}
.send-btn:hover:not(:disabled) { background: #20b355; transform: scale(1.06); }
.send-btn:disabled { opacity: .35; cursor: not-allowed; }

/* ── Attach menu ─────────────────────────────────────────────────── */
.attach-menu {
  position: absolute; bottom: calc(100% + 8px); left: 0;
  background: #233138; border: 1px solid #2a3942;
  border-radius: 12px; padding: 6px;
  min-width: 190px; z-index: 100;
  box-shadow: 0 8px 32px rgba(0,0,0,.6);
}
.attach-item {
  display: flex; align-items: center; gap: 10px;
  padding: 9px 12px; cursor: pointer; border-radius: 8px;
  font-size: 13px; color: #e9edef; transition: background .1s;
}
.attach-item:hover { background: #2a3942; }
.att-icon { width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; flex-shrink: 0; }

/* ── Recording bar ───────────────────────────────────────────────── */
.recording-bar {
  flex: 1; display: flex; align-items: center; gap: 12px;
  background: #1b2b33; border-radius: 10px; padding: 8px 14px;
}
.rec-dot {
  width: 10px; height: 10px; border-radius: 50%;
  background: #ef4444; animation: recPulse 1s infinite; flex-shrink: 0;
}
@keyframes recPulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:.5;transform:scale(.7)} }
.rec-time  { font-family: monospace; font-size: 16px; font-weight: 700; color: #ef4444; }
.rec-label { font-size: 13px; color: #8696a0; flex: 1; }
.rec-cancel {
  background: transparent; border: 1px solid #3b4a54;
  color: #8696a0; width: 32px; height: 32px; border-radius: 50%;
  cursor: pointer; font-size: 14px; display: flex; align-items: center; justify-content: center;
}
.rec-stop {
  background: #25d366; border: none; color: #000;
  width: 38px; height: 38px; border-radius: 50%;
  cursor: pointer; font-size: 15px;
  display: flex; align-items: center; justify-content: center;
}
</style>
