<script lang="ts">
  import { DropdownMenu } from "bits-ui";
  import Avatar from "$lib/components/ui/Avatar.svelte";
  import Icon from "$lib/components/ui/Icon.svelte";
  import { accountName } from "$lib/format/peer";
  import { accounts } from "$lib/stores/accounts.svelte";

  const current = $derived(accounts.selected);
</script>

<DropdownMenu.Root>
  <DropdownMenu.Trigger class="account-trigger">
    {#if current}
      <Avatar
        name={accountName(current)}
        colorKey={current.account_id}
        size={2.25}
      />
      <span class="account-name">{accountName(current)}</span>
    {:else}
      <span class="account-name">No account</span>
    {/if}
    <Icon name="down" size="1.25rem" />
  </DropdownMenu.Trigger>
  <DropdownMenu.Portal>
    <DropdownMenu.Content class="bg-menu-content" sideOffset={6} align="start">
      {#each accounts.list as account (account.account_id)}
        <DropdownMenu.Item
          class="bg-menu-item"
          data-selected={account.account_id === accounts.selectedId
            ? ""
            : undefined}
          onSelect={() => accounts.select(account.account_id)}
        >
          <Avatar
            name={accountName(account)}
            colorKey={account.account_id}
            size={1.75}
          />
          <span>{accountName(account)}</span>
          {#if account.account_id === accounts.selectedId}
            <Icon name="check" size="1.125rem" class="trailing" />
          {/if}
        </DropdownMenu.Item>
      {/each}
    </DropdownMenu.Content>
  </DropdownMenu.Portal>
</DropdownMenu.Root>

<style lang="scss">
  :global(.account-trigger) {
    cursor: pointer;
    display: flex;
    flex: 1;
    align-items: center;
    gap: 0.625rem;

    min-width: 0;
    padding: 0.375rem 0.5rem;
    border: 0;
    border-radius: 0.625rem;

    color: var(--color-text);
    background-color: transparent;
    transition: background-color 0.15s ease;

    &:hover {
      background-color: var(--color-chat-hover);
    }
  }

  .account-name {
    overflow: hidden;
    flex: 1;

    font-size: 1rem;
    font-weight: var(--font-weight-medium);
    text-align: start;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  :global(.bg-menu-item .trailing) {
    margin-inline-start: auto;
    color: var(--color-primary);
  }
</style>
