<script lang="ts">
  import Router, { push, location } from "svelte-spa-router";
  import { onMount } from "svelte";
  import { hasStoredIdentity } from "./lib/identity-store.js";
  import { session } from "./lib/store.svelte.js";

  import Landing from "./routes/Landing.svelte";
  import CreateAccount from "./routes/CreateAccount.svelte";
  import Restore from "./routes/Restore.svelte";
  import Unlock from "./routes/Unlock.svelte";
  import Dashboard from "./routes/Dashboard.svelte";
  import Claims from "./routes/Claims.svelte";
  import AddClaim from "./routes/AddClaim.svelte";

  const routes = {
    "/": Landing,
    "/create": CreateAccount,
    "/restore": Restore,
    "/unlock": Unlock,
    "/dashboard": Dashboard,
    "/claims": Claims,
    "/claims/add": AddClaim,
  };

  // First-load: if there's a stored identity but session is locked,
  // bounce to /unlock. If no stored identity and on a protected page,
  // bounce to /.
  onMount(async () => {
    const stored = await hasStoredIdentity();
    const protectedRoutes = ["/dashboard", "/claims", "/claims/add"];
    if (!stored && protectedRoutes.includes($location)) {
      push("/");
    } else if (stored && !session.unlocked && protectedRoutes.includes($location)) {
      push("/unlock");
    }
  });
</script>

<header class="border-b border-gray-200 bg-white">
  <div class="max-w-3xl mx-auto px-6 py-4 flex items-center justify-between">
    <a href="#/" class="text-lg font-semibold text-gray-900 no-underline">
      🔑 kez-chat
    </a>
    {#if session.unlocked}
      <nav class="flex items-center gap-4 text-sm">
        <a href="#/dashboard" class="text-gray-700 hover:text-gray-900">Dashboard</a>
        <a href="#/claims" class="text-gray-700 hover:text-gray-900">Claims</a>
        <span class="text-gray-400">|</span>
        <span class="text-gray-500">{session.unlocked.handle}@{session.unlocked.server}</span>
        <button
          class="text-gray-500 hover:text-gray-900 underline"
          onclick={() => { session.lock(); push("/unlock"); }}
        >
          Lock
        </button>
      </nav>
    {/if}
  </div>
</header>

<main class="max-w-3xl mx-auto px-6 py-8">
  <Router {routes} />
</main>

<footer class="border-t border-gray-200 bg-white mt-16">
  <div class="max-w-3xl mx-auto px-6 py-4 text-xs text-gray-500">
    kez-chat web v0.1 ·
    <a
      href="https://git.ptud.biz/DukeInc/Kez"
      target="_blank"
      rel="noopener"
      class="text-gray-500 hover:text-gray-700"
    >
      source
    </a>
  </div>
</footer>
