<script setup lang="ts">
import { computed, ref } from "vue";
import { useNativeRouter } from "@native-vue-router/core";
import { useRoute } from "vue-router";
import AppHeader from "../components/AppHeader.vue";
import {
  compatibilityLab,
  recordCompatibilityEvent,
} from "../compatibility-lab";

const route = useRoute();
const native = useNativeRouter();
const unloadStatus = ref("Lab remains cached");
const labLocation = computed(() => ({
  name: "vue-compatibility",
  params: { sample: route.params.sample },
  query: route.query,
  hash: route.hash,
}));

function unloadLab() {
  const count = native.unload(labLocation.value);
  unloadStatus.value = count
    ? "Lab view evicted; Back will create a new instance"
    : "No matching inactive lab view was mounted";
  recordCompatibilityEvent("Away screen", "native.unload", `${count} view(s)`);
}

async function unloadAndReturn() {
  unloadLab();
  await native.pop();
}
</script>

<template>
  <main
    class="screen compatibility-screen"
    data-testid="vue-compatibility-away"
  >
    <AppHeader
      title="Cached-route checkpoint"
      subtitle="The compatibility lab is behind this view"
      back
    />

    <section class="lab-intro compat-intro">
      <span>↩</span>
      <div>
        <strong>Inspect native cache behavior</strong>
        <p>
          The previous lab instance is inactive but still mounted until you
          explicitly unload it.
        </p>
      </div>
    </section>

    <section class="settings-group">
      <h2>Inactive route controls</h2>
      <div>
        <span
          ><strong>Compatibility lab</strong
          ><small>{{ unloadStatus }}</small></span
        ><b>behind</b>
      </div>
      <p>
        Use normal Back to observe native activate/show without Vue remount
        hooks. Use “Unload and return” to observe beforeUnmount/unmounted
        followed by a fresh component instance.
      </p>
    </section>
    <div class="compat-controls">
      <button type="button" data-testid="compat-unload-lab" @click="unloadLab">
        Unload cached lab
      </button>
      <button
        type="button"
        data-testid="compat-unload-return"
        @click="unloadAndReturn"
      >
        Unload and return
      </button>
    </div>

    <section class="settings-group compat-event-section">
      <div class="compat-event-heading">
        <span
          ><strong>Shared lifecycle journal</strong
          ><small>Events survive route eviction</small></span
        >
      </div>
      <ol class="compat-event-log" data-testid="compat-away-event-log">
        <li v-for="event in compatibilityLab.events" :key="event.id">
          <time>{{ event.timestamp }}</time>
          <span
            ><strong>{{ event.source }}</strong
            ><code>{{ event.hook }}</code></span
          >
          <small>{{ event.detail }}</small>
        </li>
      </ol>
    </section>
  </main>
</template>
