// @design-system: domain/CitySelector

'use client';

import { useLocale, useT } from '@/lib/i18n/react';
import { dirForLocale } from '@/lib/i18n';
import { cn } from '@/lib/cn';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/primitives/Select/Select';

/** Shape returned by GET /api/cities */
export interface CityOption {
  city: string;
  cityCode: string;
  lat: number;
  lng: number;
  dealCount: number;
}

export interface CitySelectorProps {
  /** Currently selected city code, or null if none selected. */
  value: string | null;
  /** Called when user picks a city. null = "All cities". */
  onChange: (cityCode: string | null) => void;
  /** Compact mode: icon + truncated label. Use on mobile. */
  compact?: boolean;
  /** Placeholder text (falls back to i18n key). */
  placeholder?: string;
  /** Additional class names. */
  className?: string;
  cities: CityOption[];
}

/**
 * CitySelector — lazy-loading city picker for the Near You feed filter.
 *
 * Fetches /api/cities on first render via TanStack Query. Renders as a Radix
 * Select. Compact variant shows MapPin icon + truncated text for mobile headers.
 *
 * a11y: Radix Select provides keyboard navigation, ARIA, and focus management.
 *
 * @example
 * ```tsx
 * <CitySelector value={cityCode} onChange={setCityCode} compact />
 * ```
 */
export function CitySelector({
  value,
  onChange,
  compact = false,
  placeholder,
  className,
  cities: rawCities,
}: CitySelectorProps) {
  const t = useT('near_you');
  const { locale } = useLocale();
  const cities = rawCities.filter((c) => c.cityCode && c.city);

  const resolvedPlaceholder = placeholder ?? t('citySelector_placeholder');

  // Selected city label for compact display
  const selectedCity = value ? cities.find((c) => c.cityCode === value) : null;
  const compactLabel = selectedCity ? selectedCity.city : resolvedPlaceholder;

  function handleValueChange(next: string) {
    onChange(next === '__all__' ? null : next);
  }

  // Radix Select requires a non-empty string value
  const selectValue = value ?? '__all__';

  return (
    <Select value={selectValue} onValueChange={handleValueChange} dir={dirForLocale(locale)}>
      <SelectTrigger
        aria-label={t('citySelector_placeholder')}
        className={cn(compact && 'h-8 max-w-[9rem] min-w-0 gap-1 text-sm', className)}
      >
        {compact ? (
          <span className="flex min-w-0 items-center">
            <span className="truncate">{compactLabel}</span>
          </span>
        ) : (
          <SelectValue placeholder={resolvedPlaceholder} />
        )}
      </SelectTrigger>
      <SelectContent>
        {/* "All cities" sentinel */}
        <SelectItem value="__all__">{resolvedPlaceholder}</SelectItem>
        {cities.map((city) => (
          <SelectItem key={city.cityCode} value={city.cityCode}>
            {city.city} <span className="text-text-muted text-xs">({city.dealCount})</span>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
