// @design-system: domain/GroupProgressBar

'use client';

import { cn } from '@/lib/cn';
import { useT } from '@/lib/i18n/react';
import { formatShekelFloat } from '@/lib/money';

/** A single pricing tier threshold */
export interface GroupTier {
  minParticipants: number;
  pricePerUnit: number;
}

/** Props for GroupProgressBar */
export interface GroupProgressBarProps {
  /** Current reservation count. */
  current: number;
  /** Minimum group size to meet the threshold. */
  minTarget: number;
  /** Maximum group size (cap). */
  maxTarget: number;
  /** Optional tiered pricing bands. When provided, markers appear at each tier threshold. */
  tiers?: GroupTier[];
  /** Whether to show milestone markers. Defaults to true. */
  showMilestones?: boolean;
  /** Additional class names. */
  className?: string;
  /** Replaces the participants_of caption line when provided. */
  caption?: string;
  /** Replaces the value label (top-right) when provided. */
  valueText?: string;
}

/**
 * GroupProgressBar - horizontal fill bar showing group deal participation progress.
 *
 * - Fill uses `--color-brand-primary-*` token classes.
 * - Background uses `--color-surface-inset`.
 * - Milestone markers at minTarget (dashed) and tier thresholds.
 * - Respects `prefers-reduced-motion`.
 * - WCAG: `role="progressbar"` with proper aria attributes.
 *
 * @example
 * ```tsx
 * <GroupProgressBar current={12} minTarget={15} maxTarget={30} showMilestones />
 * ```
 */
export function GroupProgressBar({
  current,
  minTarget,
  maxTarget,
  tiers,
  showMilestones = true,
  className,
  caption,
  valueText,
}: GroupProgressBarProps) {
  const t = useT('group_deal');

  const clampedCurrent = Math.min(current, maxTarget);
  const fillPercent = maxTarget > 0 ? (clampedCurrent / maxTarget) * 100 : 0;
  const thresholdPercent = maxTarget > 0 ? (minTarget / maxTarget) * 100 : 0;
  const thresholdMet = current >= minTarget;

  // Build milestone positions (as % of bar width)
  const tierMarkers: Array<{ percent: number; label: string }> = [];
  if (showMilestones && tiers) {
    for (const tier of tiers) {
      if (tier.minParticipants > 0 && tier.minParticipants <= maxTarget) {
        const pct = (tier.minParticipants / maxTarget) * 100;
        tierMarkers.push({
          percent: pct,
          label: formatShekelFloat(tier.pricePerUnit),
        });
      }
    }
  }

  return (
    <div className={cn('flex flex-col gap-2', className)}>
      {/* Label row */}
      <div className="flex items-center justify-between gap-2">
        <span className="text-text-secondary text-sm font-medium" aria-hidden="true">
          {t('progress_label')}
        </span>
        <span
          className={cn(
            'text-xs font-semibold',
            thresholdMet ? 'text-success-700' : 'text-text-muted',
          )}
          aria-hidden="true"
        >
          {valueText ?? (thresholdMet ? t('threshold_met') : `${current} / ${maxTarget}`)}
        </span>
      </div>

      {/* Bar + markers container */}
      <div className="relative">
        {/* Track */}
        <div
          role="progressbar"
          aria-valuenow={clampedCurrent}
          aria-valuemin={0}
          aria-valuemax={maxTarget}
          aria-label={t('progress_label')}
          className="bg-surface-inset relative h-3 overflow-hidden rounded-full"
        >
          {/* Fill */}
          <div
            className={cn(
              'absolute inset-y-0 start-0 rounded-full',
              thresholdMet ? 'bg-success-600' : 'bg-brand-primary-500',
              'motion-safe:transition-[width] motion-safe:duration-[var(--duration-slow)] motion-safe:ease-[var(--ease-out)]',
            )}
            style={{ width: `${fillPercent}%` }}
          />
        </div>

        {/* Minimum threshold marker (dashed line) */}
        {showMilestones && minTarget > 0 && minTarget < maxTarget && (
          <div
            className="absolute inset-y-0 -translate-x-px"
            style={{ insetInlineStart: `${thresholdPercent}%` }}
            aria-hidden="true"
          >
            {/* Dashed vertical marker */}
            <div className="absolute inset-y-0 w-0.5 border-s-2 border-dashed border-neutral-400" />
          </div>
        )}

        {/* Tier markers */}
        {tierMarkers.map((marker) => (
          <div
            key={marker.percent}
            className="pointer-events-none absolute inset-y-0"
            style={{ insetInlineStart: `${marker.percent}%` }}
            aria-hidden="true"
          >
            <div className="absolute inset-y-0 w-0.5 bg-neutral-300" />
          </div>
        ))}
      </div>

      {/* "N of M joined" text */}
      <p className="text-text-muted text-xs" aria-live="polite">
        {caption ?? (
          <>
            {t('participants_of')
              .replace('{{current}}', String(current))
              .replace('{{target}}', String(maxTarget))}
            {!thresholdMet && (
              <>
                {' · '}
                {t('threshold_not_met').replace(
                  '{{count}}',
                  String(Math.max(0, minTarget - current)),
                )}
              </>
            )}
          </>
        )}
      </p>
    </div>
  );
}
