import {
  GLYPH_SYNCED,
  GLYPH_AHEAD,
  GLYPH_BEHIND,
  GLYPH_PENDING,
} from '../shared/glyphs';
import { relativeTime } from '../shared/relative-time';
import type { GetVaultStatusResponse } from '../shared/messages';

// The indicator consumes exactly the get_vault_status response payload; alias
// it (rather than re-declaring the four fields) so the shape stays single-
// sourced and can't drift from the SW handler. lastSyncAt is a unix timestamp
// in SECONDS, or null when the vault has never synced.
export type VaultStatus = GetVaultStatusResponse['data'];

export function renderStatusIndicator(el: HTMLElement, status: VaultStatus): void {
  const ts = status.lastSyncAt !== null
    ? `last sync ${relativeTime(status.lastSyncAt)}`
    : 'never synced';

  const parts: string[] = [];
  if (status.pendingItems > 0) parts.push(`${GLYPH_PENDING} ${status.pendingItems} pending`);
  if (status.ahead > 0)        parts.push(`${GLYPH_AHEAD} ${status.ahead} ahead`);
  if (status.behind > 0)       parts.push(`${GLYPH_BEHIND} ${status.behind} behind`);
  if (parts.length === 0)      parts.push(`${GLYPH_SYNCED} in sync`);

  el.innerHTML = `
    <div class="vault-status">
      <div class="vault-status__state">${parts.join(' · ')}</div>
      <div class="vault-status__ts">${ts}</div>
    </div>
  `;
}
