<script setup>
definePage({
  layout: 'PageLayout',
  style: {
    navigationBarTitleText: '客服',
    navigationStyle: 'default',
  },
})

import { ref, onMounted } from 'vue'

// 与 webview Service.vue 一致：可选环境变量，未配置则用默认 Chatwoot
const chatwootBaseUrl = import.meta.env?.VITE_CHATWOOT_BASE_URL || 'https://service.quannengcha.com'
const chatwootToken = import.meta.env?.VITE_CHATWOOT_WEBSITE_TOKEN || 'XJqwnEWKVNte8iJW8DLroEzd'
const serviceUrl = import.meta.env?.VITE_SERVICE_URL || ''

const chatwootReady = ref(false)

// #ifdef H5
onMounted(() => {
  const d = document
  const t = 'script'
  const g = d.createElement(t)
  const s = d.getElementsByTagName(t)[0]
  g.src = chatwootBaseUrl + '/packs/js/sdk.js'
  g.defer = true
  g.async = true
  s.parentNode.insertBefore(g, s)
  g.onload = function () {
    if (typeof window.chatwootSDK !== 'undefined') {
      window.chatwootSDK.run({
        websiteToken: chatwootToken,
        baseUrl: chatwootBaseUrl,
        type: 'expanded_bubble',
      })
      chatwootReady.value = true
    }
  }
})
// #endif

function openChatwoot() {
  // #ifdef H5
  if (chatwootReady.value && typeof window.chatwootSDK !== 'undefined' && window.chatwootSDK.open) {
    window.chatwootSDK.open()
  } else {
    const launcher = document.querySelector('[data-chatwoot-widget]') || document.querySelector('.woot--bubble-holder') || document.querySelector('[class*="woot"]')
    if (launcher) launcher.click()
  }
  // #endif
}

function openServiceUrl() {
  if (serviceUrl) {
    // #ifdef H5
    window.location.href = serviceUrl
    // #endif
    // #ifndef H5
    uni.navigateTo({ url: '/pages/webview/index?url=' + encodeURIComponent(serviceUrl) })
    // #endif
  } else {
    uni.showToast({ title: '暂未配置客服链接', icon: 'none' })
  }
}
</script>

<template>
  <view class="service-page p-4 min-h-screen bg-gray-50">
    <view class="support-chat rounded-xl bg-white shadow-sm p-6 text-center">
      <view class="text-xl font-bold text-primary mb-2">在线客服</view>
      <view class="text-gray-600 text-sm mb-4">如果您有任何问题，请通过在线客服联系我们。</view>

      <!-- H5：本页已加载 Chatwoot，点击打开气泡 -->
      <!-- #ifdef H5 -->
      <wd-button type="primary" block class="mb-3" @click="openChatwoot">
        打开在线客服
      </wd-button>
      <view class="text-xs text-gray-400 mb-2">或请留意页面右下角客服气泡</view>
      <!-- #endif -->

      <!-- 外链客服：VITE_SERVICE_URL 配置后可用，小程序端主要依赖此方式 -->
      <wd-button v-if="serviceUrl" type="default" block outline @click="openServiceUrl">
        联系客服
      </wd-button>
      <view v-else class="text-gray-500 text-sm">可在 .env 中配置 VITE_SERVICE_URL 作为客服链接</view>
    </view>
  </view>
</template>

<style scoped>
.service-page {
  box-sizing: border-box;
}
.support-chat view {
  word-break: break-all;
}
</style>
