import { createSSRApp } from 'vue'

import 'uno.css'
import * as Pinia from 'pinia'
import App from './App.vue'
import { getShareAppMessageOptions, getShareTimelineOptions } from './composables/useWechatShare'

export function createApp() {
  const app = createSSRApp(App)
  app.use(Pinia.createPinia())

  // 微信小程序：全局启用右上角「分享给朋友」「分享到朋友圈」
  // #ifdef MP-WEIXIN
  app.mixin({
    onShareAppMessage() {
      const pages = getCurrentPages()
      const page = pages[pages.length - 1]
      if (!page) return getShareAppMessageOptions()
      const route = page.route || 'pages/index'
      const options = page.options || {}
      const query = Object.keys(options)
        .map((k) => `${k}=${encodeURIComponent(options[k])}`)
        .join('&')
      const path = query ? `${route}?${query}` : route
      return getShareAppMessageOptions({ path })
    },
    onShareTimeline() {
      const pages = getCurrentPages()
      const page = pages[pages.length - 1]
      if (!page) return getShareTimelineOptions()
      const options = page.options || {}
      const query = Object.keys(options)
        .map((k) => `${k}=${encodeURIComponent(options[k])}`)
        .join('&')
      return getShareTimelineOptions({ query })
    },
  })
  // #endif

  return {
    app,
    Pinia,
  }
}
