'use client';

import type { DriverDTO } from '@gridpilot/racing/application/dto/DriverDTO';
import Button from '../ui/Button';
import { getDriverTeam } from '@/lib/racingLegacyFacade';

interface ProfileHeaderProps {
  driver: DriverDTO;
  isOwnProfile?: boolean;
  onEditClick?: () => void;
}

export default function ProfileHeader({ driver, isOwnProfile = false, onEditClick }: ProfileHeaderProps) {
  return (
    <div className="flex items-start justify-between">
      <div className="flex items-start gap-4">
        <div className="w-20 h-20 rounded-full bg-gradient-to-br from-primary-blue to-purple-600 flex items-center justify-center text-3xl font-bold text-white">
          {driver.name.charAt(0).toUpperCase()}
        </div>
        
        <div>
          <div className="flex items-center gap-3 mb-2">
            <h1 className="text-3xl font-bold text-white">{driver.name}</h1>
            <span className="text-3xl" aria-label={`Country: ${driver.country}`}>
              {getCountryFlag(driver.country)}
            </span>
            {(() => {
              const teamData = getDriverTeam(driver.id);
              if (teamData) {
                return (
                  <span className="px-3 py-1 bg-primary-blue/20 text-primary-blue rounded-full text-sm font-medium">
                    {teamData.team.tag}
                  </span>
                );
              }
              return null;
            })()}
          </div>
          
          <div className="flex items-center gap-4 text-sm text-gray-400">
            <span>iRacing ID: {driver.iracingId}</span>
            <span>•</span>
            <span>Rating: 1450</span>
            {(() => {
              const teamData = getDriverTeam(driver.id);
              if (teamData) {
                return (
                  <>
                    <span>•</span>
                    <span className="text-primary-blue">{teamData.team.name}</span>
                  </>
                );
              }
              return null;
            })()}
          </div>
        </div>
      </div>

      {isOwnProfile && (
        <Button variant="secondary" onClick={onEditClick}>
          Edit Profile
        </Button>
      )}
    </div>
  );
}

function 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 '🏁';
}