<script lang="ts">
  import { onMount } from "svelte";
  import { push } from "svelte-spa-router";
  import { lookup, setProofs, ApiError } from "../lib/api.js";
  import { session } from "../lib/store.svelte.js";
  import VerifiedBadge from "../lib/VerifiedBadge.svelte";
  import {
    listClaims,
    setVerifyResult,
    type StoredClaim,
  } from "../lib/claims-store.js";
  import { verifyClaim } from "../lib/verify.js";
  import Avatar from "../lib/Avatar.svelte";

  let registryRecord = $state<any | null>(null);
  let claims = $state<StoredClaim[]>([]);
  let verifyingAll = $state(false);
  let copied = $state(false);

  const verified = $derived(claims.filter((c) => c.last_verify?.status === "ok"));
  const failed = $derived(claims.filter((c) => c.last_verify?.status === "fail"));
  const pending = $derived(claims.filter((c) => !c.last_verify));

  // Verified badge requires at least this many independently-verified
  // proofs. Kept in sync with VERIFY_MIN_PROOFS in Messages.svelte so the
  // badge means the same thing on the profile and in chat.
  const VERIFY_MIN_PROOFS = 2;
  const isVerified = $derived(verified.length >= VERIFY_MIN_PROOFS);

  onMount(async () => {
    if (!session.unlocked) {
      push("/unlock");
      return;
    }
    claims = await listClaims();
    // Publish our verified proof subjects to the server profile so peers
    // can discover + independently verify them (drives our badge in their
    // chat). Previously this only happened on a manual "reverify all", so
    // verified users were invisible to peers until they clicked it.
    if (claims.some((c) => c.last_verify?.status === "ok")) {
      void publishVerifiedSubjects();
    }
    try {
      registryRecord = await lookup(session.unlocked.handle);
    } catch (e) {
      if (!(e instanceof ApiError && e.status === 404)) {
        console.error(e);
      }
    }
  });

  async function reverifyAll() {
    verifyingAll = true;
    try {
      for (const c of claims) {
        const result = await verifyClaim($state.snapshot(c) as StoredClaim);
        await setVerifyResult(c.id, result);
      }
      claims = await listClaims();
      await publishVerifiedSubjects();
    } finally {
      verifyingAll = false;
    }
  }

  /**
   * Push the subjects of our currently-verified claims to the server
   * profile so peers can discover + independently verify them (drives
   * their verified badge for us). Best-effort — a failure here doesn't
   * affect local verification.
   */
  async function publishVerifiedSubjects() {
    if (!session.unlocked) return;
    const subjects = claims
      .filter((c) => c.last_verify?.status === "ok")
      .map((c) => c.envelope.payload.subject);
    try {
      await setProofs(session.unlocked.handle, session.unlocked.seed, subjects);
    } catch (e) {
      console.error("publishVerifiedSubjects failed", e);
    }
  }

  function channelLabel(ch: string): string {
    return (
      {
        github: "GitHub",
        dns: "DNS",
        web: "Website",
        nostr: "Nostr",
        bluesky: "Bluesky",
        ap: "ActivityPub",
      } as Record<string, string>
    )[ch] ?? ch;
  }

  async function copyKez() {
    if (!session.unlocked) return;
    await navigator.clipboard.writeText(
      `${session.unlocked.handle}@${session.unlocked.server}`,
    );
    copied = true;
    setTimeout(() => (copied = false), 1500);
  }

  function fingerprint(primary: string): string {
    // ed25519:<hex> → grouped short fingerprint for human comparison.
    const hex = primary.startsWith("ed25519:")
      ? primary.slice("ed25519:".length)
      : primary;
    return (hex.match(/.{1,4}/g) ?? []).slice(0, 8).join(" ");
  }
</script>

{#if session.unlocked}
  <div class="max-w-2xl mx-auto space-y-6">
    <!-- Identity card -->
    <section class="bg-surface border border-border rounded-xl p-6">
      <div class="flex items-start gap-4">
        <Avatar seed={session.unlocked.primary} size={64} ring />
        <div class="min-w-0 flex-1">
          <div class="flex items-center gap-2 flex-wrap">
            <span class="font-mono text-lg font-semibold text-text truncate inline-flex items-center gap-1">
              <span class="truncate">{session.unlocked.handle}<span class="text-text-muted">@{session.unlocked.server}</span></span>
              {#if isVerified}<VerifiedBadge size={16} />{/if}
            </span>
            <button
              class="text-xs px-2 py-0.5 rounded-sm border border-border text-text-secondary hover:bg-elevated hover:text-text shrink-0"
              onclick={copyKez}
            >
              {copied ? "✓ copied" : "copy"}
            </button>
          </div>
          <p class="mt-2 text-xs text-text-muted uppercase tracking-wider">Key fingerprint</p>
          <p class="font-mono text-sm text-text-secondary break-all">
            {fingerprint(session.unlocked.primary)}<span class="text-text-muted">…</span>
          </p>
          {#if registryRecord}
            <p class="mt-2 text-xs text-text-muted">
              Registered {new Date(registryRecord.registered_at).toLocaleDateString()}
            </p>
          {/if}
        </div>
      </div>
    </section>

    <!-- Proofs -->
    <section class="bg-surface border border-border rounded-xl p-6">
      <div class="flex items-start justify-between gap-4 mb-4">
        <div>
          <h2 class="text-sm font-semibold text-text uppercase tracking-wider">Proofs</h2>
          <p class="text-sm text-text-secondary mt-1">
            Other accounts cryptographically linked to your KEZ. Anyone can
            verify these without trusting the server.
          </p>
        </div>
        <div class="flex flex-col gap-2 shrink-0">
          {#if claims.length > 0}
            <button
              class="px-3 py-1.5 text-sm border border-border rounded-md text-text-secondary hover:bg-elevated hover:text-text disabled:opacity-50"
              onclick={reverifyAll}
              disabled={verifyingAll}
            >
              {verifyingAll ? "Verifying…" : "Re-verify"}
            </button>
          {/if}
          <a
            href="#/claims/add"
            class="px-3 py-1.5 text-sm bg-accent text-accent-contrast font-semibold rounded-md hover:bg-accent-dim no-underline text-center"
          >
            + Add proof
          </a>
        </div>
      </div>

      {#if claims.length === 0}
        <div class="border border-dashed border-border rounded-lg p-6 text-center">
          <p class="text-sm text-text-muted">No proofs yet.</p>
          <p class="text-xs text-text-muted mt-1">
            Link GitHub, your domain, nostr, Bluesky — prove the accounts you control.
          </p>
        </div>
      {:else}
        <ul class="space-y-2">
          {#each verified as c (c.id)}
            <li class="flex items-center justify-between gap-3 p-3 bg-elevated border border-border rounded-lg">
              <div class="min-w-0 flex-1">
                <div class="flex items-center gap-2 flex-wrap">
                  <span class="text-xs font-semibold px-1.5 py-0.5 rounded-sm bg-elevated border border-border text-text-secondary">
                    {channelLabel(c.channel)}
                  </span>
                  <span class="font-mono text-sm text-text truncate">{c.envelope.payload.subject}</span>
                  <span class="text-xs font-mono font-semibold px-1.5 py-0.5 rounded-sm" style="background:#4ade8014;border:1px solid #4ade8040;color:var(--color-verified);">✓ verified</span>
                </div>
              </div>
              {#if c.last_verify?.evidence_url}
                <a href={c.last_verify.evidence_url} target="_blank" rel="noopener noreferrer" class="text-xs text-accent hover:text-accent-dim underline shrink-0">proof ↗</a>
              {/if}
            </li>
          {/each}
          {#each failed as c (c.id)}
            <li class="flex items-center gap-2 p-3 bg-elevated border border-border rounded-lg">
              <span class="text-xs font-semibold px-1.5 py-0.5 rounded-sm bg-elevated border border-border text-text-secondary">{channelLabel(c.channel)}</span>
              <span class="font-mono text-sm text-text truncate flex-1">{c.envelope.payload.subject}</span>
              <span class="text-xs font-mono font-semibold text-danger shrink-0">✗ failed</span>
            </li>
          {/each}
          {#each pending as c (c.id)}
            <li class="flex items-center gap-2 p-3 bg-elevated border border-border rounded-lg">
              <span class="text-xs font-semibold px-1.5 py-0.5 rounded-sm bg-elevated border border-border text-text-secondary">{channelLabel(c.channel)}</span>
              <span class="font-mono text-sm text-text truncate flex-1">{c.envelope.payload.subject}</span>
              <span class="text-xs font-mono text-warning shrink-0">pending</span>
            </li>
          {/each}
        </ul>
        <a href="#/claims" class="mt-3 inline-block text-xs text-text-secondary hover:text-text underline">Manage proofs →</a>
      {/if}
    </section>
  </div>
{/if}
