<script setup lang="ts">
// SPEC: PJ2026-0104010803 唯一投影 draft-2026-06-18-p0-unique-projection; PJ2026-01060505 Workbench Performance draft-2026-06-17-p0
// Starts Workbench first-screen journey timing around route hydrate.

import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import CommandComposer from "@/components/workbench/CommandComposer.vue";
import ConversationPanel from "@/components/workbench/ConversationPanel.vue";
import SessionRail from "@/components/workbench/SessionRail.vue";
import HwpodNodeOpsPanel from "@/components/hwpod/HwpodNodeOpsPanel.vue";
import { useAutoRefresh } from "@/composables/useAutoRefresh";
import { shouldReflectWorkbenchSessionUrl } from "@/router/workbench-navigation";
import { useWorkbenchStore } from "@/stores/workbench";
import { normalizeWorkbenchSessionId, normalizeWorkbenchSessionRouteId } from "@/utils";
import { finishWorkbenchOpenFullLoad, startWorkbenchOpenJourney } from "@/utils/workbench-performance";

const workbench = useWorkbenchStore();
const route = useRoute();
const router = useRouter();
const routeRequestId = computed(() => normalizeWorkbenchSessionRouteId(route.params.sessionId));
const rawRouteSessionId = computed(() => typeof route.params.sessionId === "string" ? route.params.sessionId.trim() : "");
const routeReflectionTarget = computed(() => routeRequestId.value ?? (rawRouteSessionId.value || null));
const applyingRouteSession = ref(Boolean(rawRouteSessionId.value));
const componentActive = ref(false);

onMounted(async () => {
  componentActive.value = true;
  applyingRouteSession.value = Boolean(rawRouteSessionId.value);
  const hydratedRouteTarget = routeReflectionTarget.value;
  startWorkbenchOpenJourney({ route: route.path, cache: routeRequestId.value ? "cold" : "warm", authState: "warm" });
  try {
    await workbench.hydrate({ sessionId: routeRequestId.value, invalidRouteId: rawRouteSessionId.value && !routeRequestId.value ? rawRouteSessionId.value : null });
    if (routeReflectionTarget.value !== hydratedRouteTarget) await applyRouteSession();
    finishWorkbenchOpenFullLoad(workbench.error ? "error" : "ok");
  } finally {
    applyingRouteSession.value = false;
  }
  if (!routeRequestId.value && !rawRouteSessionId.value) await reflectActiveSessionInUrl(workbench.activeSessionId);
});
onBeforeUnmount(() => {
  componentActive.value = false;
});
watch(() => route.params.sessionId, () => void applyRouteSession());
watch(() => workbench.activeSessionId, (sessionId) => void reflectActiveSessionInUrl(sessionId));
useAutoRefresh(refreshLiveWhenIdle, 120_000, { immediate: false, initialDelayMs: 90_000 });

async function refreshLiveWhenIdle(): Promise<void> {
  if (workbench.loading || workbench.sessionListLoading || workbench.sessionDetailLoading || workbench.chatPending) return;
  await workbench.refreshLive();
}

async function applyRouteSession(): Promise<boolean> {
  const sessionId = routeRequestId.value;
  if (!sessionId && !rawRouteSessionId.value) return true;
  applyingRouteSession.value = true;
  let selected = false;
  try {
    selected = sessionId ? await workbench.selectSessionById(sessionId, null, { source: "route" }) : await workbench.selectSessionById(rawRouteSessionId.value, null, { source: "route" });
    return selected;
  } finally {
    applyingRouteSession.value = false;
    if (selected) await reflectActiveSessionInUrl(workbench.activeSessionId);
  }
}

async function reflectActiveSessionInUrl(value: string | null): Promise<void> {
  const sessionId = normalizeWorkbenchSessionId(value);
  const routeTarget = routeReflectionTarget.value;
  if (!shouldReflectWorkbenchSessionUrl({
    componentActive: componentActive.value,
    routeName: route.name,
    routePath: route.path,
    routeSection: route.meta.section,
    routeSessionId: routeTarget,
    sessionId,
    activeSelectionSource: workbench.activeSessionSelectionSource,
    applyingRouteSession: applyingRouteSession.value
  })) return;
  await router.replace({
    name: "CodeWorkbenchSession",
    params: { sessionId },
    query: {}
  });
}
</script>

<template>
  <section id="workspace" class="workbench-route">
    <div class="workbench-grid">
      <SessionRail />
      <main class="workbench-center">
        <ConversationPanel />
        <CommandComposer />
      </main>
      <HwpodNodeOpsPanel />
    </div>
  </section>
</template>
