<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useCollaborationStore } from '../stores/collaboration'
import { useWebSocket } from '../composables/useWebSocket'
import DocumentViewer from './DocumentViewer.vue'
import TimelinePanel from './TimelinePanel.vue'

const props = defineProps({
  sessionId: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['go-home'])

const collaborationStore = useCollaborationStore()
const ws = useWebSocket(props.sessionId)

const isRunningRound = ref(false)
const sessionStarted = ref(false)
const isAutoRunning = ref(false)
const autoRunTimeout = ref(null)
const currentWorkingAgent = ref(null)
const currentAgentThinking = ref('')
const isStopping = ref(false)

const currentSession = computed(() => collaborationStore.currentSession)
const currentDocument = computed(() => collaborationStore.currentDocument)
const agents = computed(() => currentSession.value?.agents || [])
const conversationHistory = computed(() => collaborationStore.conversationHistory)
const agentCount = computed(() => currentSession.value?.agentCount || 0)

// Convergence logic: consecutive rounds with no changes >= agent count
const hasConverged = computed(() => {
  if (conversationHistory.value.length < 1) return false
  let consecutiveNoChanges = 0
  for (let i = conversationHistory.value.length - 1; i >= 0; i--) {
    const round = conversationHistory.value[i]
    if (!round.agentsMadeChanges || round.agentsMadeChanges.length === 0) {
      consecutiveNoChanges++
    } else {
      break
    }
  }
  return consecutiveNoChanges >= agentCount.value
})

onMounted(async () => {
  try {
    await collaborationStore.getSession(props.sessionId)
    ws.connect()

    const messageInterval = setInterval(() => {
      if (ws.messages.value.length > 0) {
        const message = ws.messages.value.shift()
        handleWebSocketMessage(message)
      }
    }, 100)

    onUnmounted(() => {
      clearInterval(messageInterval)
      if (autoRunTimeout.value) clearTimeout(autoRunTimeout.value)
    })

    if (currentSession.value?.status === 'created') {
      await startSession()
    }
  } catch (error) {
    console.error('Error mounting collaborative session:', error)
  }
})

const handleWebSocketMessage = (message) => {
  if (message.type === 'initial_document_created') {
    sessionStarted.value = true
    collaborationStore.currentDocument = message.content
    currentWorkingAgent.value = null
    currentAgentThinking.value = ''
    scheduleNextRound(2000)
  } else if (message.type === 'document_modified') {
    collaborationStore.currentDocument = message.content
  } else if (message.type === 'agent_working') {
    currentWorkingAgent.value = message.agentName
    currentAgentThinking.value = ''
  } else if (message.type === 'agent_thinking') {
    currentAgentThinking.value = message.thinking || ''
  } else if (message.type === 'round_complete') {
    isRunningRound.value = false
    collaborationStore.conversationHistory.push({
      roundNumber: message.roundNumber,
      agentsMadeChanges: message.agentsMadeChanges,
      timestamp: Date.now()
    })
    currentWorkingAgent.value = null
    currentAgentThinking.value = ''

    if (hasConverged.value) {
      isAutoRunning.value = false
      setTimeout(() => {
        completeSession()
      }, 2000)
    } else {
      scheduleNextRound(1500)
    }
  } else if (message.type === 'session_error') {
    console.error('Session error:', message.error)
    isRunningRound.value = false
    isAutoRunning.value = false
    currentWorkingAgent.value = null
  } else if (message.type === 'session_completed') {
    currentWorkingAgent.value = null
    isAutoRunning.value = false
  }
}

const scheduleNextRound = (delay) => {
  if (autoRunTimeout.value) clearTimeout(autoRunTimeout.value)
  if (isStopping.value) return
  isAutoRunning.value = true
  autoRunTimeout.value = setTimeout(() => {
    runNextRoundAuto()
  }, delay)
}

const runNextRoundAuto = async () => {
  if (isRunningRound.value || hasConverged.value || isStopping.value) return

  isRunningRound.value = true
  try {
    await collaborationStore.runRound(props.sessionId)
  } catch (error) {
    console.error('Error running round:', error)
    isRunningRound.value = false
    isAutoRunning.value = false
  }
}

const startSession = async () => {
  try {
    await collaborationStore.startSession(props.sessionId)
  } catch (error) {
    console.error('Error starting session:', error)
  }
}

const completeSession = async () => {
  try {
    isAutoRunning.value = false
    if (autoRunTimeout.value) clearTimeout(autoRunTimeout.value)
    await collaborationStore.completeSession(props.sessionId)
    // Stay on the session page - don't redirect
  } catch (error) {
    console.error('Error completing session:', error)
  }
}

const stopSession = async () => {
  isStopping.value = true
  isAutoRunning.value = false
  if (autoRunTimeout.value) clearTimeout(autoRunTimeout.value)
  await completeSession()
}

const downloadDocument = () => {
  const format = currentSession.value?.documentFormat || 'md'
  const extension = format === 'md' ? 'md' : 'txt'
  collaborationStore.downloadDocument(`collaborative-document.${extension}`)
}

function formatAgentName(agent) {
  if (!agent) return 'Unknown'
  return agent.charAt(0).toUpperCase() + agent.slice(1)
}
</script>

<template>
  <div class="collaborative-session">
    <!-- Header -->
    <div class="session-header">
      <div class="header-content">
        <h1>Collaborative Design</h1>
        <p class="session-meta">
          <span>Session #{{ sessionId }}</span>
          <span class="badge" :class="{ active: sessionStarted, converged: hasConverged }">
            {{ hasConverged ? 'Converged' : sessionStarted ? 'Active' : 'Waiting' }}
          </span>
        </p>
      </div>

      <div class="header-actions">
        <button
          @click="downloadDocument"
          :disabled="!currentDocument"
          class="download-btn"
          title="Download the document"
        >
          Download
        </button>

        <button
          v-if="!hasConverged && (isAutoRunning || isRunningRound)"
          @click="stopSession"
          class="stop-btn"
          title="Stop the session"
        >
          Stop
        </button>

        <button
          v-if="hasConverged"
          @click="$emit('go-home')"
          class="home-btn"
          title="Start new session"
        >
          Home
        </button>

        <div v-if="isAutoRunning || isRunningRound" class="auto-run-indicator">
          <span class="pulse"></span>
          Auto-running...
        </div>
      </div>
    </div>

    <!-- Working Agent Display -->
    <div v-if="currentWorkingAgent" class="working-agent-card">
      <div class="raised-hand-animation">
        <span class="hand">✋</span>
      </div>
      <div class="agent-name-working">{{ formatAgentName(currentWorkingAgent) }}</div>
    </div>

    <!-- Convergence Message -->
    <div v-if="hasConverged" class="convergence-message">
      <span class="checkmark">[OK]</span>
      All {{ agentCount }} agents have reviewed and approved. Session complete!
    </div>

    <!-- Team Display -->
    <div class="team-display">
      <h3>Team</h3>
      <div class="team-grid">
        <div v-for="agent in agents" :key="agent" class="team-member">
          {{ formatAgentName(agent) }}
        </div>
      </div>
    </div>

    <!-- Main Document -->
    <div class="document-section">
      <div class="document-header">
        <h2>Architecture Document</h2>
        <span v-if="currentDocument" class="doc-status">Live</span>
      </div>
      <DocumentViewer
        :document="currentDocument || 'Waiting for initial document...'"
        :format="currentSession?.documentFormat || 'md'"
      />
    </div>
  </div>
</template>

<style scoped>
@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@keyframes raise-hand {
  0% { transform: translateY(0) rotate(0deg); }
  25% { transform: translateY(-10px) rotate(-5deg); }
  50% { transform: translateY(-20px) rotate(5deg); }
  75% { transform: translateY(-10px) rotate(-5deg); }
  100% { transform: translateY(0) rotate(0deg); }
}

.collaborative-session {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.session-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  background: rgba(255, 255, 255, 0.07);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.1);
}

.header-content h1 {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.session-meta {
  margin-top: 0.5rem;
  display: flex;
  gap: 1rem;
  align-items: center;
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
}

.badge {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.4rem 0.9rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 500;
}

.badge.active {
  background: rgba(102, 126, 234, 0.2);
  border-color: rgba(102, 126, 234, 0.4);
  color: rgba(102, 126, 234, 0.95);
}

.badge.converged {
  background: rgba(76, 175, 80, 0.2);
  border-color: rgba(76, 175, 80, 0.4);
  color: rgba(76, 175, 80, 0.95);
}

.header-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.download-btn {
  padding: 0.75rem 1.5rem;
  background: rgba(102, 126, 234, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.download-btn:hover:not(:disabled) {
  background: rgba(102, 126, 234, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.download-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.stop-btn {
  padding: 0.75rem 1.5rem;
  background: rgba(244, 67, 54, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.stop-btn:hover {
  background: rgba(244, 67, 54, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(244, 67, 54, 0.3);
}

.home-btn {
  padding: 0.75rem 1.5rem;
  background: rgba(76, 175, 80, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.home-btn:hover {
  background: rgba(76, 175, 80, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(76, 175, 80, 0.3);
}

.auto-run-indicator {
  display: flex;
  align-items: center;
  gap: 0.6rem;
  padding: 0.5rem 1rem;
  background: rgba(76, 175, 80, 0.15);
  border: 1px solid rgba(76, 175, 80, 0.3);
  border-radius: 10px;
  font-size: 0.85rem;
  color: rgba(76, 175, 80, 0.9);
  font-weight: 500;
}

.pulse {
  display: inline-block;
  width: 6px;
  height: 6px;
  background: rgba(76, 175, 80, 0.8);
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

.working-agent-card {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 1.5rem;
  background: rgba(102, 126, 234, 0.1);
  border: 2px solid rgba(102, 126, 234, 0.4);
  border-radius: 16px;
  backdrop-filter: blur(10px);
}

.raised-hand-animation {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.hand {
  font-size: 2.5rem;
  animation: raise-hand 1s infinite;
}

.agent-name-working {
  font-size: 1.2rem;
  color: rgba(102, 126, 234, 0.95);
  font-weight: 600;
}

.convergence-message {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1.2rem;
  background: rgba(76, 175, 80, 0.1);
  border: 1px solid rgba(76, 175, 80, 0.3);
  border-radius: 12px;
  color: rgba(76, 175, 80, 0.95);
  font-weight: 500;
  backdrop-filter: blur(10px);
}

.checkmark {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: rgba(76, 175, 80, 0.3);
  border-radius: 50%;
  font-weight: 700;
  font-size: 0.9rem;
}

.team-display {
  padding: 1rem;
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
}

.team-display h3 {
  margin: 0 0 0.75rem 0;
  font-size: 0.95rem;
  color: rgba(255, 255, 255, 0.8);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  font-weight: 600;
}

.team-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 0.6rem;
}

.team-member {
  padding: 0.6rem 0.9rem;
  background: rgba(102, 126, 234, 0.12);
  border: 1px solid rgba(102, 126, 234, 0.25);
  border-radius: 8px;
  font-size: 0.85rem;
  color: rgba(102, 126, 234, 0.95);
  font-weight: 500;
  text-align: center;
  transition: all 0.3s ease;
}

.team-member:hover {
  background: rgba(102, 126, 234, 0.2);
  border-color: rgba(102, 126, 234, 0.4);
}

.document-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.document-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.document-header h2 {
  margin: 0;
  font-size: 1.2rem;
  color: white;
}

.doc-status {
  display: inline-block;
  padding: 0.3rem 0.7rem;
  background: rgba(76, 175, 80, 0.2);
  border: 1px solid rgba(76, 175, 80, 0.3);
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 600;
  color: rgba(76, 175, 80, 0.9);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}
</style>
