import type { HTMLAttributes, ReactNode } from 'react'
import { cv, type VariantProps } from '../../lib/cv.js'

/**
 * Canonical status chip from the design system (`.status` + `.status-dot`):
 * a rectangular 5px-radius chip with a 5px dot, 11.5px medium text, and
 * tint backgrounds per tone. This is the single source of truth for
 * document / entity statuses across Posts, Pages, Forms, SEO, and tables —
 * do not roll per-view status pills.
 */
const statusBadge = cv(
  'inline-flex items-center gap-[5px] rounded-[5px] px-[9px] py-[3px] text-[length:var(--fs-hint)] font-medium whitespace-nowrap',
  {
    variants: {
      tone: {
        /** Published / Active — success tint (`.s-pub`). */
        success: 'bg-[var(--suc-l)] text-[var(--suc)]',
        /** Scheduled / Pending — warning tint (`.s-sch`). */
        warning: 'bg-[var(--warn-l)] text-[var(--warn)]',
        /** Errors / failing states. */
        danger: 'bg-[var(--err-l)] text-[var(--err)]',
        /** Informational states. */
        info: 'bg-[var(--info-l)] text-[var(--info)]',
        /** Draft — page background + border (`.s-dft`). */
        neutral: 'border border-[var(--bdr)] bg-[var(--bg)] text-[var(--sub)]',
        /** Archived — dimmest treatment (`.s-arc`). */
        muted: 'border border-[var(--bdr)] bg-[var(--bg)] text-[var(--muted)]',
      },
    },
    defaultVariants: { tone: 'neutral' },
  },
)

const DOT_CLASS: Record<NonNullable<StatusBadgeVariants['tone']>, string> = {
  success: 'bg-[var(--suc)]',
  warning: 'bg-[var(--warn)]',
  danger: 'bg-[var(--err)]',
  info: 'bg-[var(--info)]',
  neutral: 'bg-[var(--muted)]',
  muted: 'bg-[var(--muted)]',
}

export type StatusBadgeVariants = VariantProps<typeof statusBadge>
export type StatusBadgeTone = NonNullable<StatusBadgeVariants['tone']>

export interface StatusBadgeProps extends HTMLAttributes<HTMLSpanElement>, StatusBadgeVariants {
  /** Hide the leading dot (rare — e.g. numeric chips). */
  dot?: boolean
  children: ReactNode
}

export function StatusBadge({ tone, dot = true, className, children, ...rest }: StatusBadgeProps) {
  return (
    <span className={statusBadge({ tone, class: className })} {...rest}>
      {dot && (
        <span
          aria-hidden
          className={`h-[5px] w-[5px] shrink-0 rounded-full ${DOT_CLASS[tone ?? 'neutral']}`}
        />
      )}
      {children}
    </span>
  )
}

export { statusBadge as statusBadgeVariants }
