'use client';

import type { DealCard, StageType } from '@/features/deals/types';
import { Avatar } from '@/features/list-page/ui/RecordAvatar';
import { cn } from '@/lib/utils/cn';

/**
 * GL7 (go-live M5): the deal board card's extra row, beyond the design (its card shows amount,
 * close date and company only, list-page.js:2246; the user's call, 27 Nov 2026): a status pill
 * (Open / Won / Lost, from the column's stage type), the first linked contacts as avatars with
 * "+N" for the rest, and the HubSpot deal score when the deal has one.
 */
export const DEAL_STATUS_LABEL: Record<StageType, string> = {
  open: 'Open',
  won: 'Won',
  lost: 'Lost',
};

/** "+2" when the card shows fewer avatars than the deal has contacts, else null. */
export function moreContactsLabel(shown: number, total: number): string | null {
  return total > shown ? `+${total - shown}` : null;
}

/** The score as the card shows it: whole numbers as is, else one decimal. */
export function scoreText(score: number): string {
  return Number.isInteger(score) ? String(score) : score.toFixed(1);
}

export function DealCardExtras({
  stageType,
  card,
}: {
  stageType: StageType;
  card: Pick<DealCard, 'contacts' | 'contactCount' | 'score' | 'tags'>;
}) {
  const contacts = card.contacts ?? [];
  const more = moreContactsLabel(contacts.length, card.contactCount);
  const score = card.score ?? null;
  const tags = card.tags ?? [];
  return (
    <div className="lp-bcard__deal">
      {/* GL8: the deal's tags (its Deal tags field), as HubSpot's card pills. */}
      {tags.map((tag) => (
        <span key={tag} className="deal-tag-pill">
          {tag}
        </span>
      ))}
      <span className={cn('deal-status-pill', `deal-status-pill--${stageType}`)}>
        {DEAL_STATUS_LABEL[stageType]}
      </span>
      {score !== null ? (
        <span className="deal-score-badge" title="Deal score">
          Score {scoreText(score)}
        </span>
      ) : null}
      {contacts.length > 0 ? (
        <span
          className="deal-card-avatars"
          aria-label={`${card.contactCount} associated contact${card.contactCount === 1 ? '' : 's'}`}
        >
          {contacts.map((c) => (
            <span key={c.id} title={c.name ?? 'Unnamed contact'}>
              <Avatar name={c.name ?? '?'} size="xs" />
            </span>
          ))}
          {more ? <span className="deal-card-avatars__more">{more}</span> : null}
        </span>
      ) : null}
    </div>
  );
}
