<template>
  <div class="welcome-screen">
    <!-- Mobile-only sidebar toggle, pinned to top-left corner -->
    <GnIconButton icon="ph ph-sidebar" label="Menu" class="welcome-sidebar-btn" @click="emit('toggle-sidebar')" />

    <div class="welcome-logo">
      <img src="/images/logo.svg" alt="Navi" />
      <h1>Navi</h1>
      <p>Your personal AI assistant</p>
    </div>

    <div v-if="profilesStore.profiles.length" class="welcome-profiles">
      <div
        v-for="p in profilesStore.profiles"
        :key="p.id"
        class="welcome-profile-card"
        :class="{ 'is-selected': selectedId === p.id }"
        @click="selectedId = p.id"
      >
        <GnAvatar size="md" variant="secondary" :icon="profileIcon(p)" />
        <div class="profile-name">{{ p.name }}</div>
        <div class="profile-desc">{{ p.description }}</div>
      </div>
    </div>

    <GnButton
      variant="primary"
      :disabled="!selectedId || creating"
      :loading="creating"
      icon="ph ph-chat-centered-text"
      @click="handleStart"
    >
      Start a conversation
    </GnButton>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const emit = defineEmits(['toggle-sidebar'])
import { useProfilesStore } from '@/stores/profiles.js'
import { useSessionsStore } from '@/stores/sessions.js'
import { useChatStore } from '@/stores/chat.js'

const profilesStore = useProfilesStore()
const sessionsStore = useSessionsStore()
const chatStore = useChatStore()

const selectedId = ref(profilesStore.selectedProfileId ?? profilesStore.profiles[0]?.id ?? null)
const creating = ref(false)

const PROFILE_ICONS = {
  secretary: 'ph-briefcase',
  server_admin: 'ph-terminal',
  developer: 'ph-code',
  tool_developer: 'ph-wrench',
  discuss: 'ph-chats',
}

function profileIcon(p) {
  const cls = PROFILE_ICONS[p.id] ?? 'ph-robot'
  return `ph ${cls}`
}

async function handleStart() {
  if (!selectedId.value || creating.value) return
  creating.value = true
  try {
    profilesStore.selectedProfileId = selectedId.value
    const session = await sessionsStore.createSession(selectedId.value)
    await chatStore.loadSession(session.session_id)
  } catch (err) {
    console.error('[welcome] start failed', err)
  } finally {
    creating.value = false
  }
}
</script>

<style scoped>
.welcome-sidebar-btn {
  display: none;
  position: absolute;
  top: 12px;
  left: 12px;

  @media (max-width: 1280px) {
    display: flex;
  }
}
</style>
