import type { NDKUserProfile } from '@nostr-dev-kit/ndk';
import firstLine from '@utils/firstLine';
import { getProfile } from '@utils/profileUtils';
import { LitElement, css, html } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

import '@components/EveLink';

@customElement('arx-nostr-medium-profile')
export class MediumProfile extends LitElement {
  @property() profile!: NDKUserProfile;
  @property() npub = '';

  @state()
  private displayName = '';

  @state()
  private profileUrl = '';

  @state()
  private truncatedAbout = '';

  static override styles = [
    css`
      :host {
        display: block;
      }

      arx-eve-link {
        color: var(--color-base-content);
        text-decoration: none;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem;
        border-radius: var(--radius-selector);
        transition: all 0.2s ease;
      }

      arx-eve-link:hover {
        background-color: oklch(from var(--color-base-300) l c h / 0.5);
      }

      arx-eve-link:focus-visible {
        outline: var(--border) solid var(--color-accent);
        outline-offset: 2px;
      }

      .display-name {
        font-weight: 500;
        color: var(--color-base-content);
        margin-bottom: 0.25rem;
      }

      .bio {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 0.85rem;
        color: var(--color-secondary);
        max-width: 180px;
      }

      arx-nostr-avatar {
        flex-shrink: 0;
        transition: transform 0.2s ease;
      }

      arx-eve-link:hover arx-nostr-avatar {
        transform: scale(1.05);
      }
    `,
  ];

  override firstUpdated() {
    const { displayName, profileUrl } = getProfile({
      profile: this.profile,
      npub: this.npub,
    });
    this.displayName = displayName;
    this.profileUrl = profileUrl;
    this.truncatedAbout = this.getTruncatedAbout();
  }

  getTruncatedAbout() {
    const about = firstLine(this.profile.about);
    return about?.length > 80 ? `${about.substring(0, 80)}...` : about;
  }

  override render() {
    return html`
      <arx-eve-link href=${this.profileUrl}>
        <arx-nostr-avatar
          .profile=${this.profile}
          size="medium"
        ></arx-nostr-avatar>
        <div>
          <div>${this.displayName}</div>
          <div class="bio">${this.truncatedAbout}</div>
        </div>
      </arx-eve-link>
    `;
  }
}
