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

  let existing = $state<{
    handle: string;
    server: string;
    primary: string;
    created_at: string;
  } | null>(null);
  let loading = $state(true);

  onMount(async () => {
    if (await hasStoredIdentity()) {
      existing = await loadStoredIdentityMeta();
    }
    loading = false;
  });
</script>

<div class="space-y-8">
  <section>
    <h1 class="text-3xl font-bold text-gray-900">Welcome to kez-chat</h1>
    <p class="mt-2 text-gray-600">
      A decentralized identity + chat system. Create an account, link your
      online identities, prove who you are without trusting a central server.
    </p>
  </section>

  {#if loading}
    <p class="text-gray-500 text-sm">Checking local state…</p>
  {:else if existing}
    <section class="border border-gray-200 rounded-lg p-6 bg-white">
      <p class="text-sm text-gray-500 mb-1">Existing account on this device:</p>
      <p class="text-xl font-mono font-semibold text-gray-900">
        {existing.handle}@{existing.server}
      </p>
      <p class="mt-1 text-xs font-mono text-gray-500 break-all">
        {existing.primary}
      </p>
      <div class="mt-4 flex gap-3">
        <button
          class="px-4 py-2 bg-gray-900 text-white rounded-md hover:bg-gray-700"
          onclick={() => push("/unlock")}
        >
          Unlock
        </button>
      </div>
    </section>
  {:else}
    <section class="grid sm:grid-cols-2 gap-4">
      <button
        class="text-left border border-gray-200 rounded-lg p-6 bg-white hover:border-gray-400 transition"
        onclick={() => push("/create")}
      >
        <h2 class="text-lg font-semibold text-gray-900">Create a new account</h2>
        <p class="mt-1 text-sm text-gray-600">
          Generate a fresh key pair, pick a handle, back up your seed phrase.
        </p>
      </button>

      <button
        class="text-left border border-gray-200 rounded-lg p-6 bg-white hover:border-gray-400 transition"
        onclick={() => push("/restore")}
      >
        <h2 class="text-lg font-semibold text-gray-900">Restore from seed</h2>
        <p class="mt-1 text-sm text-gray-600">
          Have a 64-char hex seed from another device? Paste it to recover
          your identity.
        </p>
      </button>
    </section>
  {/if}

  <section class="text-sm text-gray-500 border-t border-gray-200 pt-6">
    <p class="font-medium text-gray-700">What is this?</p>
    <p class="mt-1">
      Your identity is an Ed25519 keypair — not a username + password.
      Account creation makes a handle (<code class="bg-gray-100 px-1 rounded">tudisco@kez.lat</code>),
      stores your seed locally under a passphrase, and registers your public
      key with this server. There's no email, no recovery flow — keep the
      seed safe.
    </p>
  </section>
</div>
