'use client';

import { useState, FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import {
  User,
  Globe,
  Flag,
  Car,
  Heart,
  Clock,
  Check,
  ChevronRight,
  ChevronLeft,
  Gamepad2,
  Target,
  Zap,
  Trophy,
  Users,
  MapPin,
  Mail,
  Calendar,
  AlertCircle,
} from 'lucide-react';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Heading from '@/components/ui/Heading';
import { Driver } from '@gridpilot/racing';
import { getDriverRepository } from '@/lib/di-container';

// ============================================================================
// TYPES
// ============================================================================

type OnboardingStep = 1 | 2 | 3 | 4;

interface PersonalInfo {
  firstName: string;
  lastName: string;
  displayName: string;
  email: string;
  country: string;
  timezone: string;
}

interface RacingInfo {
  iracingId: string;
  experienceLevel: 'beginner' | 'intermediate' | 'advanced' | 'pro';
  preferredDiscipline: string;
  yearsRacing: string;
}

interface PreferencesInfo {
  favoriteTrack: string;
  favoriteCar: string;
  racingStyle: string;
  availability: string;
  lookingForTeam: boolean;
  openToRequests: boolean;
}

interface BioInfo {
  bio: string;
  goals: string;
}

interface FormErrors {
  firstName?: string;
  lastName?: string;
  displayName?: string;
  email?: string;
  country?: string;
  iracingId?: string;
  submit?: string;
}

// ============================================================================
// CONSTANTS
// ============================================================================

const COUNTRIES = [
  { code: 'US', name: 'United States' },
  { code: 'GB', name: 'United Kingdom' },
  { code: 'DE', name: 'Germany' },
  { code: 'NL', name: 'Netherlands' },
  { code: 'FR', name: 'France' },
  { code: 'IT', name: 'Italy' },
  { code: 'ES', name: 'Spain' },
  { code: 'AU', name: 'Australia' },
  { code: 'CA', name: 'Canada' },
  { code: 'BR', name: 'Brazil' },
  { code: 'JP', name: 'Japan' },
  { code: 'BE', name: 'Belgium' },
  { code: 'AT', name: 'Austria' },
  { code: 'CH', name: 'Switzerland' },
  { code: 'SE', name: 'Sweden' },
  { code: 'NO', name: 'Norway' },
  { code: 'DK', name: 'Denmark' },
  { code: 'FI', name: 'Finland' },
  { code: 'PL', name: 'Poland' },
  { code: 'PT', name: 'Portugal' },
];

const TIMEZONES = [
  { value: 'America/New_York', label: 'Eastern Time (ET)' },
  { value: 'America/Chicago', label: 'Central Time (CT)' },
  { value: 'America/Denver', label: 'Mountain Time (MT)' },
  { value: 'America/Los_Angeles', label: 'Pacific Time (PT)' },
  { value: 'Europe/London', label: 'Greenwich Mean Time (GMT)' },
  { value: 'Europe/Berlin', label: 'Central European Time (CET)' },
  { value: 'Europe/Paris', label: 'Central European Time (CET)' },
  { value: 'Australia/Sydney', label: 'Australian Eastern Time (AET)' },
  { value: 'Asia/Tokyo', label: 'Japan Standard Time (JST)' },
  { value: 'America/Sao_Paulo', label: 'Brasília Time (BRT)' },
];

const EXPERIENCE_LEVELS = [
  { value: 'beginner', label: 'Beginner', description: 'Just getting started with sim racing' },
  { value: 'intermediate', label: 'Intermediate', description: '1-2 years of experience' },
  { value: 'advanced', label: 'Advanced', description: '3+ years, competitive racing' },
  { value: 'pro', label: 'Pro/Semi-Pro', description: 'Professional level competition' },
];

const DISCIPLINES = [
  { value: 'road', label: 'Road Racing', icon: '🏎️' },
  { value: 'oval', label: 'Oval Racing', icon: '🏁' },
  { value: 'dirt-road', label: 'Dirt Road', icon: '🚗' },
  { value: 'dirt-oval', label: 'Dirt Oval', icon: '🏎️' },
  { value: 'multi', label: 'Multi-discipline', icon: '🎯' },
];

const RACING_STYLES = [
  { value: 'aggressive', label: 'Aggressive Overtaker', icon: '⚡' },
  { value: 'consistent', label: 'Consistent Pacer', icon: '📈' },
  { value: 'strategic', label: 'Strategic Calculator', icon: '🧠' },
  { value: 'late-braker', label: 'Late Braker', icon: '🎯' },
  { value: 'smooth', label: 'Smooth Operator', icon: '✨' },
];

const AVAILABILITY = [
  { value: 'weekday-evenings', label: 'Weekday Evenings (18:00-23:00)' },
  { value: 'weekends', label: 'Weekends Only' },
  { value: 'late-nights', label: 'Late Nights (22:00-02:00)' },
  { value: 'flexible', label: 'Flexible Schedule' },
  { value: 'mornings', label: 'Mornings (06:00-12:00)' },
];

// ============================================================================
// HELPER COMPONENTS
// ============================================================================

function StepIndicator({ currentStep, totalSteps }: { currentStep: number; totalSteps: number }) {
  const steps = [
    { id: 1, label: 'Personal', icon: User },
    { id: 2, label: 'Racing', icon: Gamepad2 },
    { id: 3, label: 'Preferences', icon: Heart },
    { id: 4, label: 'Bio & Goals', icon: Target },
  ];

  return (
    <div className="flex items-center justify-center gap-2 mb-8">
      {steps.map((step, index) => {
        const Icon = step.icon;
        const isCompleted = step.id < currentStep;
        const isCurrent = step.id === currentStep;

        return (
          <div key={step.id} className="flex items-center">
            <div className="flex flex-col items-center">
              <div
                className={`flex h-12 w-12 items-center justify-center rounded-full transition-all duration-300 ${
                  isCurrent
                    ? 'bg-primary-blue text-white shadow-lg shadow-primary-blue/30'
                    : isCompleted
                    ? 'bg-performance-green text-white'
                    : 'bg-iron-gray border border-charcoal-outline text-gray-500'
                }`}
              >
                {isCompleted ? (
                  <Check className="w-5 h-5" />
                ) : (
                  <Icon className="w-5 h-5" />
                )}
              </div>
              <span
                className={`mt-2 text-xs font-medium ${
                  isCurrent ? 'text-white' : isCompleted ? 'text-performance-green' : 'text-gray-500'
                }`}
              >
                {step.label}
              </span>
            </div>
            {index < steps.length - 1 && (
              <div
                className={`w-12 h-0.5 mx-2 mt-[-20px] ${
                  isCompleted ? 'bg-performance-green' : 'bg-charcoal-outline'
                }`}
              />
            )}
          </div>
        );
      })}
    </div>
  );
}

function SelectableCard({
  selected,
  onClick,
  icon,
  label,
  description,
  className = '',
}: {
  selected: boolean;
  onClick: () => void;
  icon?: string | React.ReactNode;
  label: string;
  description?: string;
  className?: string;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`p-4 rounded-xl border text-left transition-all ${
        selected
          ? 'bg-primary-blue/20 border-primary-blue text-white'
          : 'bg-iron-gray/50 border-charcoal-outline text-gray-400 hover:border-gray-500 hover:bg-iron-gray'
      } ${className}`}
    >
      <div className="flex items-center gap-3">
        {icon && (
          <span className="text-2xl">{typeof icon === 'string' ? icon : icon}</span>
        )}
        <div>
          <p className={`font-medium ${selected ? 'text-white' : 'text-gray-300'}`}>{label}</p>
          {description && (
            <p className={`text-xs mt-0.5 ${selected ? 'text-primary-blue/80' : 'text-gray-500'}`}>
              {description}
            </p>
          )}
        </div>
      </div>
    </button>
  );
}

// ============================================================================
// MAIN COMPONENT
// ============================================================================

export default function OnboardingWizard() {
  const router = useRouter();
  const [step, setStep] = useState<OnboardingStep>(1);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<FormErrors>({});

  // Form state
  const [personalInfo, setPersonalInfo] = useState<PersonalInfo>({
    firstName: '',
    lastName: '',
    displayName: '',
    email: '',
    country: '',
    timezone: '',
  });

  const [racingInfo, setRacingInfo] = useState<RacingInfo>({
    iracingId: '',
    experienceLevel: 'intermediate',
    preferredDiscipline: 'road',
    yearsRacing: '',
  });

  const [preferencesInfo, setPreferencesInfo] = useState<PreferencesInfo>({
    favoriteTrack: '',
    favoriteCar: '',
    racingStyle: 'consistent',
    availability: 'weekday-evenings',
    lookingForTeam: false,
    openToRequests: true,
  });

  const [bioInfo, setBioInfo] = useState<BioInfo>({
    bio: '',
    goals: '',
  });

  // Validation
  const validateStep = async (currentStep: OnboardingStep): Promise<boolean> => {
    const newErrors: FormErrors = {};

    if (currentStep === 1) {
      if (!personalInfo.firstName.trim()) {
        newErrors.firstName = 'First name is required';
      }
      if (!personalInfo.lastName.trim()) {
        newErrors.lastName = 'Last name is required';
      }
      if (!personalInfo.displayName.trim()) {
        newErrors.displayName = 'Display name is required';
      } else if (personalInfo.displayName.length < 3) {
        newErrors.displayName = 'Display name must be at least 3 characters';
      }
      if (!personalInfo.country) {
        newErrors.country = 'Please select your country';
      }
    }

    if (currentStep === 2) {
      if (!racingInfo.iracingId.trim()) {
        newErrors.iracingId = 'iRacing ID is required';
      } else {
        // Check if iRacing ID already exists
        const driverRepo = getDriverRepository();
        const exists = await driverRepo.existsByIRacingId(racingInfo.iracingId);
        if (exists) {
          newErrors.iracingId = 'This iRacing ID is already registered';
        }
      }
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleNext = async () => {
    const isValid = await validateStep(step);
    if (isValid && step < 4) {
      setStep((step + 1) as OnboardingStep);
    }
  };

  const handleBack = () => {
    if (step > 1) {
      setStep((step - 1) as OnboardingStep);
    }
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (loading) return;

    // Validate all steps
    for (let s = 1; s <= 4; s++) {
      const isValid = await validateStep(s as OnboardingStep);
      if (!isValid) {
        setStep(s as OnboardingStep);
        return;
      }
    }

    setLoading(true);
    setErrors({});

    try {
      const driverRepo = getDriverRepository();

      // Build bio with all the additional info
      const fullBio = [
        bioInfo.bio,
        bioInfo.goals ? `Goals: ${bioInfo.goals}` : '',
        `Experience: ${EXPERIENCE_LEVELS.find(e => e.value === racingInfo.experienceLevel)?.label}`,
        racingInfo.yearsRacing ? `Years Racing: ${racingInfo.yearsRacing}` : '',
        `Discipline: ${DISCIPLINES.find(d => d.value === racingInfo.preferredDiscipline)?.label}`,
        `Style: ${RACING_STYLES.find(s => s.value === preferencesInfo.racingStyle)?.label}`,
        preferencesInfo.favoriteTrack ? `Favorite Track: ${preferencesInfo.favoriteTrack}` : '',
        preferencesInfo.favoriteCar ? `Favorite Car: ${preferencesInfo.favoriteCar}` : '',
        `Available: ${AVAILABILITY.find(a => a.value === preferencesInfo.availability)?.label}`,
        preferencesInfo.lookingForTeam ? '🔍 Looking for team' : '',
        preferencesInfo.openToRequests ? '👋 Open to friend requests' : '',
      ].filter(Boolean).join('\n');

      const driver = Driver.create({
        id: crypto.randomUUID(),
        iracingId: racingInfo.iracingId.trim(),
        name: personalInfo.displayName.trim(),
        country: personalInfo.country,
        bio: fullBio || undefined,
      });

      await driverRepo.create(driver);
      
      router.push('/dashboard');
      router.refresh();
    } catch (error) {
      setErrors({
        submit: error instanceof Error ? error.message : 'Failed to create profile',
      });
      setLoading(false);
    }
  };

  const getCountryFlag = (countryCode: string): string => {
    const code = countryCode.toUpperCase();
    if (code.length === 2) {
      const codePoints = [...code].map(char => 127397 + char.charCodeAt(0));
      return String.fromCodePoint(...codePoints);
    }
    return '🏁';
  };

  return (
    <div className="max-w-3xl mx-auto px-4 py-10">
      {/* Header */}
      <div className="text-center mb-8">
        <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
          <Flag className="w-8 h-8 text-primary-blue" />
        </div>
        <Heading level={1} className="mb-2">Welcome to GridPilot</Heading>
        <p className="text-gray-400">
          Let's set up your racing profile in just a few steps
        </p>
      </div>

      {/* Progress Indicator */}
      <StepIndicator currentStep={step} totalSteps={4} />

      {/* Form Card */}
      <Card className="relative overflow-hidden">
        {/* Background accent */}
        <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />

        <form onSubmit={handleSubmit} className="relative">
          {/* Step 1: Personal Information */}
          {step === 1 && (
            <div className="space-y-6">
              <div>
                <Heading level={2} className="text-xl mb-1 flex items-center gap-2">
                  <User className="w-5 h-5 text-primary-blue" />
                  Personal Information
                </Heading>
                <p className="text-sm text-gray-400">
                  Tell us a bit about yourself
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label htmlFor="firstName" className="block text-sm font-medium text-gray-300 mb-2">
                    First Name *
                  </label>
                  <Input
                    id="firstName"
                    type="text"
                    value={personalInfo.firstName}
                    onChange={(e) =>
                      setPersonalInfo({ ...personalInfo, firstName: e.target.value })
                    }
                    error={!!errors.firstName}
                    errorMessage={errors.firstName}
                    placeholder="Max"
                    disabled={loading}
                  />
                </div>

                <div>
                  <label htmlFor="lastName" className="block text-sm font-medium text-gray-300 mb-2">
                    Last Name *
                  </label>
                  <Input
                    id="lastName"
                    type="text"
                    value={personalInfo.lastName}
                    onChange={(e) =>
                      setPersonalInfo({ ...personalInfo, lastName: e.target.value })
                    }
                    error={!!errors.lastName}
                    errorMessage={errors.lastName}
                    placeholder="Verstappen"
                    disabled={loading}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="displayName" className="block text-sm font-medium text-gray-300 mb-2">
                  Display Name * <span className="text-gray-500 font-normal">(shown publicly)</span>
                </label>
                <Input
                  id="displayName"
                  type="text"
                  value={personalInfo.displayName}
                  onChange={(e) =>
                    setPersonalInfo({ ...personalInfo, displayName: e.target.value })
                  }
                  error={!!errors.displayName}
                  errorMessage={errors.displayName}
                  placeholder="SuperMax33"
                  disabled={loading}
                />
              </div>

              <div>
                <label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
                  Email <span className="text-gray-500 font-normal">(optional, for notifications)</span>
                </label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                  <Input
                    id="email"
                    type="email"
                    value={personalInfo.email}
                    onChange={(e) =>
                      setPersonalInfo({ ...personalInfo, email: e.target.value })
                    }
                    placeholder="max@racing.com"
                    disabled={loading}
                    className="pl-10"
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label htmlFor="country" className="block text-sm font-medium text-gray-300 mb-2">
                    Country *
                  </label>
                  <div className="relative">
                    <Globe className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 z-10" />
                    <select
                      id="country"
                      value={personalInfo.country}
                      onChange={(e) =>
                        setPersonalInfo({ ...personalInfo, country: e.target.value })
                      }
                      className="block w-full rounded-md border-0 px-4 py-3 pl-10 bg-iron-gray text-white shadow-sm ring-1 ring-inset ring-charcoal-outline placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue transition-all duration-150 sm:text-sm appearance-none cursor-pointer"
                      disabled={loading}
                    >
                      <option value="">Select country</option>
                      {COUNTRIES.map((country) => (
                        <option key={country.code} value={country.code}>
                          {getCountryFlag(country.code)} {country.name}
                        </option>
                      ))}
                    </select>
                    <ChevronRight className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 rotate-90" />
                  </div>
                  {errors.country && (
                    <p className="mt-2 text-sm text-warning-amber">{errors.country}</p>
                  )}
                </div>

                <div>
                  <label htmlFor="timezone" className="block text-sm font-medium text-gray-300 mb-2">
                    Timezone
                  </label>
                  <div className="relative">
                    <Clock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 z-10" />
                    <select
                      id="timezone"
                      value={personalInfo.timezone}
                      onChange={(e) =>
                        setPersonalInfo({ ...personalInfo, timezone: e.target.value })
                      }
                      className="block w-full rounded-md border-0 px-4 py-3 pl-10 bg-iron-gray text-white shadow-sm ring-1 ring-inset ring-charcoal-outline placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue transition-all duration-150 sm:text-sm appearance-none cursor-pointer"
                      disabled={loading}
                    >
                      <option value="">Select timezone</option>
                      {TIMEZONES.map((tz) => (
                        <option key={tz.value} value={tz.value}>
                          {tz.label}
                        </option>
                      ))}
                    </select>
                    <ChevronRight className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 rotate-90" />
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 2: Racing Information */}
          {step === 2 && (
            <div className="space-y-6">
              <div>
                <Heading level={2} className="text-xl mb-1 flex items-center gap-2">
                  <Gamepad2 className="w-5 h-5 text-primary-blue" />
                  Racing Background
                </Heading>
                <p className="text-sm text-gray-400">
                  Tell us about your racing experience
                </p>
              </div>

              <div>
                <label htmlFor="iracingId" className="block text-sm font-medium text-gray-300 mb-2">
                  iRacing Customer ID *
                </label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-sm">#</span>
                  <Input
                    id="iracingId"
                    type="text"
                    value={racingInfo.iracingId}
                    onChange={(e) =>
                      setRacingInfo({ ...racingInfo, iracingId: e.target.value })
                    }
                    error={!!errors.iracingId}
                    errorMessage={errors.iracingId}
                    placeholder="123456"
                    disabled={loading}
                    className="pl-8"
                  />
                </div>
                <p className="mt-1 text-xs text-gray-500">
                  Find this in your iRacing account settings
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-3">
                  Experience Level
                </label>
                <div className="grid grid-cols-2 gap-3">
                  {EXPERIENCE_LEVELS.map((level) => (
                    <SelectableCard
                      key={level.value}
                      selected={racingInfo.experienceLevel === level.value}
                      onClick={() =>
                        setRacingInfo({
                          ...racingInfo,
                          experienceLevel: level.value as RacingInfo['experienceLevel'],
                        })
                      }
                      label={level.label}
                      description={level.description}
                    />
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-3">
                  Preferred Discipline
                </label>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                  {DISCIPLINES.map((discipline) => (
                    <SelectableCard
                      key={discipline.value}
                      selected={racingInfo.preferredDiscipline === discipline.value}
                      onClick={() =>
                        setRacingInfo({
                          ...racingInfo,
                          preferredDiscipline: discipline.value,
                        })
                      }
                      icon={discipline.icon}
                      label={discipline.label}
                    />
                  ))}
                </div>
              </div>

              <div>
                <label htmlFor="yearsRacing" className="block text-sm font-medium text-gray-300 mb-2">
                  Years Sim Racing
                </label>
                <div className="relative">
                  <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                  <Input
                    id="yearsRacing"
                    type="text"
                    value={racingInfo.yearsRacing}
                    onChange={(e) =>
                      setRacingInfo({ ...racingInfo, yearsRacing: e.target.value })
                    }
                    placeholder="e.g., 3 years"
                    disabled={loading}
                    className="pl-10"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Step 3: Preferences */}
          {step === 3 && (
            <div className="space-y-6">
              <div>
                <Heading level={2} className="text-xl mb-1 flex items-center gap-2">
                  <Heart className="w-5 h-5 text-primary-blue" />
                  Racing Preferences
                </Heading>
                <p className="text-sm text-gray-400">
                  Customize your racing profile
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label htmlFor="favoriteTrack" className="block text-sm font-medium text-gray-300 mb-2">
                    Favorite Track
                  </label>
                  <div className="relative">
                    <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <Input
                      id="favoriteTrack"
                      type="text"
                      value={preferencesInfo.favoriteTrack}
                      onChange={(e) =>
                        setPreferencesInfo({ ...preferencesInfo, favoriteTrack: e.target.value })
                      }
                      placeholder="e.g., Spa-Francorchamps"
                      disabled={loading}
                      className="pl-10"
                    />
                  </div>
                </div>

                <div>
                  <label htmlFor="favoriteCar" className="block text-sm font-medium text-gray-300 mb-2">
                    Favorite Car
                  </label>
                  <div className="relative">
                    <Car className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <Input
                      id="favoriteCar"
                      type="text"
                      value={preferencesInfo.favoriteCar}
                      onChange={(e) =>
                        setPreferencesInfo({ ...preferencesInfo, favoriteCar: e.target.value })
                      }
                      placeholder="e.g., Porsche 911 GT3 R"
                      disabled={loading}
                      className="pl-10"
                    />
                  </div>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-3">
                  Racing Style
                </label>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                  {RACING_STYLES.map((style) => (
                    <SelectableCard
                      key={style.value}
                      selected={preferencesInfo.racingStyle === style.value}
                      onClick={() =>
                        setPreferencesInfo({
                          ...preferencesInfo,
                          racingStyle: style.value,
                        })
                      }
                      icon={style.icon}
                      label={style.label}
                    />
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-3">
                  Availability
                </label>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {AVAILABILITY.map((avail) => (
                    <SelectableCard
                      key={avail.value}
                      selected={preferencesInfo.availability === avail.value}
                      onClick={() =>
                        setPreferencesInfo({
                          ...preferencesInfo,
                          availability: avail.value,
                        })
                      }
                      icon={<Clock className="w-4 h-4" />}
                      label={avail.label}
                    />
                  ))}
                </div>
              </div>

              <div className="space-y-3">
                <label className="block text-sm font-medium text-gray-300">
                  Status Flags
                </label>
                <div className="flex flex-wrap gap-3">
                  <button
                    type="button"
                    onClick={() =>
                      setPreferencesInfo({
                        ...preferencesInfo,
                        lookingForTeam: !preferencesInfo.lookingForTeam,
                      })
                    }
                    className={`flex items-center gap-2 px-4 py-3 rounded-xl border transition-all ${
                      preferencesInfo.lookingForTeam
                        ? 'bg-performance-green/20 border-performance-green text-performance-green'
                        : 'bg-iron-gray/50 border-charcoal-outline text-gray-400 hover:border-gray-500'
                    }`}
                  >
                    <Users className="w-4 h-4" />
                    <span className="text-sm font-medium">Looking for Team</span>
                  </button>

                  <button
                    type="button"
                    onClick={() =>
                      setPreferencesInfo({
                        ...preferencesInfo,
                        openToRequests: !preferencesInfo.openToRequests,
                      })
                    }
                    className={`flex items-center gap-2 px-4 py-3 rounded-xl border transition-all ${
                      preferencesInfo.openToRequests
                        ? 'bg-primary-blue/20 border-primary-blue text-primary-blue'
                        : 'bg-iron-gray/50 border-charcoal-outline text-gray-400 hover:border-gray-500'
                    }`}
                  >
                    <Heart className="w-4 h-4" />
                    <span className="text-sm font-medium">Open to Friend Requests</span>
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Step 4: Bio & Goals */}
          {step === 4 && (
            <div className="space-y-6">
              <div>
                <Heading level={2} className="text-xl mb-1 flex items-center gap-2">
                  <Target className="w-5 h-5 text-primary-blue" />
                  Bio & Goals
                </Heading>
                <p className="text-sm text-gray-400">
                  Tell the community about yourself and your racing aspirations
                </p>
              </div>

              <div>
                <label htmlFor="bio" className="block text-sm font-medium text-gray-300 mb-2">
                  About You
                </label>
                <textarea
                  id="bio"
                  value={bioInfo.bio}
                  onChange={(e) => setBioInfo({ ...bioInfo, bio: e.target.value })}
                  placeholder="Tell us about yourself, your racing history, what got you into sim racing..."
                  maxLength={500}
                  rows={4}
                  disabled={loading}
                  className="block w-full rounded-md border-0 px-4 py-3 bg-iron-gray text-white shadow-sm ring-1 ring-inset ring-charcoal-outline placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue transition-all duration-150 sm:text-sm sm:leading-6 resize-none"
                />
                <p className="mt-1 text-xs text-gray-500 text-right">
                  {bioInfo.bio.length}/500
                </p>
              </div>

              <div>
                <label htmlFor="goals" className="block text-sm font-medium text-gray-300 mb-2">
                  Racing Goals
                </label>
                <textarea
                  id="goals"
                  value={bioInfo.goals}
                  onChange={(e) => setBioInfo({ ...bioInfo, goals: e.target.value })}
                  placeholder="What are you hoping to achieve? Championship titles, improving lap times, joining a competitive team..."
                  maxLength={300}
                  rows={3}
                  disabled={loading}
                  className="block w-full rounded-md border-0 px-4 py-3 bg-iron-gray text-white shadow-sm ring-1 ring-inset ring-charcoal-outline placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue transition-all duration-150 sm:text-sm sm:leading-6 resize-none"
                />
                <p className="mt-1 text-xs text-gray-500 text-right">
                  {bioInfo.goals.length}/300
                </p>
              </div>

              {/* Preview */}
              <div className="p-4 rounded-xl bg-deep-graphite border border-charcoal-outline">
                <p className="text-xs text-gray-500 uppercase tracking-wider mb-3">Profile Preview</p>
                <div className="flex items-start gap-4">
                  <div className="w-16 h-16 rounded-xl bg-gradient-to-br from-primary-blue to-purple-600 flex items-center justify-center text-2xl font-bold text-white">
                    {personalInfo.displayName.charAt(0).toUpperCase() || '?'}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <p className="text-white font-semibold">{personalInfo.displayName || 'Your Name'}</p>
                      <span className="text-xl">{personalInfo.country ? getCountryFlag(personalInfo.country) : '🏁'}</span>
                    </div>
                    <div className="flex flex-wrap gap-2 text-xs">
                      <span className="px-2 py-0.5 rounded-full bg-primary-blue/20 text-primary-blue">
                        {EXPERIENCE_LEVELS.find(e => e.value === racingInfo.experienceLevel)?.label}
                      </span>
                      <span className="px-2 py-0.5 rounded-full bg-purple-500/20 text-purple-400">
                        {DISCIPLINES.find(d => d.value === racingInfo.preferredDiscipline)?.label}
                      </span>
                      {preferencesInfo.lookingForTeam && (
                        <span className="px-2 py-0.5 rounded-full bg-performance-green/20 text-performance-green">
                          Looking for Team
                        </span>
                      )}
                    </div>
                    {bioInfo.bio && (
                      <p className="text-gray-400 text-sm mt-2 line-clamp-2">{bioInfo.bio}</p>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Error Message */}
          {errors.submit && (
            <div className="mt-6 flex items-start gap-3 p-4 rounded-xl bg-red-500/10 border border-red-500/30">
              <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
              <p className="text-sm text-red-400">{errors.submit}</p>
            </div>
          )}

          {/* Navigation Buttons */}
          <div className="mt-8 flex items-center justify-between">
            <Button
              type="button"
              variant="secondary"
              onClick={handleBack}
              disabled={step === 1 || loading}
              className="flex items-center gap-2"
            >
              <ChevronLeft className="w-4 h-4" />
              Back
            </Button>

            {step < 4 ? (
              <Button
                type="button"
                variant="primary"
                onClick={handleNext}
                disabled={loading}
                className="flex items-center gap-2"
              >
                Continue
                <ChevronRight className="w-4 h-4" />
              </Button>
            ) : (
              <Button
                type="submit"
                variant="primary"
                disabled={loading}
                className="flex items-center gap-2"
              >
                {loading ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Creating Profile...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4" />
                    Complete Setup
                  </>
                )}
              </Button>
            )}
          </div>
        </form>
      </Card>

      {/* Help Text */}
      <p className="text-center text-xs text-gray-500 mt-6">
        You can always update your profile later in the settings
      </p>
    </div>
  );
}