/**
 * TierCard — upgrade-upsell-modal (spec 36).
 *
 * Renders a single tier card: display name, optional "★ מומלץ" badge, price
 * block, feature rows, and a CTA slot. Price text crossfades (150ms) when the
 * billing period changes, gated behind prefers-reduced-motion.
 *
 * Card states:
 *  - current tier  → --ink-soft border, "תוכנית נוכחית" label, disabled CTA
 *  - selected      → 2px --accent ring + elevated shadow
 *  - hover         → surface lightness shift via hover:bg-hover
 *  - readOnly      → no CTA, no selection ring (ask-admin view)
 */
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { cn } from '../lib/cn'
import type { TierCardData } from './tier-card-data'
import type { CtaVariant } from './cta-logic'

export interface TierCardProps {
  data: TierCardData
  period: 'monthly' | 'annual'
  selected: boolean
  isCurrent: boolean
  ctaVariant: CtaVariant
  /** null when ctaVariant === 'downgrade' — CTA hidden */
  ctaLabel: string | null
  /** mailto: href for contact / null_adapter variants */
  contactHref?: string
  /** disable CTA button while checkout POST is in flight */
  loading?: boolean
  /** ask-admin view: no CTAs, no selection ring */
  readOnly?: boolean
  onSelect(tier: TierCardData['tier']): void
  onCheckout(tier: TierCardData['tier']): void
}

export function TierCard({
  data,
  period,
  selected,
  isCurrent,
  ctaVariant,
  ctaLabel,
  contactHref,
  loading = false,
  readOnly = false,
  onSelect,
  onCheckout,
}: TierCardProps): React.JSX.Element {
  const { t } = useTranslation()
  const { tier, displayName, price, recommended, features } = data

  // --- Price display ---
  const priceContent = React.useMemo(() => {
    if (price.monthly === 0) {
      return (
        <span className="text-title-2 font-bold text-ink">
          {t('upgrade-modal.price_free', { defaultValue: 'Free forever' })}
        </span>
      )
    }
    if (price.monthly === null) {
      return (
        <span className="text-title-2 font-bold text-ink">
          {t('upgrade-modal.price_contact', { defaultValue: 'Contact us' })}
        </span>
      )
    }
    const amount = period === 'annual' && price.annual !== null ? price.annual : price.monthly
    return (
      <span className="text-title-2 font-bold text-ink">
        {t('upgrade-modal.price_per_month', {
          amount,
          defaultValue: `${amount} ₪ / mo`,
        })}
      </span>
    )
  }, [price, period, t])

  const annualBilledAsLine =
    period === 'annual' && price.annualBilledAs !== null ? (
      <p className="mt-1 text-meta text-ink-soft">
        {t('upgrade-modal.annual_billed_as', {
          amount: price.annualBilledAs,
          defaultValue: `Billed annually: ${price.annualBilledAs} ₪ (10 payments)`,
        })}
      </p>
    ) : null

  // --- Card click handler ---
  function handleCardClick() {
    if (!readOnly && !isCurrent) {
      onSelect(tier)
    }
  }

  // --- CTA slot ---
  function renderCta() {
    if (readOnly) return null
    if (ctaVariant === 'downgrade' || ctaLabel === null) return null

    if (ctaVariant === 'current') {
      return (
        <button
          type="button"
          disabled
          className={cn(
            'mt-4 w-full rounded py-2 text-body-2 font-medium',
            'bg-surface border border-line text-ink-soft opacity-60 cursor-default',
          )}
          aria-label={ctaLabel}
        >
          {ctaLabel}
        </button>
      )
    }

    if (ctaVariant === 'contact' || ctaVariant === 'null_adapter') {
      return (
        <a
          href={contactHref}
          className={cn(
            'mt-4 block w-full rounded py-2 text-center text-body-2 font-medium',
            'bg-accent text-ink-on-accent',
            'hover:opacity-90 transition-opacity motion-reduce:transition-none',
            'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-border',
          )}
        >
          {ctaLabel}
        </a>
      )
    }

    // ctaVariant === 'checkout'
    return (
      <button
        type="button"
        onClick={() => onCheckout(tier)}
        disabled={loading}
        aria-busy={loading}
        className={cn(
          'mt-4 w-full rounded py-2 text-body-2 font-medium',
          'bg-accent text-ink-on-accent',
          'hover:opacity-90 transition-opacity motion-reduce:transition-none',
          'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent-border',
          'disabled:opacity-50 disabled:pointer-events-none',
        )}
      >
        {loading ? t('common.loading', { defaultValue: 'Loading…' }) : ctaLabel}
      </button>
    )
  }

  return (
    <div
      role="group"
      aria-label={displayName}
      onClick={handleCardClick}
      className={cn(
        'relative flex flex-col rounded p-4 border cursor-pointer transition-colors motion-reduce:transition-none',
        'focus-within:outline-none',
        // current tier: muted border
        isCurrent && 'border-ink-soft cursor-default',
        // selected (non-current): accent 2px ring + shadow
        !isCurrent && selected && !readOnly && 'border-accent ring-2 ring-accent shadow',
        // unselected hover: surface darkens
        !isCurrent && !selected && !readOnly && 'border-line hover:bg-hover',
        // readOnly: no pointer events on the card itself
        readOnly && 'cursor-default border-line',
      )}
    >
      {/* Recommended badge */}
      {recommended && (
        <span className="mb-2 inline-flex self-start rounded px-2 py-0.5 text-meta font-semibold bg-accent-soft text-accent">
          {t('upgrade-modal.recommended_badge', { defaultValue: '★ Recommended' })}
        </span>
      )}

      {/* Current plan badge */}
      {isCurrent && (
        <span className="mb-2 inline-flex self-start rounded px-2 py-0.5 text-meta font-medium bg-surface border border-ink-soft text-ink-soft">
          {t('upgrade-modal.current_plan_badge', { defaultValue: 'Current plan' })}
        </span>
      )}

      {/* Display name */}
      <h3 className="text-title-3 font-semibold text-ink">{displayName}</h3>

      {/* Price block with crossfade animation (gated by prefers-reduced-motion) */}
      <div
        className="mt-2 min-h-[3rem] transition-opacity duration-150 motion-reduce:transition-none"
        key={`${period}-${tier}`}
      >
        {priceContent}
        {annualBilledAsLine}
      </div>

      {/* Feature rows */}
      <ul className="mt-4 flex flex-col gap-1.5" role="list">
        {features.map((f) => (
          <li
            key={f.labelKey}
            className={cn(
              'flex items-start gap-2 text-body-2',
              f.highlight && 'ps-1 border-s-4 border-accent bg-accent-soft -ms-1 rounded-e pe-1',
            )}
          >
            {f.available ? (
              <span
                className="mt-0.5 h-4 w-4 shrink-0 font-bold text-success"
                aria-hidden="true"
              >
                ✓
              </span>
            ) : (
              <span
                className="mt-0.5 h-4 w-4 shrink-0 font-bold text-ink-soft opacity-40"
                aria-hidden="true"
              >
                —
              </span>
            )}
            <span className={cn(f.available ? 'text-ink' : 'text-ink-soft opacity-60')}>
              {t(`upgrade-modal.${f.labelKey}`, { defaultValue: f.labelKey })}
            </span>
          </li>
        ))}
      </ul>

      {/* CTA slot */}
      {renderCta()}
    </div>
  )
}
