/**
 * PeriodToggle — upgrade-upsell-modal (spec 36).
 *
 * Segmented radio-group for switching between 'monthly' and 'annual' billing
 * periods. Active segment uses --accent background; inactive uses --surface.
 * Keyboard arrow keys move selection (standard radiogroup pattern).
 * Respects prefers-reduced-motion via Tailwind's motion-reduce modifier.
 */
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { cn } from '../lib/cn'

export interface PeriodToggleProps {
  value: 'monthly' | 'annual'
  onChange(next: 'monthly' | 'annual'): void
}

const OPTIONS = ['monthly', 'annual'] as const

export function PeriodToggle({ value, onChange }: PeriodToggleProps): React.JSX.Element {
  const { t } = useTranslation()

  function handleKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {
    const current = OPTIONS.indexOf(value)
    if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
      e.preventDefault()
      onChange(OPTIONS[(current + 1) % OPTIONS.length] as 'monthly' | 'annual')
    } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
      e.preventDefault()
      onChange(OPTIONS[(current - 1 + OPTIONS.length) % OPTIONS.length] as 'monthly' | 'annual')
    }
  }

  return (
    <div
      role="radiogroup"
      aria-label={t('upgrade-modal.period_label', { defaultValue: 'Billing period' })}
      className="inline-flex rounded border border-line bg-surface p-0.5"
      onKeyDown={handleKeyDown}
    >
      {OPTIONS.map((option) => {
        const isActive = value === option
        const label =
          option === 'monthly'
            ? t('upgrade-modal.period_monthly', { defaultValue: 'Monthly' })
            : t('upgrade-modal.period_annual', { defaultValue: 'Annual — save 17%' })

        return (
          <button
            key={option}
            type="button"
            role="radio"
            aria-checked={isActive}
            onClick={() => onChange(option)}
            className={cn(
              'relative rounded px-4 py-2 text-body-2 font-medium transition-colors motion-reduce:transition-none',
              'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-border',
              isActive
                ? 'bg-accent text-ink-on-accent'
                : 'bg-transparent text-ink-soft hover:text-ink',
            )}
          >
            {option === 'annual' && !isActive ? (
              <span className="flex items-center gap-2">
                {t('upgrade-modal.period_annual_short', { defaultValue: 'Annual' })}
                <span className="rounded px-1.5 py-0.5 text-meta font-semibold bg-success text-ink-on-accent">
                  {t('upgrade-modal.save_badge', { defaultValue: 'Save 17%' })}
                </span>
              </span>
            ) : (
              label
            )}
          </button>
        )
      })}
    </div>
  )
}
