// Montvale 결제수단 UI (montvalefloristnj.com 그대로)
// 카드 브랜드 4종(Visa·Mastercard·Amex·Discover) + 디지털 월렛 2종(Apple Pay·Google Pay).
// 카드 전체번호는 화면 저장/표시 금지 — 마스킹. 실제 결제는 백엔드 PaymentGateway 어댑터 경유.
import { useState, ReactElement } from 'react'
import { CreditCard, Lock } from 'lucide-react'

/* ── 카드 브랜드 배지 (인라인 SVG, 외부 의존성 없음) ── */
function VisaBadge() {
  return (
    <svg viewBox="0 0 48 32" className="h-7 w-auto" role="img" aria-label="Visa">
      <rect width="48" height="32" rx="4" fill="#fff" stroke="#e7e2dc" />
      <text x="24" y="21" textAnchor="middle" fontFamily="Georgia, serif" fontWeight="700" fontStyle="italic" fontSize="13" fill="#1a1f71">VISA</text>
    </svg>
  )
}
function MastercardBadge() {
  return (
    <svg viewBox="0 0 48 32" className="h-7 w-auto" role="img" aria-label="Mastercard">
      <rect width="48" height="32" rx="4" fill="#fff" stroke="#e7e2dc" />
      <circle cx="20" cy="16" r="8" fill="#eb001b" />
      <circle cx="28" cy="16" r="8" fill="#f79e1b" fillOpacity="0.85" />
    </svg>
  )
}
function AmexBadge() {
  return (
    <svg viewBox="0 0 48 32" className="h-7 w-auto" role="img" aria-label="American Express">
      <rect width="48" height="32" rx="4" fill="#2e77bb" />
      <text x="24" y="20" textAnchor="middle" fontFamily="Arial, sans-serif" fontWeight="700" fontSize="9" fill="#fff">AMEX</text>
    </svg>
  )
}
function DiscoverBadge() {
  return (
    <svg viewBox="0 0 48 32" className="h-7 w-auto" role="img" aria-label="Discover">
      <rect width="48" height="32" rx="4" fill="#fff" stroke="#e7e2dc" />
      <circle cx="36" cy="22" r="9" fill="#f68121" />
      <text x="22" y="19" textAnchor="middle" fontFamily="Arial, sans-serif" fontWeight="700" fontSize="7" fill="#231f20">DISCOVER</text>
    </svg>
  )
}
function ApplePayBadge() {
  return (
    <svg viewBox="0 0 48 32" className="h-7 w-auto" role="img" aria-label="Apple Pay">
      <rect width="48" height="32" rx="4" fill="#000" />
      <text x="24" y="20" textAnchor="middle" fontFamily="-apple-system, Helvetica, sans-serif" fontWeight="600" fontSize="9" fill="#fff"> Pay</text>
    </svg>
  )
}
function GooglePayBadge() {
  return (
    <svg viewBox="0 0 48 32" className="h-7 w-auto" role="img" aria-label="Google Pay">
      <rect width="48" height="32" rx="4" fill="#fff" stroke="#e7e2dc" />
      <text x="24" y="20" textAnchor="middle" fontFamily="Arial, sans-serif" fontWeight="700" fontSize="9">
        <tspan fill="#4285f4">G</tspan><tspan fill="#ea4335">o</tspan><tspan fill="#fbbc05">o</tspan><tspan fill="#4285f4">g</tspan><tspan fill="#34a853">l</tspan><tspan fill="#ea4335">e</tspan>
        <tspan fill="#5f6368"> Pay</tspan>
      </text>
    </svg>
  )
}

const BADGES: Record<string, () => ReactElement> = {
  Visa: VisaBadge,
  Mastercard: MastercardBadge,
  Amex: AmexBadge,
  Discover: DiscoverBadge,
  'Apple Pay': ApplePayBadge,
  'Google Pay': GooglePayBadge,
}

// 푸터/About 등에 쓰는 결제수단 배지 줄 (6종 그대로)
export function PaymentBadges({ items, className = '' }: { items: string[]; className?: string }) {
  return (
    <div className={`flex flex-wrap items-center gap-1.5 ${className}`}>
      {items.map(p => {
        const B = BADGES[p]
        return B ? <B key={p} /> : <span key={p} className="text-[10px] bg-cream/10 rounded px-2 py-1">{p}</span>
      })}
    </div>
  )
}

/* ── 카드 번호 마스킹: 마지막 4자리만 노출 ── */
export function maskCard(num: string): string {
  const digits = num.replace(/\D/g, '')
  if (digits.length < 4) return '•••• •••• •••• ••••'
  return `•••• •••• •••• ${digits.slice(-4)}`
}
function formatCardInput(num: string): string {
  return num.replace(/\D/g, '').slice(0, 16).replace(/(.{4})/g, '$1 ').trim()
}

export type WalletMethod = 'APPLE_PAY' | 'GOOGLE_PAY'
export type PayMethod = 'CARD' | WalletMethod

/* ── 결제 섹션: 카드 폼(Stripe Elements 스타일 모의) + 디지털 월렛 버튼 ──
 * 카드 전체번호는 컴포넌트 외부로 전달하지 않으며(부모는 마지막4·만료만 수신), 화면에는 마스킹만 표시.
 * 운영 시 Stripe Elements로 교체 가능 — 동일한 onChange 계약 유지. */
export function PaymentSection({
  method,
  onMethod,
  onCardChange,
  cards = ['Visa', 'Mastercard', 'Amex', 'Discover'],
  wallets = ['Apple Pay', 'Google Pay'],
}: {
  method: PayMethod
  onMethod: (m: PayMethod) => void
  onCardChange?: (info: { last4: string; expiry: string; complete: boolean }) => void
  cards?: string[]
  wallets?: string[]
}) {
  const [number, setNumber] = useState('')
  const [expiry, setExpiry] = useState('')
  const [cvc, setCvc] = useState('')
  const [name, setName] = useState('')
  const [focused, setFocused] = useState(false)

  const digits = number.replace(/\D/g, '')
  const emit = (n = number, e = expiry, c = cvc) => {
    const d = n.replace(/\D/g, '')
    const complete = d.length >= 15 && /^\d{2}\/\d{2}$/.test(e) && c.replace(/\D/g, '').length >= 3
    onCardChange?.({ last4: d.slice(-4), expiry: e, complete })
  }

  const walletKey = (w: string): WalletMethod => (w === 'Apple Pay' ? 'APPLE_PAY' : 'GOOGLE_PAY')

  return (
    <div className="space-y-4">
      {/* 결제수단 선택 (카드 + 디지털 월렛) */}
      <div className="grid grid-cols-3 gap-2">
        <button
          type="button" onClick={() => onMethod('CARD')}
          className={`flex items-center justify-center gap-1.5 py-2.5 rounded-xl border text-sm ${method === 'CARD' ? 'border-bloom bg-petal text-bloom2 font-semibold' : 'border-blush-100 text-[#6b5258]'}`}>
          <CreditCard size={16} /> Card
        </button>
        {wallets.map(w => {
          const key = walletKey(w)
          const B = BADGES[w]
          return (
            <button
              key={w} type="button" onClick={() => onMethod(key)}
              className={`flex items-center justify-center py-2 rounded-xl border ${method === key ? 'border-bloom bg-petal' : 'border-blush-100'}`}
              aria-label={w}>
              {B ? <B /> : <span className="text-sm">{w}</span>}
            </button>
          )
        })}
      </div>

      {/* 허용 카드 브랜드 배지 */}
      <div className="flex items-center gap-2">
        <span className="text-[11px] text-gray-400">Accepted:</span>
        <PaymentBadges items={cards} />
      </div>

      {method === 'CARD' ? (
        // Stripe Elements 스타일 모의 폼 — 전체번호 미저장/마스킹
        <div className="rounded-2xl border border-blush-100 p-4 space-y-3 bg-white">
          <div>
            <label className="block text-xs text-gray-500 mb-1">Card number</label>
            <div className="flex items-center gap-2 px-3 py-2.5 rounded-xl border border-blush-100 focus-within:border-bloom">
              <CreditCard size={16} className="text-blush-400 shrink-0" />
              <input
                inputMode="numeric" autoComplete="cc-number"
                value={focused ? formatCardInput(number) : (digits ? maskCard(number) : '')}
                onFocus={() => setFocused(true)}
                onBlur={() => setFocused(false)}
                onChange={e => { const v = e.target.value; setNumber(v); emit(v) }}
                placeholder="1234 1234 1234 1234"
                className="flex-1 bg-transparent text-sm outline-none tracking-wider" />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs text-gray-500 mb-1">Expiry (MM/YY)</label>
              <input
                inputMode="numeric" autoComplete="cc-exp" value={expiry}
                onChange={e => {
                  let v = e.target.value.replace(/\D/g, '').slice(0, 4)
                  if (v.length >= 3) v = v.slice(0, 2) + '/' + v.slice(2)
                  setExpiry(v); emit(number, v)
                }}
                placeholder="MM/YY"
                className="w-full px-3 py-2.5 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">CVC</label>
              <input
                inputMode="numeric" autoComplete="cc-csc" value={cvc}
                onChange={e => { const v = e.target.value.replace(/\D/g, '').slice(0, 4); setCvc(v); emit(number, expiry, v) }}
                placeholder="•••" type="password"
                className="w-full px-3 py-2.5 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
            </div>
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">Name on card</label>
            <input
              autoComplete="cc-name" value={name} onChange={e => setName(e.target.value)}
              placeholder="Full name"
              className="w-full px-3 py-2.5 rounded-xl border border-blush-100 text-sm outline-none focus:border-bloom" />
          </div>
          <p className="flex items-center gap-1 text-[11px] text-gray-400">
            <Lock size={11} /> Card number is masked and never stored on this device. Processed via GUARDiA PaymentGateway.
          </p>
        </div>
      ) : (
        // 디지털 월렛 — 버튼 표시 (미설정 시 백엔드 mock 처리)
        <div className="rounded-2xl border border-blush-100 p-4 bg-white">
          <button
            type="button"
            className={`w-full py-3 rounded-xl font-semibold flex items-center justify-center gap-2 ${method === 'APPLE_PAY' ? 'bg-black text-white' : 'bg-white border border-edge text-[#3c4043]'}`}>
            {method === 'APPLE_PAY' ? ' Pay' : 'G Pay'}
          </button>
          <p className="flex items-center gap-1 text-[11px] text-gray-400 mt-2">
            <Lock size={11} /> {method === 'APPLE_PAY' ? 'Apple Pay' : 'Google Pay'} via secure wallet. If unconfigured, processed as mock at checkout.
          </p>
        </div>
      )}
    </div>
  )
}
