<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import Splitter from 'primevue/splitter'
import SplitterPanel from 'primevue/splitterpanel'
import ChartView from './components/ChartView.vue'
import ChatPanel from './components/ChatPanel.vue'
import LoginScreen from './components/LoginScreen.vue'
import { useChartStore } from './stores/chart'
import { useShapeStore } from './stores/shapes'
import { useIndicatorStore } from './stores/indicators'
import { useIndicatorTypesStore } from './stores/indicatorTypes'
import { useChannelStore } from './stores/channel'
import { useStateSync } from './composables/useStateSync'
import { wsManager } from './composables/useWebSocket'
import { authService } from './composables/useAuth'

const isAuthenticated = authService.isAuthenticated
const authError = ref<string>()
const isDragging = ref(false)
const isMobile = ref(false)
let stateSyncCleanup: (() => void) | null = null

// Check screen width for mobile layout
const checkMobile = () => {
  isMobile.value = window.innerWidth < 768
}

const chartStore = useChartStore()

// Watch mobile state and update ChartStore
watch(isMobile, (mobile) => {
  if (mobile) {
    // Set all chart state to null when chart is hidden
    chartStore.symbol = null as any
    chartStore.start_time = null
    chartStore.end_time = null
    chartStore.period = null as any
  }
})

// Check if user is already authenticated on page load
onMounted(async () => {
  // Try to restore session from stored token
  const token = authService.getToken()
  if (token) {
    const sessionValid = await authService.checkAuth()
    if (sessionValid) {
      isAuthenticated.value = true
      // Connect WebSocket with existing token
      try {
        await wsManager.connect(token)
        await initializeApp()
      } catch (err) {
        console.error('Failed to connect WebSocket on session restore:', err)
      }
    }
  }

  // Initialize mobile check
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

const handleAuthenticate = async (email: string, password: string) => {
  authError.value = undefined

  try {
    // Step 1: Login via HTTP to get JWT token
    const result = await authService.login(email, password)

    if (!result.success) {
      authError.value = result.error || 'Login failed'
      return
    }

    if (!result.token) {
      authError.value = 'No token received from server'
      return
    }

    // Step 2: Connect WebSocket with JWT token for real-time sync
    await wsManager.connect(result.token)

    // Step 3: Initialize application
    await initializeApp()
  } catch (err: any) {
    authError.value = err.message || 'Authentication failed'
    console.error('Authentication error:', err)
  }
}

const initializeApp = async () => {
  // Initialize state sync after successful authentication
  const chartStore = useChartStore()
  const shapeStore = useShapeStore()
  const indicatorStore = useIndicatorStore()
  const indicatorTypesStore = useIndicatorTypesStore()
  const channelStore = useChannelStore()
  const stateSync = useStateSync({
    chartState: chartStore,
    shapes: shapeStore,
    indicators: indicatorStore,
    indicator_types: indicatorTypesStore,
    channelState: channelStore
  })
  stateSyncCleanup = stateSync.cleanup
}

onMounted(() => {
  // Listen for splitter drag events
  document.addEventListener('mousedown', (e) => {
    // Check if the mousedown is on a splitter gutter
    const target = e.target as HTMLElement
    if (target.closest('.p-splitter-gutter')) {
      isDragging.value = true
    }
  })

  document.addEventListener('mouseup', () => {
    isDragging.value = false
  })
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', checkMobile)
  if (stateSyncCleanup) {
    stateSyncCleanup()
  }
  wsManager.disconnect()
})
</script>

<template>
  <div class="app-container dark">
    <LoginScreen
      v-if="!isAuthenticated"
      :error-message="authError"
      @authenticate="handleAuthenticate"
    />
    <Splitter v-else-if="!isMobile" class="main-splitter">
      <SplitterPanel :size="62" :minSize="40" class="chart-panel">
        <ChartView />
      </SplitterPanel>
      <SplitterPanel :size="38" :minSize="20" class="chat-panel">
        <ChatPanel />
      </SplitterPanel>
    </Splitter>
    <div v-else class="mobile-layout">
      <ChatPanel />
    </div>
    <!-- Transparent overlay to prevent iframe from capturing mouse events during drag -->
    <div v-if="isDragging" class="drag-overlay"></div>
  </div>
</template>

<style scoped>
.app-container {
  width: 100vw !important;
  height: 100vh !important;
  overflow: hidden;
  background: #0f0f0f !important;
}

.app-container.dark {
  background: #0f0f0f !important;
}

.main-splitter {
  height: 100vh !important;
  background: #0f0f0f !important;
}

.main-splitter :deep(.p-splitter-gutter) {
  background: #2e2e2e !important;
}

.main-splitter :deep(.p-splitter-gutter-handle) {
  background: #2e2e2e !important;
}

.chart-panel,
.chat-panel {
  height: 100% !important;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chart-panel :deep(.p-splitter-panel-content),
.chat-panel :deep(.p-splitter-panel-content) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.drag-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  cursor: col-resize;
  background: transparent;
}

.mobile-layout {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

@media (max-width: 767px) {
  .main-splitter {
    display: none;
  }
}
</style>
