// @design-system: domain/CaseStatusTimeline
/**
 * CaseStatusTimeline — displays the sequential state transitions of a case.
 * RTL-first: uses logical properties. Each step: icon, state label, actor, time.
 */

import { useT, useLocale } from '@/lib/i18n/react';
import { formatDateTime } from '@/lib/format';
import type { StringBundle } from '@/lib/i18n/types';
import type { MessageAuthorType, StateTransitionView } from '@/server/support/types';

export interface CaseStatusTimelineProps {
  transitions: StateTransitionView[];
}

function actorLabelKey(actorType: MessageAuthorType): keyof StringBundle['cases']['detail'] {
  if (actorType === 'customer') return 'actor_customer';
  if (actorType === 'vendor') return 'actor_vendor';
  return 'actor_support';
}

export function CaseStatusTimeline({ transitions }: CaseStatusTimelineProps) {
  const t = useT('cases');
  const { locale } = useLocale();
  const tDetail = t('detail') as unknown as StringBundle['cases']['detail'];
  const tStatus = t('status') as unknown as StringBundle['cases']['status'];

  const sorted = [...transitions].sort(
    (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
  );

  if (sorted.length === 0) return null;

  return (
    <section aria-label={tDetail.timeline_title}>
      <h2 className="text-muted mb-3 text-sm font-semibold">{tDetail.timeline_title}</h2>
      <ol className="border-border relative ms-3 space-y-4 border-s">
        {sorted.map((tr) => (
          <li key={tr.id} className="ms-4">
            <div
              className="bg-brand-primary-500 border-background absolute -start-1.5 h-3 w-3 rounded-full border"
              aria-hidden="true"
            />
            <div className="flex flex-col gap-0.5">
              <span className="text-foreground text-sm font-medium">
                {tStatus[tr.toState as keyof StringBundle['cases']['status']] ?? tr.toState}
              </span>
              <span className="text-muted text-xs">{tDetail[actorLabelKey(tr.actorType)]}</span>
              <time className="text-muted text-xs" dateTime={tr.createdAt}>
                {formatDateTime(tr.createdAt, locale)}
              </time>
            </div>
          </li>
        ))}
      </ol>
    </section>
  );
}
