'use client';
// Redeem.tsx — 兑换激活码 + 购买渠道（本站不收款,资金流全走外部）。承袭 UCRedeem。
import React, { useState } from 'react';
import { Icon } from './icons';
import { card, input } from './shared';
import { ErrorLine } from './Login';
import type { TFn, Lang } from '../lib/i18n';
import { getClient } from '../lib/api/client';
import { bilingual } from '../lib/api/errors';

export default function Redeem({ t, lang, onRedeemed }: { t: TFn; lang: Lang; onRedeemed?: () => void }) {
  const api = getClient();
  const [code, setCode] = useState('');
  const [ok, setOk] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  const channels: { icon: string; name: string; sub: string; accent?: boolean; mono?: boolean }[] = [
    { icon: 'shopping-bag', name: t('chStore'), sub: t('chStoreSub'), accent: true },
    { icon: 'credit-card', name: 'USDT (TRC20)', sub: t('chUsdtSub') },
    { icon: 'send', name: 'Telegram', sub: '@Pangolin_bot', mono: true },
    { icon: 'message-circle', name: 'LINE', sub: '@pangolinvpn', mono: true },
    { icon: 'mail', name: t('chEmail'), sub: 'buy@pangolin.vpn', mono: true },
  ];

  async function submit() {
    if (busy || code.trim().length < 4) return;
    setBusy(true);
    setErr('');
    try {
      await api.redeem(code.trim());
      setOk(true);
      onRedeemed?.();
    } catch (e) {
      setErr(bilingual(e, lang));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 680 }}>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 25, fontWeight: 700, color: 'var(--fg1)' }}>{t('navRedeem')}</div>
      <div style={{ ...card, padding: '20px 22px' }}>
        <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--fg1)', marginBottom: 12 }}>{t('redeemTitle')}</div>
        {ok ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, color: 'var(--success)', fontWeight: 600, fontSize: 15, padding: '4px 0' }}>
            <Icon name="check-circle" size={19} color="var(--success)" />
            {t('redeemOk')}
          </div>
        ) : (
          <>
            <div style={{ display: 'flex', gap: 10 }}>
              <input
                value={code}
                onChange={(e) => { setCode(e.target.value.toUpperCase()); setErr(''); }}
                onKeyDown={(e) => e.key === 'Enter' && submit()}
                placeholder={t('redeemPh')}
                style={{ ...input, fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}
              />
              <button onClick={submit} disabled={busy} style={{ border: 'none', borderRadius: 'var(--radius-md)', padding: '0 22px', background: 'var(--accent)', color: '#fff', fontWeight: 700, fontSize: 14, cursor: busy ? 'wait' : 'pointer', flexShrink: 0 }}>
                {busy ? t('loading') : t('redeemBtn')}
              </button>
            </div>
            {err && <div style={{ marginTop: 12 }}><ErrorLine text={err} /></div>}
          </>
        )}
      </div>
      <div>
        <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--fg1)', marginBottom: 5 }}>{t('buyTitle')}</div>
        <div style={{ fontSize: 12.5, color: 'var(--fg3)', lineHeight: 1.5, marginBottom: 13 }}>{t('buySub')}</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(240px,1fr))', gap: 11 }}>
          {channels.map((c) => (
            <button key={c.name} style={{ display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', cursor: 'pointer', background: c.accent ? 'var(--accent-subtle)' : 'var(--surface)', border: `1px solid ${c.accent ? 'var(--accent-border)' : 'var(--border)'}`, borderRadius: 'var(--radius-lg)', padding: '13px 15px', boxShadow: 'var(--shadow-sm)' }}>
              <div style={{ width: 38, height: 38, borderRadius: 'var(--radius-md)', background: c.accent ? 'var(--accent)' : 'var(--bg-subtle)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon name={c.icon} size={18} color={c.accent ? '#fff' : 'var(--accent)'} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg1)' }}>{c.name}</div>
                <div style={{ fontSize: 11.5, color: 'var(--fg3)', fontFamily: c.mono ? 'var(--font-mono)' : 'var(--font-sans)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.sub}</div>
              </div>
              <Icon name="external-link" size={15} color="var(--fg3)" />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
