<template>
  <div class="built-in-app" :class="[`app-${appId}`, { 'fullscreen': isFullscreen }]">
    <div class="app-container">
      <slot></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { inject, onMounted, onUnmounted, ref, provide } from 'vue'
import type { SystemServiceIntegration } from '@/services/SystemServiceIntegration'

const props = defineProps<{
  appId: string
  title?: string
}>()

const isFullscreen = ref(false)
const systemService = inject<SystemServiceIntegration>('systemService')

// 为子组件提供应用上下文
const appContext = {
  appId: props.appId,
  title: props.title || props.appId,
  systemService,
  // 直接暴露系统服务的方法，简化调用
  storage: systemService?.getResourceService(),
  events: systemService?.getEventService(),
  lifecycle: systemService?.getLifecycleManager(),
  window: {
    setTitle: (title: string) => {
      if (window.SystemSDK) {
        window.SystemSDK.window.setTitle(title)
      }
    },
    toggleFullscreen: () => {
      isFullscreen.value = !isFullscreen.value
    }
  }
}

// 提供应用上下文给子组件
provide('appContext', appContext)

// SDK初始化 - 简化版本
onMounted(async () => {
  try {
    if (window.SystemSDK) {
      await window.SystemSDK.init({
        appId: props.appId,
        appName: props.title || props.appId,
        version: '1.0.0',
        permissions: ['storage', 'notification']
      })
      
      if (props.title) {
        await window.SystemSDK.window.setTitle(props.title)
      }
      
      console.log(`内置应用 ${props.appId} 初始化成功`)
    }
  } catch (error) {
    console.error(`内置应用 ${props.appId} 初始化失败:`, error)
  }
})

// 清理
onUnmounted(() => {
  if (window.SystemSDK && window.SystemSDK.initialized) {
    window.SystemSDK.destroy?.()
  }
})

// 切换全屏模式
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

// 暴露方法给父组件
defineExpose({
  toggleFullscreen,
  appContext
})
</script>

<style scoped>
.built-in-app {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.app-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
}

/* 应用特定样式 */
.app-calculator {
  max-width: 400px;
  margin: 0 auto;
}

.app-notepad {
  padding: 10px;
}

.app-todo {
  /* 待办事项应用样式 */
}
</style>