<script setup lang="ts">
import pyApi from "@/py_api";
import use_app_store from "@/store/app";
import { getVersion } from "@tauri-apps/api/app";
import {
  getCurrentWindow,
  LogicalPosition,
  LogicalSize,
} from "@tauri-apps/api/window";
import { LazyStore } from "@tauri-apps/plugin-store";
import { onMounted, ref, watch, computed } from "vue";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

const is_dev = import.meta.env.DEV;
const appVersion = ref("");
const app_store = use_app_store();
const ready = ref(false);
const darkTheme = ref(false);
const randomIconPath = ref("");

// 新UI中需要的数据
const settings = ref({
  autostart: true,
  showWindow: true
});

// 当前视图计算
const currentView = computed(() => route.name || 'home');

// 视图标题计算
const viewTitle = computed(() => {
  switch (currentView.value) {
    case 'home': return '控制面板';
    case 'gestures': return '手势管理';
    case 'settings': return '设置中心';
    case 'help': return '帮助文档';
    default: return 'WaveControl';
  }
});

// 在组件挂载时生成随机图标
onMounted(() => {
  const randomIndex = Math.floor(Math.random() * 9) + 1;
  randomIconPath.value = `/wavecontrol${randomIndex}.jpg`;
});

// 初始化逻辑
onMounted(async () => {
  ready.value = await pyApi.ready();

  const timer = setInterval(async () => {
    ready.value = await pyApi.ready();
    if (ready.value) {
      clearInterval(timer);
    }
  }, 5000);

  await getCurrentWindow().onCloseRequested(async () => {
    const factor = await getCurrentWindow().scaleFactor();
    const position = (await getCurrentWindow().innerPosition()).toLogical(factor);
    const size = (await getCurrentWindow().innerSize()).toLogical(factor);
    await window_store_json.set("window_state", {
      x: position.x,
      y: position.y,
      width: size.width,
      height: size.height,
    });

    if (!is_dev) {
      await pyApi.shutdown();
    }
  });
});
// 窗口恢复上一次位置
const window_store_json = new LazyStore("window_state.json");
onMounted(async () => {
  appVersion.value = await getVersion();
  const window_state = await window_store_json.get("window_state");
  if (window_state) {
    let new_x = window_state.x;
    let new_y = window_state.y;
    const screen_width = window.screen.width;
    const screen_height = window.screen.height;

    // 如果窗口位置超出屏幕，则将窗口位置设置为100，100
    if (new_x <= 0) new_x = 100;
    if (new_x >= screen_width) new_x = 100
    if (new_y <= 0) new_y = 100;
    if (new_y >= screen_height) new_y = 100;

    getCurrentWindow().setPosition(new LogicalPosition(new_x, new_y));
    getCurrentWindow().setSize(
      new LogicalSize(window_state.width, window_state.height)
    );
  }
});

// app_store 数据加载
const app_store_json = new LazyStore("settings.json");
onMounted(async () => {
  const config_data = await app_store_json.get("config");
  console.log("config_data", config_data);
  if (config_data) {
    Object.assign(app_store.config, JSON.parse(JSON.stringify(config_data)));
  }
});

watch(
  () => app_store.config,
  async (value) => {
    await app_store_json.set("config", value);
    app_store_json.save();
  },
  { deep: true }
);

// 通知
import {
  isPermissionGranted,
  requestPermission,
} from "@tauri-apps/plugin-notification";

onMounted(async () => {
  let permissionGranted = await isPermissionGranted();
  if (!permissionGranted) {
    const permission = await requestPermission();
    permissionGranted = permission === "granted";
  }
});

// 使用默认浏览器打开 iframe 中的 <a> 标签
import { openUrl } from "@tauri-apps/plugin-opener";
window.addEventListener("message", async function (e) {
  const url = e.data;
  if (url) {
    await openUrl(url);
  }
});

// 创建子窗口
import { createSubWindow } from "@/utils/subWindow";
const subWindow = ref(null);
onMounted(async () => {
  if (!subWindow.value) {
    subWindow.value = await createSubWindow("/sub-window", "subWindow");
  }
});

// 操作方法
const toggleTheme = () => {
  darkTheme.value = !darkTheme.value;
};

const switchView = (viewName: string) => {
  router.push({ name: viewName });
};

const toggleSetting = (setting: string) => {
  settings.value[setting] = !settings.value[setting];
};

// 状态计算属性
const statusClass = computed(() => ({
  'status-active': ready.value,
  'status-inactive': !ready.value
}));

const statusText = computed(() => {
  return ready.value ? '运行中' : '已停止';
});
</script>

<template>
  <div class="app-container" :class="{'dark-theme': darkTheme}">
    <!-- 加载状态 -->
    <div v-if="!ready" class="loading-overlay">
      <div class="loader-container">
        <div class="spinner"></div>
        <div class="loading-text">手势识别模块加载中...</div>
      </div>
    </div>

    <!-- 主界面 -->
    <div v-else class="main-layout">
      <!-- 左侧导航 -->
      <div class="sidebar">
        <div class="branding">
          <!-- 使用随机图标路径 -->
          <img :src="randomIconPath" alt="WaveControl Logo" class="logo" /> 
          <div class="app-info">
            <div class="app-name">WaveControl</div>
          </div>
        </div>
        
        <div class="nav-items">
          <div class="nav-item" :class="{active: currentView === 'home'}" @click="switchView('home')">
            <i class="icon">🏠</i>
            <span>主控台</span>
          </div>
          <div class="nav-item" :class="{active: currentView === 'guide'}" @click="switchView('guide')">
            <i class="icon">👋</i>
            <span>手势管理</span>
          </div>
          <div class="nav-item" :class="{active: currentView === 'settings'}" @click="switchView('settings')">
            <i class="icon">⚙️</i>
            <span>设置</span>
          </div>
          <div class="nav-item" :class="{active: currentView === 'help'}" @click="switchView('help')">
            <i class="icon">❓</i>
            <span>帮助</span>
          </div>
        </div>
        
        <div class="status-card">
          <div class="status-indicator" :class="statusClass">
            {{ statusText }}
          </div>
          <div class="fps-counter">
            <span>FPS</span>
            <span class="value">60</span>
          </div>
        </div>
        
        <div class="contributors">
          <div v-if="app_store.is_macos()">
            <a
              class="contributor-link"
              href="https://gitee.com/wydhhh/software-engineering"
              target="_blank"
            >
              @backpack</a
            >
          </div>
          <div v-else class="contributor">@ninjakelly</div>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="content-area">
        <div class="header-bar">
          <div class="title-container">
            <h1 class="view-title">{{ viewTitle }}</h1>
            <div class="view-description">隔空手势控制系统</div>
          </div>
          
          <div class="controls">
            <button class="theme-toggle" @click="toggleTheme">
              <i class="icon">{{ darkTheme ? '☀️' : '🌙' }}</i>
            </button>
          </div>
        </div>
        
        <div class="main-content">
          <router-view />
        </div>
      </div>
    </div>
    
    <DevTool v-if="is_dev" />
  </div>
</template>

<style scoped lang="scss">
.app-container {
  font-family: 'Segoe UI', system-ui, sans-serif;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  transition: background-color 0.3s, color 0.3s;
  
  &.dark-theme {
    --bg-primary: #0f172a;
    --bg-secondary: #1e293b;
    --bg-tertiary: #334155;
    --text-primary: #f1f5f9;
    --text-secondary: #94a3b8;
    --accent-primary: #0ea5e9;
    --accent-secondary: #7dd3fc;
    --hover-bg: rgba(148, 163, 184, 0.12);
    --border-color: #334155;
    --card-bg: rgba(30, 41, 59, 0.7);
    --shadow-color: rgba(0, 0, 0, 0.4);
    --status-active: #0ea5e9;
    --status-inactive: #475569;
  }
  
  &:not(.dark-theme) {
    --bg-primary: #f8fafc;
    --bg-secondary: #f1f5f9;
    --bg-tertiary: #e2e8f0;
    --text-primary: #0f172a;
    --text-secondary: #475569;
    --accent-primary: #0284c7;
    --accent-secondary: #0ea5e9;
    --hover-bg: rgba(15, 23, 42, 0.05);
    --border-color: #cbd5e1;
    --card-bg: rgba(241, 245, 249, 0.7);
    --shadow-color: rgba(0, 0, 0, 0.08);
    --status-active: #0284c7;
    --status-inactive: #94a3b8;
  }
  
  background-color: var(--bg-primary);
  color: var(--text-primary);
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--bg-primary);
  z-index: 100;
}

.loader-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(14, 165, 233, 0.2);
  border-radius: 50%;
  border-top: 4px solid var(--accent-primary);
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 18px;
  font-weight: 500;
  color: var(--text-primary);
}

.main-layout {
  display: flex;
  height: 100vh;
}

/* 左侧导航样式 */
.sidebar {
  width: 260px;
  background-color: var(--bg-secondary);
  display: flex;
  flex-direction: column;
  padding: 25px 0;
  border-right: 1px solid var(--border-color);
  z-index: 10;
}

.branding {
  display: flex;
  align-items: center;
  padding: 0 20px 20px;
}

.logo {
  width: 42px;
  height: 42px;
  border-radius: 10px;
  margin-right: 12px;
  background: linear-gradient(135deg, var(--accent-primary), #7dd3fc);
  padding: 5px;
}

.app-info {
  display: flex;
  flex-direction: column;
}

.app-name {
  font-size: 18px;
  font-weight: 700;
  letter-spacing: 0.5px;
  color: var(--text-primary);
}

.app-version {
  font-size: 13px;
  color: var(--text-secondary);
  font-weight: 500;
  opacity: 0.8;
}

.nav-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 0 15px;
  flex: 1;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s;
  gap: 14px;
  font-size: 16px;
  color: var(--text-secondary);
  
  &:hover {
    background-color: var(--hover-bg);
    color: var(--text-primary);
  }
  
  &.active {
    background: rgba(14, 165, 233, 0.15);
    color: var(--accent-primary);
    font-weight: 500;
    
    .icon {
      color: var(--accent-primary);
    }
  }
}

.icon {
  font-size: 18px;
}

.status-card {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 20px;
  margin: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid var(--border-color);
  box-shadow: 0 4px 6px var(--shadow-color);
}

.status-indicator {
  display: inline-flex;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
  padding: 6px 12px;
  border-radius: 20px;
  
  &::before {
    content: '';
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 8px;
  }
  
  &.status-active {
    background: rgba(14, 165, 233, 0.2);
    color: var(--accent-primary);
    
    &::before {
      background-color: var(--accent-primary);
    }
  }
  
  &.status-inactive {
    background: rgba(148, 163, 184, 0.2);
    color: var(--text-secondary);
    
    &::before {
      background-color: var(--text-secondary);
    }
  }
}

.fps-counter {
  margin-top: 15px;
  display: flex;
  align-items: baseline;
  gap: 8px;
  
  span {
    font-size: 14px;
    color: var(--text-secondary);
  }
  
  .value {
    font-size: 24px;
    font-weight: 600;
    color: var(--accent-primary);
  }
}

.contributors {
  padding: 20px;
  color: var(--text-secondary);
  font-size: 14px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  
  .contributor {
    padding: 5px 12px;
    border-radius: 6px;
    background-color: var(--bg-tertiary);
  }
  
  .contributor-link {
    color: var(--accent-primary);
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

/* 主内容区域样式 */
.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25px 30px 15px;
  border-bottom: 1px solid var(--border-color);
}

.title-container {
  display: flex;
  flex-direction: column;
}

.view-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0;
  color: var(--text-primary);
  line-height: 1.2;
}

.view-description {
  font-size: 15px;
  color: var(--text-secondary);
  margin-top: 6px;
}

.controls {
  display: flex;
  gap: 15px;
}

.theme-toggle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: var(--bg-secondary);
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 18px;
  color: var(--text-primary);
  transition: all 0.2s;
  
  &:hover {
    background: var(--hover-bg);
    transform: scale(1.05);
  }
}

.main-content {
  flex: 1;
  overflow: auto;
  padding: 30px;
}

/* 添加路由视图过渡效果 */
.router-view-container {
  transition: opacity 0.3s ease;
  
  > * {
    animation: fadeIn 0.5s ease;
  }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>