<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../../stores/auth_store'
import * as analysisRepository from '../../repositories/analysis_repository'

const props = defineProps({
  jobId: { type: String, required: true }
})

const authStore = useAuthStore()
const tabs = ref([])
const selectedTab = ref(null)
const pushing = ref(false)
const notice = ref(null)

onMounted(async () => {
  try {
    const data = await analysisRepository.getSheetTabs(authStore.email)
    tabs.value = data.tabs || []
    selectedTab.value = tabs.value[0] || null
  } catch {
    // Apps Script plugin (Phase 4) isn't installed/deployed yet — the
    // backend returns a structured 501 for this, which we surface as
    // a plain, non-alarming notice rather than an error toast.
    notice.value = 'Push to Sheet needs the Bettersight Sheets plugin — install it from your Account page.'
  }
})

async function push() {
  pushing.value = true
  try {
    await analysisRepository.pushToSheet(authStore.email, props.jobId, selectedTab.value)
    await authStore.updateOnboarding({ push_to_sheet: true })
    notice.value = 'Pushed to Sheet ✓'
  } catch {
    notice.value = 'Push to Sheet needs the Bettersight Sheets plugin — install it from your Account page.'
  } finally {
    pushing.value = false
  }
}
</script>

<template>
  <div class="card" style="padding:16px 20px;display:flex;align-items:center;gap:10px;" data-tour="push-to-sheet">
    <USelect
      v-if="tabs.length"
      v-model="selectedTab"
      :items="tabs"
      style="width:200px;"
    />
    <UButton color="primary" :disabled="!tabs.length" :loading="pushing" @click="push">
      Push to Sheet
    </UButton>
    <span v-if="notice" style="font-size:12px;color:var(--t3);">{{ notice }}</span>
  </div>
</template>
