'use client';

import { useMemo } from 'react';
import { cn } from '@djangocfg/ui-core/lib';
import { Progress } from '@djangocfg/ui-core/components';
import { useT } from '@djangocfg/i18n';
import type { TourProgressProps } from '../types';

/**
 * Progress indicator for tour steps.
 * Supports dots, bar, fraction, and none variants.
 */
export function TourProgress({
  current,
  total,
  variant = 'dots',
  onDotClick,
  className,
}: TourProgressProps) {
  const t = useT();

  // Early return for hidden states
  if (variant === 'none' || total <= 1) return null;

  // Prepare data
  const currentStep = current + 1;
  const progressPercent = (currentStep / total) * 100;
  const stepLabel = t('tools.tour.stepOf', { current: currentStep, total });
  const isClickable = !!onDotClick;

  // Prepare dots data
  const dots = useMemo(() => {
    if (variant !== 'dots') return [];

    return Array.from({ length: total }, (_, index) => ({
      index,
      isActive: index === current,
      label: t('tools.tour.stepOf', { current: index + 1, total }),
      className: cn(
        'h-2 w-2 rounded-full transition-all',
        index === current ? 'bg-primary scale-110' : 'bg-muted hover:bg-muted-foreground/50',
        isClickable && 'cursor-pointer'
      ),
    }));
  }, [variant, total, current, isClickable, t]);

  // Render bar variant
  if (variant === 'bar') {
    return (
      <Progress
        value={progressPercent}
        className={cn('h-1', className)}
        aria-label={stepLabel}
      />
    );
  }

  // Render fraction variant
  if (variant === 'fraction') {
    const fractionClassName = cn('text-sm text-muted-foreground tabular-nums', className);

    return (
      <div className={fractionClassName} aria-label={stepLabel}>
        {currentStep} / {total}
      </div>
    );
  }

  // Render dots variant (default)
  const dotsContainerClassName = cn('flex items-center justify-center gap-1.5', className);

  return (
    <div className={dotsContainerClassName} role="tablist" aria-label={stepLabel}>
      {dots.map((dot) => (
        <button
          key={dot.index}
          type="button"
          role="tab"
          aria-selected={dot.isActive}
          aria-label={dot.label}
          className={dot.className}
          onClick={() => onDotClick?.(dot.index)}
          disabled={!isClickable}
        />
      ))}
    </div>
  );
}
