// lib/api/mappers/leads.mappers.ts
//
// Presentation config, same layout as my-audits.mappers.ts.

import type {
  ClientGroup,
  Lead,
  LeadPriority,
  LeadStatus,
  LeadUserRef,
  RollupClientGroup,
  SelectableClientGroup,
} from '@/lib/api/types/leads.types';

// ─── Status ──────────────────────────────────────────────────────────────
export const STATUS_CONFIG: Record<
  LeadStatus,
  { label: string; bg: string; fg: string; border: string; icon: string }
> = {
  New: { label: 'New', bg: '#eff6ff', fg: '#1d4ed8', border: '#bfdbfe', icon: '✨' },
  Interested: { label: 'Interested', bg: '#f0fdfa', fg: '#0f766e', border: '#99f6e4', icon: '🔥' },
  Converted: { label: 'Converted', bg: '#f0fdf4', fg: '#15803d', border: '#bbf7d0', icon: '✅' },
  Lost: { label: 'Lost', bg: '#fef2f2', fg: '#b91c1c', border: '#fecaca', icon: '✕' },
};

// ─── Priority ────────────────────────────────────────────────────────────
export const PRIORITY_CONFIG: Record<
  LeadPriority,
  { label: string; bg: string; fg: string; border: string }
> = {
  Low: { label: 'Low', bg: '#f8fafc', fg: '#64748b', border: '#e2e8f0' },
  Medium: { label: 'Medium', bg: '#fffbeb', fg: '#b45309', border: '#fde68a' },
  High: { label: 'High', bg: '#fef2f2', fg: '#b91c1c', border: '#fecaca' },
};

// ─── Client group ────────────────────────────────────────────────────────
// QRS_B shares the QRS palette on purpose: it *is* QRS as far as grouping
// and reporting are concerned, so the two should read as one group at a
// glance. The superscript B is the only thing distinguishing them.

export const CLIENT_GROUP_OPTIONS: {
  value: SelectableClientGroup;
  label: string;
  legacy?: boolean;
}[] = [
  { value: 'QRS', label: 'QRS' },
  { value: 'TQS', label: 'TQS' },
  { value: 'QRS_B', label: 'QRS-B', legacy: true },
  { value: 'QRS_NEW', label: 'QRS New' },
];

/** Same label rule as BatchForm's groupLabel(). */
export const groupLabel = (g: ClientGroup): string =>
  CLIENT_GROUP_CONFIG[g]?.label ?? g;

export const CLIENT_GROUP_CONFIG: Record<
  ClientGroup,
  { label: string; bg: string; fg: string; border: string }
> = {
  QRS: { label: 'QRS', bg: '#eef2ff', fg: '#4338ca', border: '#c7d2fe' },
  // Same palette as QRS on purpose — it *is* QRS as far as the business
  // is concerned; the suffix is only there so nobody thinks the data was
  // silently rewritten.
  QRS_B: { label: 'QRS-B', bg: '#eef2ff', fg: '#4338ca', border: '#c7d2fe' },
  TQS: { label: 'TQS', bg: '#fdf4ff', fg: '#a21caf', border: '#f5d0fe' },
  QRS_NEW: { label: 'QRS New', bg: '#ecfeff', fg: '#0e7490', border: '#a5f3fc' },
};

/** QRS_B counts as QRS everywhere we group or compare. */
export function normalizeClientGroup(
  value: ClientGroup | null | undefined,
): RollupClientGroup | null {
  if (!value) return null;
  if (value === 'QRS_B') return 'QRS';
  return value;
}

/** True when a row belongs to the group the user picked in the filter. */
export function matchesClientGroup(
  row: Lead,
  filter: RollupClientGroup | 'all',
): boolean {
  if (filter === 'all') return true;
  return normalizeClientGroup(row.client_group) === filter;
}

// ─── Formatting ──────────────────────────────────────────────────────────

export function formatUserName(user: LeadUserRef | null | undefined): string {
  if (!user) return '—';
  const full = `${user.firstName ?? ''} ${user.lastName ?? ''}`.trim();
  return full || user.email || `User #${user.id}`;
}

export function initialsOf(user: LeadUserRef | null | undefined): string {
  if (!user) return '?';
  const first = (user.firstName ?? '').trim();
  const last = (user.lastName ?? '').trim();
  if (first || last) return `${first[0] ?? ''}${last[0] ?? ''}`.toUpperCase();
  return (user.email ?? '?')[0].toUpperCase();
}

/** "12 Mar 2026" plus a relative hint for anything inside a week. */
export function formatDateWithHint(iso: string | null): {
  main: string;
  hint: string | null;
} {
  if (!iso) return { main: '—', hint: null };
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return { main: '—', hint: null };

  const main = d.toLocaleDateString('en-GB', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
  });

  const diffDays = Math.round((Date.now() - d.getTime()) / 86_400_000);
  let hint: string | null = null;
  if (diffDays === 0) hint = 'today';
  else if (diffDays === 1) hint = 'yesterday';
  else if (diffDays > 1 && diffDays < 7) hint = `${diffDays}d ago`;
  else if (diffDays === -1) hint = 'tomorrow';
  else if (diffDays < -1 && diffDays > -7) hint = `in ${Math.abs(diffDays)}d`;

  return { main, hint };
}

/** "2h ago" / "just now" — used on the reassignment stamp. */
export function timeAgo(iso: string | null): string | null {
  if (!iso) return null;
  const d = new Date(iso).getTime();
  if (Number.isNaN(d)) return null;

  const secs = Math.round((Date.now() - d) / 1000);
  if (secs < 60) return 'just now';
  if (secs < 3600) return `${Math.floor(secs / 60)}m ago`;
  if (secs < 86_400) return `${Math.floor(secs / 3600)}h ago`;
  if (secs < 604_800) return `${Math.floor(secs / 86_400)}d ago`;
  return null;
}
