/**
 * Dashboard building blocks for the host and admin areas. Server-safe (no hooks), built on the
 * shared design tokens so the back office reads as the same product as the marketing site and TV.
 */
import type { ReactNode } from 'react';
import { Badge, type BadgeTone } from '@/components/ui/Badge';
import { AlertIcon, CheckIcon, InfoIcon } from '@/components/ui/icons';
import { cn } from '@/lib/cn';

export function PageHeader({
  title,
  description,
  kicker,
  actions,
}: {
  title: ReactNode;
  description?: ReactNode;
  kicker?: ReactNode;
  actions?: ReactNode;
}) {
  return (
    <header className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
      <div className="min-w-0">
        {kicker && <p className="text-xs font-bold tracking-[0.2em] text-cyan uppercase">{kicker}</p>}
        <h1 className="mt-1 font-display text-2xl font-bold tracking-[-0.02em] text-fg sm:text-3xl">{title}</h1>
        {description && <p className="mt-2 max-w-2xl text-base text-muted">{description}</p>}
      </div>
      {actions && <div className="flex flex-wrap gap-3">{actions}</div>}
    </header>
  );
}

export function Panel({
  title,
  description,
  actions,
  children,
  className,
  id,
  padded = true,
}: {
  title?: ReactNode;
  description?: ReactNode;
  actions?: ReactNode;
  children: ReactNode;
  className?: string;
  id?: string;
  padded?: boolean;
}) {
  const headingId = id ? `${id}-title` : undefined;
  return (
    <section
      aria-labelledby={title ? headingId : undefined}
      className={cn('rounded-card border border-line bg-surface/85 shadow-card', className)}
      id={id}
    >
      {(title || actions) && (
        <div className="flex flex-wrap items-start justify-between gap-3 border-b border-line/70 px-5 py-4 sm:px-6">
          <div className="min-w-0">
            {title && (
              <h2 id={headingId} className="font-display text-lg font-semibold tracking-[-0.01em] text-fg">
                {title}
              </h2>
            )}
            {description && <p className="mt-1 text-sm text-muted">{description}</p>}
          </div>
          {actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
        </div>
      )}
      <div className={padded ? 'p-5 sm:p-6' : undefined}>{children}</div>
    </section>
  );
}

export type StatTone = 'violet' | 'cyan' | 'amber' | 'lime' | 'neutral';
const statAccent: Record<StatTone, string> = {
  violet: 'from-violet/25',
  cyan: 'from-cyan/20',
  amber: 'from-amber/20',
  lime: 'from-lime/20',
  neutral: 'from-white/[0.04]',
};

export function StatCard({ label, value, hint, tone = 'neutral' }: { label: ReactNode; value: ReactNode; hint?: ReactNode; tone?: StatTone }) {
  return (
    <div className={cn('rounded-2xl border border-line bg-gradient-to-br to-transparent p-4 sm:p-5', statAccent[tone])}>
      <dt className="text-sm font-medium text-muted">{label}</dt>
      <dd className="num mt-1 font-display text-2xl font-bold text-fg sm:text-3xl">{value}</dd>
      {hint && <dd className="mt-1 text-xs text-subtle">{hint}</dd>}
    </div>
  );
}

export type NoticeTone = 'info' | 'success' | 'error' | 'warning';
const noticeStyles: Record<NoticeTone, string> = {
  info: 'border-cyan/40 bg-cyan/10 text-cyan-soft',
  success: 'border-lime/40 bg-lime/10 text-lime-soft',
  error: 'border-danger/50 bg-danger/10 text-danger-soft',
  warning: 'border-amber/45 bg-amber/10 text-amber-soft',
};

export function Notice({ tone = 'info', title, children, className }: { tone?: NoticeTone; title?: ReactNode; children?: ReactNode; className?: string }) {
  const Icon = tone === 'success' ? CheckIcon : tone === 'info' ? InfoIcon : AlertIcon;
  return (
    <div className={cn('flex items-start gap-3 rounded-xl border px-4 py-3 text-sm', noticeStyles[tone], className)}>
      <Icon className="mt-0.5 size-4 shrink-0" />
      <div className="min-w-0 space-y-1">
        {title && <p className="font-semibold text-fg">{title}</p>}
        {children && <div className="text-muted [&_strong]:text-fg">{children}</div>}
      </div>
    </div>
  );
}

export function EmptyState({ title, children, action }: { title: ReactNode; children?: ReactNode; action?: ReactNode }) {
  return (
    <div className="flex flex-col items-center gap-2 rounded-2xl border border-dashed border-line-strong/60 px-6 py-10 text-center">
      <p className="font-semibold text-fg">{title}</p>
      {children && <p className="max-w-md text-sm text-muted">{children}</p>}
      {action && <div className="mt-3">{action}</div>}
    </div>
  );
}

const EVENT_STATUS_TONE: Record<string, BadgeTone> = {
  SCHEDULED: 'violet',
  LIVE: 'lime',
  PAUSED: 'amber',
  COMPLETED: 'neutral',
  CANCELLED: 'danger',
  WAITING: 'cyan',
  RUNNING: 'lime',
  PILOT: 'cyan',
  ACTIVE: 'lime',
  TRIALING: 'cyan',
  PAST_DUE: 'amber',
  NEW: 'violet',
  CONTACTED: 'cyan',
  QUALIFIED: 'lime',
  REJECTED: 'neutral',
  CONVERTED: 'amber',
  PUBLISHED: 'lime',
  DRAFT: 'neutral',
  ARCHIVED: 'neutral',
  KICKED: 'danger',
  LEFT: 'neutral',
};

/** Badge for any status enum used in the back office (events, sessions, venues, leads, packs). */
export function StatusBadge({ status, label }: { status: string; label?: string }) {
  return <Badge tone={EVENT_STATUS_TONE[status] ?? 'neutral'}>{label ?? status.replace(/_/g, ' ').toLowerCase()}</Badge>;
}

/** Table styles: a scroll wrapper keeps wide tables usable on phones. */
export function TableWrap({ children, label }: { children: ReactNode; label?: string }) {
  return (
    // `relative` keeps absolutely positioned descendants (sr-only labels) inside the scroll box,
    // otherwise they escape it and widen the whole page on phones.
    <div className="relative -mx-5 overflow-x-auto sm:-mx-6" role={label ? 'region' : undefined} aria-label={label} tabIndex={label ? 0 : undefined}>
      <table className="w-full min-w-[36rem] border-collapse text-left text-sm">{children}</table>
    </div>
  );
}
export const th = 'border-b border-line px-5 py-3 text-xs font-semibold tracking-[0.08em] text-subtle uppercase first:pl-5 sm:first:pl-6 last:pr-5 sm:last:pr-6';
export const td = 'border-b border-line/50 px-5 py-3 align-middle text-fg first:pl-5 sm:first:pl-6 last:pr-5 sm:last:pr-6';

/** Inline text link in the dashboard palette. */
export const linkStyles = 'font-semibold text-violet-soft underline-offset-4 hover:text-fg hover:underline focus-visible:rounded';
