import { useState } from 'react'
import { Heart } from 'lucide-react'

function formatVotes(n) {
  if (n >= 1000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`
  return String(n)
}

function initials(name) {
  return name
    .split(' ')
    .filter(Boolean)
    .map((part) => part[0])
    .join('')
    .slice(0, 2)
    .toUpperCase()
}

export default function FinalistCard({
  option,
  rank,
  selected,
  onSelect,
  showVotes = true,
  showFollow = true,
}) {
  const [following, setFollowing] = useState(false)
  const firstName = option.name.split(' ')[0]

  return (
    <div
      role="button"
      tabIndex={0}
      onClick={onSelect}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault()
          onSelect?.()
        }
      }}
      className={`cursor-pointer overflow-hidden rounded-3xl border bg-white transition hover:-translate-y-1 hover:shadow-lg ${
        selected ? 'border-brand-500 ring-2 ring-brand-200' : 'border-brand-200'
      }`}
    >
      <div className={`relative flex aspect-[4/5] items-center justify-center bg-gradient-to-br ${option.gradient} p-5`}>
        {showVotes && (
          <span className="absolute left-4 top-4 inline-flex items-center gap-1.5 rounded-full bg-white/80 px-3 py-1.5 text-xs font-semibold text-brand-800 backdrop-blur-sm">
            <Heart className="h-3.5 w-3.5" />
            {formatVotes(option.votes)}
          </span>
        )}
        {rank && (
          <span className="absolute right-4 top-4 rounded-full bg-brand-900/90 px-3 py-1.5 text-[10px] font-bold uppercase tracking-[0.1em] text-white">
            Finalist #{rank}
          </span>
        )}
        <span className="flex h-20 w-20 items-center justify-center rounded-2xl bg-white/70 text-2xl font-bold text-brand-900 shadow-sm">
          {initials(option.name)}
        </span>
      </div>

      <div className="p-5">
        <h3 className="brand-heading text-lg font-bold text-brand-900">{option.name}</h3>
        <p className="mt-0.5 text-sm text-brand-700/70">{option.title}</p>

        {showFollow && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation()
              setFollowing((v) => !v)
            }}
            className={`mt-4 w-full rounded-full px-4 py-2.5 text-sm font-semibold transition ${
              following
                ? 'bg-brand-800 text-white hover:bg-brand-900'
                : 'border border-brand-300 bg-white text-brand-800 hover:bg-brand-50'
            }`}
          >
            {following ? 'Following' : `Follow ${firstName}`}
          </button>
        )}
      </div>
    </div>
  )
}
