'use client'

import { paletteFor } from '../posts/badges.js'

/**
 * Tag UI for the Pages area. Two variants:
 *   - PageTagChip — interactive filter chip (filter bar). Toggles a tag
 *     on/off; announces pressed state for screen readers.
 *   - PageTagPill — static inline pill (Tags column). Compact, with a
 *     colored dot so tags don't rely on color alone.
 *
 * Both resolve color through the shared `paletteFor` palette so they
 * stay consistent with Post Type badges and work in light/dark mode.
 */

const DOT_COLOR: Record<string, string> = {
  purple: 'bg-brand',
  green: 'bg-success',
  orange: 'bg-warning',
  red: 'bg-destructive',
  blue: 'bg-info',
  pink: 'bg-chart-4',
  gray: 'bg-muted-foreground',
}

export function tagDotColor(color: string | null | undefined): string {
  if (!color) return DOT_COLOR.gray!
  return DOT_COLOR[color] ?? DOT_COLOR.gray!
}

export function PageTagChip({
  name,
  color,
  count,
  selected,
  onToggle,
}: {
  name: string
  color: string | null
  count?: number
  selected: boolean
  onToggle: () => void
}) {
  const p = paletteFor(color)
  return (
    <button
      type="button"
      onClick={onToggle}
      aria-pressed={selected}
      className={`focus-visible:ring-ring inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors focus:outline-none focus-visible:ring-2 ${
        selected
          ? `${p.bg} ${p.text} border-transparent ring-1 ${p.ring}`
          : 'border-border bg-background text-foreground hover:bg-accent'
      }`}
    >
      <span aria-hidden className={`h-2 w-2 rounded-full ${tagDotColor(color)}`} />
      {name}
      {typeof count === 'number' && (
        <span className="text-muted-foreground tabular-nums">{count}</span>
      )}
    </button>
  )
}

export function PageTagPill({ name, color }: { name: string; color: string | null }) {
  const p = paletteFor(color)
  return (
    <span
      className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium ${p.bg} ${p.text}`}
    >
      <span aria-hidden className={`h-1.5 w-1.5 rounded-full ${tagDotColor(color)}`} />
      {name}
    </span>
  )
}

export function PageTagsCell({
  tagSlugs,
  primaryTagId,
  resolve,
}: {
  tagSlugs: string[]
  primaryTagId: string | null
  resolve: (slug: string) => { name: string; color: string | null } | undefined
}) {
  if (tagSlugs.length === 0) {
    return <span className="text-muted-foreground text-xs">—</span>
  }
  // Show the primary tag first, then the rest, so grouping context is
  // visible at a glance.
  const ordered = [...tagSlugs].sort((a, b) => {
    if (a === primaryTagId) return -1
    if (b === primaryTagId) return 1
    return 0
  })
  return (
    <div className="flex flex-wrap items-center gap-1">
      {ordered.map((slug) => {
        const tag = resolve(slug)
        return <PageTagPill key={slug} name={tag?.name ?? slug} color={tag?.color ?? null} />
      })}
    </div>
  )
}
