<script setup>
import { ref, onUnmounted, nextTick, onMounted } from 'vue'
import { useFillHeight } from '../../composables/useFillHeight'
import { Plug, Info, X } from 'lucide-vue-next'

const clipboardContent = ref('')
const isListening = ref(false)
const lastClipboardText = ref('')
const textareaRef = ref(null)
const isExtensionReady = ref(false)
const showExtensionModal = ref(false)
let intervalId = null
let extensionCheckInterval = null

const { height: textareaHeight } = useFillHeight(textareaRef, 40) // 40px margin bottom

// Listen for extension messages
const handleExtensionMessage = (event) => {
  if (event.source !== window) return

  if (event.data.type === 'TOOLS_APP_EXTENSION_READY' || event.data.type === 'TOOLS_APP_PONG') {
    isExtensionReady.value = true
    lastPongTime = Date.now()
    // console.log('Extension is ready')
  }

  if (event.data.type === 'TOOLS_APP_CLIPBOARD_UPDATE' && isListening.value) {
    const text = event.data.content
    if (text && text !== lastClipboardText.value) {
      lastClipboardText.value = text
      clipboardContent.value += (clipboardContent.value ? '\n' : '') + text
      scrollToBottom()
    }
  }
}

const closeModalOnEsc = (e) => {
  if (e.key === 'Escape' && showExtensionModal.value) {
    showExtensionModal.value = false
  }
}

// Watchdog for extension
let lastPongTime = Date.now()
const PING_INTERVAL = 200
const TIMEOUT_THRESHOLD = 500

const startExtensionWatchdog = () => {
  extensionCheckInterval = setInterval(() => {
    // 1. Send Ping
    window.postMessage({ type: 'TOOLS_APP_PING' }, '*')

    // 2. Check timeout
    // If current time - lastPongTime > threshold, then disconnected
    if (Date.now() - lastPongTime > TIMEOUT_THRESHOLD) {
       isExtensionReady.value = false
    }
  }, PING_INTERVAL)
}

// Wrapper to intercept PONG and update heartbeat
const messageListener = (event) => {
  if (event.source !== window) return

  if (event.data.type === 'TOOLS_APP_PONG' || event.data.type === 'TOOLS_APP_EXTENSION_READY') {
    lastPongTime = Date.now()
    isExtensionReady.value = true
  }

  handleExtensionMessage(event)
}

onMounted(() => {
  window.addEventListener('message', messageListener)
  window.addEventListener('keydown', closeModalOnEsc)

  // Initial check
  window.postMessage({ type: 'TOOLS_APP_INIT' }, '*')

  // Start heartbeat
  startExtensionWatchdog()
})

onUnmounted(() => {
  stopListening()
  if (extensionCheckInterval) clearInterval(extensionCheckInterval)
  window.removeEventListener('message', messageListener)
  window.removeEventListener('keydown', closeModalOnEsc)
})

const scrollToBottom = () => {
  nextTick(() => {
    const textarea = document.querySelector('.tool-textarea')
    if (textarea) {
      textarea.scrollTop = textarea.scrollHeight
    }
  })
}

const startListening = async () => {
  try {
    isListening.value = true

    // Try native API first (for web app usage without extension)
    // Initial read
    try {
      const text = await navigator.clipboard.readText()
      if (text) {
          lastClipboardText.value = text
          clipboardContent.value += (clipboardContent.value ? '\n' : '') + text
          scrollToBottom()
      }
    } catch (e) {
      console.log('Native clipboard read failed (expected if not focused), relying on extension if available')
    }

    // If extension is ready, ask it to start sniffing
    if (isExtensionReady.value) {
      window.postMessage({ type: 'TOOLS_APP_START_SNIFFING' }, '*')
    }

    // Fallback polling for web app (only works when focused usually)
    intervalId = setInterval(async () => {
      try {
        const currentText = await navigator.clipboard.readText()
        if (currentText && currentText !== lastClipboardText.value) {
          lastClipboardText.value = currentText
          clipboardContent.value += (clipboardContent.value ? '\n' : '') + currentText
          scrollToBottom()
        }
      } catch (err) {
        // Ignore errors in polling (e.g. lost focus)
      }
    }, 1000)
  } catch (err) {
    console.error('Permission denied or clipboard error:', err)
    alert('Clipboard access denied. Please allow clipboard access to use this tool.')
  }
}

const stopListening = () => {
  isListening.value = false
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }

  if (isExtensionReady.value) {
    window.postMessage({ type: 'TOOLS_APP_STOP_SNIFFING' }, '*')
  }
}

const clearText = () => {
  clipboardContent.value = ''
  // Don't reset lastClipboardText so if they copy the same thing again it's detected?
  // No, if they clear, they might want to see it again if they copy it again.
  // But usually "change" means diff from clipboard.
  // If I clear text, but clipboard still has "A", and I copy "A" again (refresh clipboard), readText still returns "A".
  // So it won't be detected as a change.
  // If user wants to capture "A" again, they need to copy something else then "A".
  // That's standard behavior for "sniffer" (detect changes).
}

const copyToClipboard = async () => {
  if (!clipboardContent.value) return
  try {
    await navigator.clipboard.writeText(clipboardContent.value)
  } catch (err) {
    console.error('Failed to copy to clipboard:', err)
  }
}

onUnmounted(() => {
  stopListening()
})
</script>

<template>
  <div class="tool-container" style="max-width: 100%;">
    <div class="tool-panel">
      <div class="tool-header">
        <h2 class="tool-title">Clipboard Sniffer</h2>
        <div
          class="extension-status"
          :class="{ 'connected': isExtensionReady }"
          @click="showExtensionModal = true"
          :title="isExtensionReady ? 'Extension connected' : 'Extension not detected - Click for info'"
        >
          <Plug v-if="isExtensionReady" size="20" />
          <Info v-else size="20" />
        </div>
      </div>

      <div class="controls">
        <button
          v-if="!isListening"
          class="btn-neon"
          @click="startListening"
          v-ripple
        >
          Start Sniffing
        </button>
        <button
          v-else
          class="btn-neon active"
          @click="stopListening"
          v-ripple
        >
          Stop Sniffing
        </button>

        <button class="btn-neon" @click="copyToClipboard" v-ripple>
          Copy
        </button>

        <button class="btn-neon" @click="clearText" v-ripple>
          Clear
        </button>
      </div>

      <div class="result-area" style="margin-top: 1rem;">
        <div ref="textareaRef" :style="{ height: textareaHeight, width: '100%' }">
          <textarea
            v-model="clipboardContent"
            class="tool-textarea"
            placeholder="Clipboard content will appear here line by line..."
          ></textarea>
        </div>
      </div>
    </div>

    <!-- Extension Info Modal -->
    <div v-if="showExtensionModal" class="modal-overlay" @click.self="showExtensionModal = false">
      <div class="modal-content glass-panel">
        <button class="close-btn" @click="showExtensionModal = false">
          <X size="24" />
        </button>

        <div v-if="!isExtensionReady">
          <h3>Enhance Your Experience</h3>
          <p>
            Install our browser extension to enable <strong>background clipboard sniffing</strong>!
          </p>
          <p class="description">
            Without the extension, this tool can only capture clipboard content when the tab is active.
            With the extension, you can capture content even when you're working in other apps.
          </p>
          <div class="modal-actions">
            <a href="#" class="btn-neon" @click.prevent>Extension Coming Soon</a>
          </div>
        </div>

        <div v-else>
          <h3>Extension Connected!</h3>
          <p>
            You have successfully enabled <strong>background clipboard sniffing</strong>.
          </p>
          <p class="description">
            The extension is active and monitoring your clipboard in the background.
            You can now switch to other apps and copy text - it will appear here automatically.
          </p>
          <div class="modal-actions">
            <button class="btn-neon" @click="showExtensionModal = false">Got it!</button>
          </div>
        </div>

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

<style scoped>
.tool-header {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 100%;
}

.extension-status {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.3s ease;
}

:global(:root[data-theme="light"]) .extension-status {
  background: rgba(0, 0, 0, 0.05);
  color: #666;
}

.extension-status:hover {
  background: rgba(255, 255, 255, 0.2);
  color: var(--text-color);
}

:global(:root[data-theme="light"]) .extension-status:hover {
  background: rgba(0, 0, 0, 0.1);
  color: #000;
}

.extension-status.connected {
  color: #4ade80; /* Green for connected */
  cursor: pointer; /* Allow clicking to see status */
}

/* :global(:root[data-theme="light"]) .extension-status.connected {
  color: #16a34a;
} */

.extension-status.connected:hover {
  background: rgba(74, 222, 128, 0.1);
}

/* :global(:root[data-theme="light"]) .extension-status.connected:hover {
  background: rgba(22, 163, 74, 0.1);
} */

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(4px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  position: relative;
  width: 90%;
  max-width: 500px;
  padding: 2rem;
  border-radius: 16px;
  background: var(--glass-bg);
  border: 1px solid var(--glass-border);
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
  text-align: center;
}

.close-btn {
  position: absolute;
  top: 1rem;
  right: 1rem;
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 50%;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-color);
}

.modal-content h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  font-size: 1.5rem;
  color: var(--text-color);
}

.modal-content p {
  margin-bottom: 1rem;
  line-height: 1.6;
  color: var(--text-color);
}

.description {
  color: var(--text-secondary) !important;
  font-size: 0.9rem;
  margin-bottom: 2rem !important;
}

.modal-actions {
  display: flex;
  justify-content: center;
}

.controls {
  display: flex;
  gap: 1rem;
  justify-content: center;
  flex-wrap: wrap;
}

.btn-neon {
  padding: 0.75rem 1.5rem;
  min-width: 120px;
}

.btn-neon.active {
  background: rgba(255, 0, 0, 0.2);
  border-color: rgba(255, 0, 0, 0.5);
  box-shadow: 0 0 15px rgba(255, 0, 0, 0.3);
}

.tool-textarea {
  height: 100%;
}
</style>
