import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface TorchClient {
  id: string
  name: string
  autoRequest: boolean
  userAgent: string
  hostname: string
  url: string
  connectedAt: string
  hasTorch: boolean
}

export const useTorchStore = defineStore('torch', () => {
  // State
  const clientId = ref<string | null>(null)
  const hasTorch = ref(false)
  const torchHolderId = ref<string | null>(null)
  const clients = ref<TorchClient[]>([])
  const isRequesting = ref(false)
  const clientName = ref(localStorage.getItem('torch-client-name') || '')
  const autoRequest = ref(localStorage.getItem('torch-auto-request') === 'true')

  // Computed
  const isConnected = computed(() => clientId.value !== null)
  const torchHolder = computed(() => clients.value.find(c => c.hasTorch))

  // Actions
  function setClientId(id: string) {
    clientId.value = id
  }

  function setTorchState(holder: string | null) {
    torchHolderId.value = holder
    hasTorch.value = holder === clientId.value
  }

  function setClients(newClients: TorchClient[]) {
    clients.value = newClients
    // Update torch state based on clients
    const holder = newClients.find(c => c.hasTorch)
    torchHolderId.value = holder?.id || null
    hasTorch.value = holder?.id === clientId.value
  }

  function setRequesting(value: boolean) {
    isRequesting.value = value
  }

  function setClientName(name: string) {
    clientName.value = name
    localStorage.setItem('torch-client-name', name)
  }

  function setAutoRequest(val: boolean) {
    autoRequest.value = val
    localStorage.setItem('torch-auto-request', String(val))
  }

  function reset() {
    clientId.value = null
    hasTorch.value = false
    torchHolderId.value = null
    clients.value = []
    isRequesting.value = false
    // Do NOT reset clientName/autoRequest — persist across sessions
  }

  return {
    // State
    clientId,
    hasTorch,
    torchHolderId,
    clients,
    isRequesting,
    clientName,
    autoRequest,
    // Computed
    isConnected,
    torchHolder,
    // Actions
    setClientId,
    setTorchState,
    setClients,
    setRequesting,
    setClientName,
    setAutoRequest,
    reset
  }
})
