/**
 * proposalCountdown — pure helper for proposal expiry urgency.
 * proposal-expiry-deadline (wave-12).
 *
 * Rules (spec-verbatim):
 *   - none    : expiresAt null, status not SENT/VIEWED, or daysRemaining > 7
 *   - amber   : daysRemaining 3–7 inclusive
 *   - red     : daysRemaining 1–2 inclusive
 *   - today   : same UTC calendar day (daysRemaining === 0)
 *   - expired : expiresAt < now (before start of today UTC)
 *
 * Day arithmetic: floor(msLeft / 86_400_000) — calendar-day diff in UTC.
 */
import type { ProposalCountdown, ProposalExpiryVariant } from '@zync/types'

const LIVE_STATUSES = new Set(['sent', 'viewed', 'SENT', 'VIEWED'])

export function proposalCountdown(
  expiresAt: string | null,
  now: Date,
  status: string,
): ProposalCountdown {
  const none: ProposalCountdown = { variant: 'none', daysRemaining: null, expiresAt: null }

  if (!expiresAt) return none
  if (!LIVE_STATUSES.has(status)) return none

  const expiry = new Date(expiresAt)
  if (isNaN(expiry.getTime())) return none

  // UTC midnight for both dates to compare calendar days
  const nowMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
  const expMidnight = Date.UTC(expiry.getUTCFullYear(), expiry.getUTCMonth(), expiry.getUTCDate())

  const diffMs = expMidnight - nowMidnight
  const daysRemaining = Math.floor(diffMs / 86_400_000)

  let variant: ProposalExpiryVariant

  if (expiry.getTime() < now.getTime() && daysRemaining < 0) {
    variant = 'expired'
  } else if (daysRemaining === 0) {
    variant = 'today'
  } else if (daysRemaining < 0) {
    // past midnight but technically still same-day edge — treat as expired
    variant = 'expired'
  } else if (daysRemaining <= 2) {
    variant = 'red'
  } else if (daysRemaining <= 7) {
    variant = 'amber'
  } else {
    return none
  }

  return { variant, daysRemaining, expiresAt }
}
