<script lang="ts">
  import { getActivityStatus } from '../../services/auth/activity-tracker.js';
  import { fetchProfile } from '../../services/auth/profile-fetcher.js';
  import { fetchUserStatus } from '../../services/auth/user-status-fetcher.js';
  import { onMount } from 'svelte';

  interface Props {
    pubkey: string;
  }

  let { pubkey }: Props = $props();

  let profile = $state<{ name?: string; picture?: string } | null>(null);
  let status = $state<string | null>(null);
  let activityStatus = $state<'red' | 'yellow' | 'green' | null>(null);

  $effect(() => {
    if (pubkey) {
      loadProfile();
      loadStatus();
      updateActivityStatus();
    }
  });

  async function loadProfile() {
    const p = await fetchProfile(pubkey);
    if (p) {
      profile = p;
    }
  }

  async function loadStatus() {
    status = await fetchUserStatus(pubkey);
  }

  function updateActivityStatus() {
    activityStatus = getActivityStatus(pubkey);
  }

  function getActivityColor(): string {
    switch (activityStatus) {
      case 'red':
        return '#ef4444';
      case 'yellow':
        return '#eab308';
      case 'green':
        return '#22c55e';
      default:
        return '#9ca3af';
    }
  }
</script>

<a href="/profile/{pubkey}" class="profile-badge inline-flex items-center gap-2">
  {#if profile?.picture}
    <img src={profile.picture} alt={profile.name || pubkey} class="profile-picture w-6 h-6 rounded" />
  {:else}
    <div class="w-6 h-6 rounded bg-fog-highlight dark:bg-fog-dark-highlight"></div>
  {/if}
  <span>{profile?.name || pubkey.slice(0, 16)}...</span>
  {#if activityStatus}
    <span
      class="w-2 h-2 rounded-full"
      style="background-color: {getActivityColor()}"
      title="Activity indicator"
    ></span>
  {/if}
  {#if status}
    <span class="text-sm text-fog-text-light dark:text-fog-dark-text-light">({status})</span>
  {/if}
</a>

<style>
  .profile-badge {
    text-decoration: none;
    color: inherit;
  }

  .profile-badge:hover {
    text-decoration: underline;
  }
</style>
