/**
 * UserCenterScreen — storefront account dashboard.
 * Tabs: overview / orders / addresses / payment / profile / support
 * Styles live in screens.css (.yy-uc-*). Routed via index.html #/account/:tab.
 */

window.UserCenterScreen = function UserCenterScreen({ lang, onNav, user, tab, onUserUpdate, onOpenAuth }) {
  const L   = lang || 'zh';
  const zh  = L === 'zh';
  const tx  = (z, e) => zh ? z : e;
  const activeTab = tab || 'overview';

  // Guard: if the user is not logged in, show a friendly sign-in prompt.
  if (!user) {
    return (
      <div className="screen-body">
        <div className="yy-uc-wrap" style={{ maxWidth: 460 }}>
          <div className="yy-uc-panel" style={{ textAlign: 'center', padding: '44px 32px' }}>
            <h2 className="yy-uc-section-title" style={{ marginBottom: 8 }}>
              {tx('请先登录', 'Please sign in')}
            </h2>
            <p style={{ color: 'var(--fg-muted)', margin: '0 0 22px', fontSize: 14, lineHeight: 1.6 }}>
              {tx('登录后即可查看订单、管理收货地址与联系客服。',
                  'Sign in to view your orders, manage addresses, and contact support.')}
            </p>
            <button className="yy-uc-btn" onClick={onOpenAuth}>{tx('登录 / 注册', 'Sign in / Register')}</button>
          </div>
        </div>
      </div>
    );
  }

  const tabs = [
    { id: 'overview',  icon: '◐', zh: '概览',       en: 'Overview' },
    { id: 'orders',    icon: '▤', zh: '我的订单',   en: 'Orders' },
    { id: 'addresses', icon: '⌂', zh: '收货地址',   en: 'Addresses' },
    { id: 'payment',   icon: '◇', zh: '支付方式',   en: 'Payment' },
    { id: 'profile',   icon: '◯', zh: '账户资料',   en: 'Profile' },
    { id: 'support',   icon: '?', zh: '帮助与客服', en: 'Help & support' },
  ];

  return (
    <div className="screen-body">
      <div className="yy-uc-wrap">
        <div className="yy-uc-header">
          <h1 className="yy-uc-hello">
            {tx('你好,', 'Hello, ')}{user.name || user.email.split('@')[0]}
          </h1>
          <div className="yy-uc-email">{user.email}</div>
        </div>

        <div className="yy-uc-grid">
          <aside className="yy-uc-aside">
            {tabs.map(t => (
              <div key={t.id}
                   className={'yy-uc-tab ' + (t.id === activeTab ? 'on' : '')}
                   onClick={() => onNav('account', null, t.id)}>
                <span style={{ width: 18, textAlign: 'center', opacity: 0.7 }}>{t.icon}</span>
                <span>{zh ? t.zh : t.en}</span>
              </div>
            ))}
            <div className="yy-uc-tab-sep"/>
            <div className="yy-uc-signout"
                 onClick={() => { window.YY_API.logout().then(() => window.location.reload()); }}>
              {tx('退出登录', 'Sign out')}
            </div>
          </aside>

          <main className="yy-uc-main">
            {activeTab === 'overview'  && <UC_Overview  user={user} onNav={onNav} tx={tx}/>}
            {activeTab === 'orders'    && <UC_Orders    user={user} onNav={onNav} tx={tx} lang={L}/>}
            {activeTab === 'addresses' && <UC_Addresses user={user} tx={tx}/>}
            {activeTab === 'payment'   && <UC_Payment   tx={tx}/>}
            {activeTab === 'profile'   && <UC_Profile   user={user} tx={tx} onUserUpdate={onUserUpdate}/>}
            {activeTab === 'support'   && <UC_Support   user={user} tx={tx}/>}
          </main>
        </div>
      </div>
    </div>
  );
};

// ============================================================================
// Overview tab — quick stats + shortcut cards.
// ============================================================================
function UC_Overview({ user, onNav, tx }) {
  const [counts, setCounts] = React.useState({ orders: null, addresses: null });
  React.useEffect(() => {
    (async () => {
      try {
        const [os, as] = await Promise.all([
          window.YY_API.myOrders().catch(() => []),
          window.YY_API.myAddresses().catch(() => []),
        ]);
        setCounts({ orders: os.length, addresses: as.length });
      } catch {}
    })();
  }, []);
  const Card = ({ title, value, hint, onClick }) => (
    <div className="yy-uc-stat" onClick={onClick}>
      <div className="k">{title}</div>
      <div className="v">{value == null ? '—' : value}</div>
      <div className="h">{hint}</div>
    </div>
  );
  return (
    <div>
      <h2 className="yy-uc-section-title">{tx('账户概览', 'Account overview')}</h2>
      <div className="yy-uc-stats">
        <Card title={tx('订单', 'ORDERS')}       value={counts.orders}    hint={tx('查看订单与物流', 'View orders & tracking')} onClick={() => onNav('account', null, 'orders')}/>
        <Card title={tx('收货地址', 'ADDRESSES')} value={counts.addresses} hint={tx('管理收货地址', 'Manage addresses')}        onClick={() => onNav('account', null, 'addresses')}/>
        <Card title={tx('客户服务', 'SUPPORT')}   value={'∞'}              hint={tx('我们 24 小时在线', "We're here 24/7")}      onClick={() => onNav('account', null, 'support')}/>
      </div>
      <div className="yy-uc-empty" style={{ marginTop: 24, padding: '20px 22px', textAlign: 'left', borderStyle: 'dashed' }}>
        {tx(
          '欢迎回到 YYShop。你可以在左侧切换不同功能:查看订单详情、管理收货地址、修改账户资料或联系客服。',
          'Welcome back to YYShop. Use the sidebar on the left — view order details, manage addresses, update your profile, or contact support.'
        )}
      </div>
    </div>
  );
}

// ============================================================================
// Orders tab — list + detail panel.
// ============================================================================
function UC_Orders({ user, onNav, tx, lang }) {
  const [rows, setRows]   = React.useState(null);
  const [sel, setSel]     = React.useState(null);
  const [err, setErr]     = React.useState('');
  React.useEffect(() => {
    (async () => {
      try { setRows(await window.YY_API.myOrders()); }
      catch (e) { setErr(e.message); setRows([]); }
    })();
  }, []);

  const fmtDate = (s) => s ? new Date(s).toLocaleString(lang === 'zh' ? 'zh-CN' : 'en-US', { dateStyle: 'medium', timeStyle: 'short' }) : '';
  const statusLabel = (s) => ({
    pending:   tx('待付款',  'Pending'),
    paid:      tx('已付款',  'Paid'),
    shipped:   tx('已发货',  'Shipped'),
    delivered: tx('已送达',  'Delivered'),
    cancelled: tx('已取消',  'Cancelled'),
  })[s] || s;

  if (sel) {
    return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <span className="yy-uc-back" onClick={() => setSel(null)}>← {tx('返回订单列表', 'Back to orders')}</span>
          <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{fmtDate(sel.created_at)}</span>
        </div>
        <h2 className="yy-uc-section-title" style={{ marginBottom: 10 }}>
          {tx('订单', 'Order')} {sel.order_no}
        </h2>
        <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginBottom: 16 }}>
          {tx('状态', 'Status')}: <span className={'yy-uc-chip ' + sel.status} style={{ marginLeft: 6 }}>{statusLabel(sel.status)}</span>
        </div>

        <div className="yy-uc-panel">
          <h4>{tx('收件信息', 'Shipping')}</h4>
          <div className="body">
            {sel.customer_name}<br/>
            {sel.address1}{sel.address2 ? ', ' + sel.address2 : ''}<br/>
            {[sel.city, sel.postal, sel.country].filter(Boolean).join(', ')}<br/>
            {sel.phone}
          </div>
        </div>

        <div className="yy-uc-order-items">
          {(sel.items || []).map((it, i) => (
            <div key={i} className="yy-uc-order-item">
              <div className="thumb" style={{ backgroundImage: it.image_url ? `url(${it.image_url})` : 'none' }}/>
              <div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{(it.name && (it.name[lang] || it.name.en)) || it.title || '—'}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>{tx('数量', 'Qty')}: {it.qty || 1}</div>
              </div>
              <div className="yy-uc-money">${(Number(it.price) * (it.qty || 1)).toFixed(2)}</div>
            </div>
          ))}
        </div>

        <div className="yy-uc-totals">
          <div className="r"><span>{tx('小计', 'Subtotal')}</span><span>${Number(sel.subtotal).toFixed(2)}</span></div>
          <div className="r"><span>{tx('运费', 'Shipping')}</span><span>${Number(sel.shipping).toFixed(2)}</span></div>
          <div className="r"><span>{tx('税费', 'Tax')}</span><span>${Number(sel.tax).toFixed(2)}</span></div>
          <div className="r sum"><span>{tx('总计', 'Total')}</span><span>${Number(sel.total).toFixed(2)} {sel.currency}</span></div>
        </div>
      </div>
    );
  }

  return (
    <div>
      <h2 className="yy-uc-section-title">{tx('我的订单', 'My orders')}</h2>
      {rows == null && <div style={{ color: 'var(--fg-muted)', padding: 24 }}>{tx('加载中…', 'Loading…')}</div>}
      {rows && rows.length === 0 && (
        <div className="yy-uc-empty">
          <div className="ico">📦</div>
          <div>{tx('你还没有下过订单。', "You haven't placed any orders yet.")}</div>
          <div style={{ marginTop: 14 }}>
            <button className="yy-uc-btn" onClick={() => onNav('home')}>{tx('去逛逛', 'Start shopping')} →</button>
          </div>
        </div>
      )}
      {err && <div className="yy-uc-msg err">{err}</div>}
      {rows && rows.length > 0 && (
        <div className="yy-uc-list">
          {rows.map(r => (
            <div key={r.id} className="yy-uc-list-row" onClick={() => setSel(r)}>
              <div>
                <div className="yy-uc-order-no">{r.order_no}</div>
                <div className="yy-uc-order-meta">{fmtDate(r.created_at)} · {(r.items || []).length} {tx('件', 'items')}</div>
              </div>
              <div className={'yy-uc-chip ' + r.status}>{statusLabel(r.status)}</div>
              <div className="yy-uc-money">${Number(r.total).toFixed(2)}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ============================================================================
// Addresses tab — CRUD list + edit modal.
// ============================================================================
function UC_Addresses({ user, tx }) {
  const [rows, setRows]   = React.useState(null);
  const [edit, setEdit]   = React.useState(null); // address object or {} for new
  const [busy, setBusy]   = React.useState(false);
  const [err,  setErr]    = React.useState('');

  async function refresh() {
    setErr('');
    try { setRows(await window.YY_API.myAddresses()); }
    catch (e) { setErr(e.message); setRows([]); }
  }
  React.useEffect(() => { refresh(); }, []);

  async function save(form) {
    setBusy(true); setErr('');
    try {
      if (form.id) await window.YY_API.updateAddr(form.id, form);
      else         await window.YY_API.createAddr(form);
      setEdit(null);
      await refresh();
    } catch (e) { setErr(e.body?.error || e.message); }
    finally { setBusy(false); }
  }
  async function del(id) {
    if (!confirm(tx('确定删除这条地址?', 'Delete this address?'))) return;
    setBusy(true);
    try { await window.YY_API.deleteAddr(id); await refresh(); }
    catch (e) { setErr(e.body?.error || e.message); }
    finally { setBusy(false); }
  }
  async function makeDefault(id) {
    setBusy(true);
    try { await window.YY_API.defaultAddr(id); await refresh(); }
    catch (e) { setErr(e.body?.error || e.message); }
    finally { setBusy(false); }
  }

  return (
    <div>
      <div className="yy-uc-toolbar">
        <h2 className="yy-uc-section-title" style={{ margin: 0 }}>{tx('收货地址', 'Addresses')}</h2>
        <button className="yy-uc-btn" onClick={() => setEdit({})}>+ {tx('新增地址', 'Add address')}</button>
      </div>

      {err && <div className="yy-uc-msg err">{err}</div>}

      {rows == null && <div style={{ color: 'var(--fg-muted)', padding: 24 }}>{tx('加载中…', 'Loading…')}</div>}
      {rows && rows.length === 0 && (
        <div className="yy-uc-empty">
          <div className="ico">🏠</div>
          <div>{tx('暂无收货地址。', 'No addresses yet.')}</div>
          <div style={{ marginTop: 14 }}>
            <button className="yy-uc-btn" onClick={() => setEdit({})}>+ {tx('新增地址', 'Add address')}</button>
          </div>
        </div>
      )}
      {rows && rows.length > 0 && (
        <div className="yy-uc-addr-grid">
          {rows.map(a => (
            <div key={a.id} className={'yy-uc-addr-card ' + (a.is_default ? 'is-default' : '')}>
              {a.is_default && <div className="badge">{tx('默认', 'Default')}</div>}
              <div className="name">{a.recipient_name}</div>
              <div className="phone">{a.phone || '—'}</div>
              <div className="addr">
                {a.street}<br/>
                {[a.district, a.city, a.province].filter(Boolean).join(', ')}<br/>
                {[a.country, a.postal_code].filter(Boolean).join(' ')}
              </div>
              <div className="yy-uc-addr-actions">
                <button className="yy-uc-btn ghost sm" onClick={() => setEdit(a)}>{tx('编辑', 'Edit')}</button>
                {!a.is_default && <button className="yy-uc-btn ghost sm" onClick={() => makeDefault(a.id)}>{tx('设为默认', 'Set default')}</button>}
                <button className="yy-uc-btn danger sm" onClick={() => del(a.id)}>{tx('删除', 'Delete')}</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {edit && <AddressEditModal initial={edit} onClose={() => setEdit(null)} onSave={save} busy={busy} tx={tx}/>}
    </div>
  );
}

function AddressEditModal({ initial, onClose, onSave, busy, tx }) {
  const [f, setF] = React.useState({
    id:             initial.id,
    recipient_name: initial.recipient_name || '',
    phone:          initial.phone          || '',
    country:        initial.country        || 'China',
    province:       initial.province       || '',
    city:           initial.city           || '',
    district:       initial.district       || '',
    street:         initial.street         || '',
    postal_code:    initial.postal_code    || '',
    is_default:     !!initial.is_default,
  });
  const set = (k, v) => setF(x => ({ ...x, [k]: v }));
  return (
    <div className="yy-auth-backdrop" onClick={onClose}>
      <div className="yy-auth-modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 540 }}>
        <div className="yy-auth-tabs">
          <div className="yy-auth-tab on">
            {f.id ? tx('编辑地址', 'Edit address') : tx('新增地址', 'Add address')}
          </div>
          <button className="yy-auth-close" onClick={onClose} aria-label="Close">×</button>
        </div>
        <form className="yy-auth-body" onSubmit={e => { e.preventDefault(); onSave(f); }}>
          <div className="yy-uc-form" style={{ maxWidth: 'none', gap: 12 }}>
            <div className="yy-uc-field">
              <label className="yy-uc-label">{tx('收件人', 'Recipient name')}</label>
              <input className="yy-uc-input" required value={f.recipient_name} onChange={e => set('recipient_name', e.target.value)}/>
            </div>
            <div className="yy-uc-field">
              <label className="yy-uc-label">{tx('手机号', 'Phone')}</label>
              <input className="yy-uc-input" type="tel" value={f.phone} onChange={e => set('phone', e.target.value)}/>
            </div>
            <div className="yy-uc-row2">
              <div className="yy-uc-field">
                <label className="yy-uc-label">{tx('国家', 'Country')}</label>
                <input className="yy-uc-input" value={f.country} onChange={e => set('country', e.target.value)}/>
              </div>
              <div className="yy-uc-field">
                <label className="yy-uc-label">{tx('省 / 州', 'Province / State')}</label>
                <input className="yy-uc-input" value={f.province} onChange={e => set('province', e.target.value)}/>
              </div>
            </div>
            <div className="yy-uc-row2">
              <div className="yy-uc-field">
                <label className="yy-uc-label">{tx('城市', 'City')}</label>
                <input className="yy-uc-input" value={f.city} onChange={e => set('city', e.target.value)}/>
              </div>
              <div className="yy-uc-field">
                <label className="yy-uc-label">{tx('区 / 县', 'District')}</label>
                <input className="yy-uc-input" value={f.district} onChange={e => set('district', e.target.value)}/>
              </div>
            </div>
            <div className="yy-uc-field">
              <label className="yy-uc-label">{tx('详细地址', 'Street address')}</label>
              <input className="yy-uc-input" required value={f.street} onChange={e => set('street', e.target.value)}/>
            </div>
            <div className="yy-uc-field">
              <label className="yy-uc-label">{tx('邮编', 'Postal code')}</label>
              <input className="yy-uc-input" value={f.postal_code} onChange={e => set('postal_code', e.target.value)}/>
            </div>
            <label className="yy-uc-checkline" style={{ marginTop: 4 }}>
              <input type="checkbox" checked={!!f.is_default} onChange={e => set('is_default', e.target.checked)}/>
              {tx('设为默认地址', 'Set as default')}
            </label>
          </div>
          <button type="submit" className="yy-auth-submit" disabled={busy}>
            {busy ? '…' : (f.id ? tx('保存', 'Save') : tx('新增', 'Add'))}
          </button>
        </form>
      </div>
    </div>
  );
}

// ============================================================================
// Payment tab — placeholder only (per product decision).
// ============================================================================
function UC_Payment({ tx }) {
  return (
    <div>
      <h2 className="yy-uc-section-title">{tx('支付方式', 'Payment methods')}</h2>
      <div className="yy-uc-placeholder">
        <div className="ico">💳</div>
        <h3>{tx('即将上线', 'Coming soon')}</h3>
        <p>{tx(
          '我们正在接入支付方式管理,支持信用卡、微信、支付宝、PayPal 等。敬请期待。',
          "We're adding payment method management — credit cards, WeChat, Alipay, and PayPal. Stay tuned."
        )}</p>
      </div>
    </div>
  );
}

// ============================================================================
// Profile tab — name / phone / locale + password change + email change.
// ============================================================================
function UC_Profile({ user, tx, onUserUpdate }) {
  const [form, setForm] = React.useState({ name: user.name || '', phone: user.phone || '', locale: user.locale || 'zh' });
  const [pw,   setPw]   = React.useState({ current: '', next: '', confirm: '' });
  const [msg,  setMsg]  = React.useState('');
  const [err,  setErr]  = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [emailModal, setEmailModal] = React.useState(false);

  async function saveProfile(e) {
    e.preventDefault();
    setBusy(true); setErr(''); setMsg('');
    try {
      const r = await window.YY_API.updateProfile(form);
      if (onUserUpdate && r.user) onUserUpdate(r.user);
      setMsg(tx('已保存', 'Saved'));
    } catch (e) { setErr(e.body?.error || e.message); }
    finally { setBusy(false); }
  }
  async function changePw(e) {
    e.preventDefault();
    setBusy(true); setErr(''); setMsg('');
    if (pw.next !== pw.confirm) { setErr(tx('两次输入的新密码不一致', 'New passwords do not match')); setBusy(false); return; }
    if (pw.next.length < 6)    { setErr(tx('密码至少 6 位', 'Password must be at least 6 characters')); setBusy(false); return; }
    try {
      await window.YY_API.changePassword(pw.current, pw.next);
      setPw({ current: '', next: '', confirm: '' });
      setMsg(tx('密码已更新', 'Password updated'));
    } catch (e) {
      const code = e.body?.error || e.message;
      setErr(code === 'bad_current_password' ? tx('当前密码错误', 'Current password is incorrect') : code);
    }
    finally { setBusy(false); }
  }

  return (
    <div>
      <h2 className="yy-uc-section-title">{tx('账户资料', 'Profile')}</h2>
      {msg && <div className="yy-uc-msg ok">{msg}</div>}
      {err && <div className="yy-uc-msg err">{err}</div>}

      <form onSubmit={saveProfile} className="yy-uc-form">
        <div className="yy-uc-field">
          <label className="yy-uc-label">{tx('邮箱', 'Email')}</label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 10 }}>
            <input className="yy-uc-input" disabled value={user.email}/>
            <button type="button" className="yy-uc-btn ghost sm" onClick={() => setEmailModal(true)}>
              {tx('修改邮箱', 'Change email')}
            </button>
          </div>
        </div>
        <div className="yy-uc-field">
          <label className="yy-uc-label">{tx('姓名', 'Name')}</label>
          <input className="yy-uc-input" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))}/>
        </div>
        <div className="yy-uc-field">
          <label className="yy-uc-label">{tx('手机号', 'Phone')}</label>
          <input className="yy-uc-input" value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))}/>
        </div>
        <div className="yy-uc-field">
          <label className="yy-uc-label">{tx('语言', 'Language')}</label>
          <select className="yy-uc-select" value={form.locale} onChange={e => setForm(f => ({ ...f, locale: e.target.value }))}>
            <option value="zh">中文</option>
            <option value="en">English</option>
          </select>
        </div>
        <button type="submit" className="yy-uc-btn" disabled={busy} style={{ justifySelf: 'start', marginTop: 4 }}>
          {busy ? '…' : tx('保存', 'Save')}
        </button>
      </form>

      <div style={{ borderTop: '1px solid var(--border)', margin: '32px 0 20px' }}/>

      <h3 className="yy-uc-subtitle" style={{ marginTop: 0 }}>{tx('修改密码', 'Change password')}</h3>
      <form onSubmit={changePw} className="yy-uc-form">
        <div className="yy-uc-field">
          <label className="yy-uc-label">{tx('当前密码', 'Current password')}</label>
          <input className="yy-uc-input" type="password" required value={pw.current} onChange={e => setPw(p => ({ ...p, current: e.target.value }))}/>
        </div>
        <div className="yy-uc-field">
          <label className="yy-uc-label">{tx('新密码(至少 6 位)', 'New password (min 6)')}</label>
          <input className="yy-uc-input" type="password" required minLength="6" value={pw.next} onChange={e => setPw(p => ({ ...p, next: e.target.value }))}/>
        </div>
        <div className="yy-uc-field">
          <label className="yy-uc-label">{tx('确认新密码', 'Confirm new password')}</label>
          <input className="yy-uc-input" type="password" required value={pw.confirm} onChange={e => setPw(p => ({ ...p, confirm: e.target.value }))}/>
        </div>
        <button type="submit" className="yy-uc-btn" disabled={busy} style={{ justifySelf: 'start' }}>
          {busy ? '…' : tx('更新密码', 'Update password')}
        </button>
      </form>

      {emailModal && (
        <EmailChangeModal
          user={user}
          tx={tx}
          onClose={() => setEmailModal(false)}
          onDone={(u) => { if (onUserUpdate) onUserUpdate(u); setEmailModal(false); setMsg(tx('邮箱已更新', 'Email updated')); }}
        />
      )}
    </div>
  );
}

// ----------------------------------------------------------------------------
// EmailChangeModal — 3-step dual-code flow: password → old code → new code.
// ----------------------------------------------------------------------------
function EmailChangeModal({ user, tx, onClose, onDone }) {
  const [step, setStep]         = React.useState('start'); // start | old | new | done
  const [form, setForm]         = React.useState({ new_email: '', password: '' });
  const [codeOld, setCodeOld]   = React.useState('');
  const [codeNew, setCodeNew]   = React.useState('');
  const [busy, setBusy]         = React.useState(false);
  const [err,  setErr]          = React.useState('');
  const [msg,  setMsg]          = React.useState('');
  const [newAddr, setNewAddr]   = React.useState('');

  const xlate = (code) => ({
    invalid_email:        tx('邮箱格式不正确', 'Invalid email'),
    same_email:           tx('新邮箱不能与当前邮箱相同', 'New email must differ from the current one'),
    email_exists:         tx('该邮箱已被使用', 'Email already in use'),
    bad_current_password: tx('当前密码错误', 'Current password is incorrect'),
    bad_code:             tx('验证码不正确', 'Incorrect code'),
    code_expired:         tx('验证码已过期', 'Code expired'),
    request_expired:      tx('请求已过期,请重新开始', 'Request expired, please restart'),
    too_many_attempts:    tx('尝试次数过多,请稍后重试', 'Too many attempts, try later'),
    no_pending_request:   tx('无进行中的请求', 'No pending request'),
  })[code] || code;

  async function doStart(e) {
    e.preventDefault();
    setBusy(true); setErr(''); setMsg('');
    try {
      const r = await window.YY_API.emailChangeStart(form.new_email.trim().toLowerCase(), form.password);
      setNewAddr(form.new_email.trim().toLowerCase());
      setStep('old');
      setMsg(tx(`验证码已发送至旧邮箱 ${user.email}`, `Code sent to your current email ${user.email}`));
    } catch (e) { setErr(xlate(e.body?.error || e.message)); }
    finally { setBusy(false); }
  }
  async function doVerifyOld(e) {
    e.preventDefault();
    setBusy(true); setErr(''); setMsg('');
    try {
      await window.YY_API.emailChangeVerifyOld(codeOld.trim());
      setStep('new');
      setMsg(tx(`验证码已发送至新邮箱 ${newAddr}`, `Code sent to your new email ${newAddr}`));
    } catch (e) { setErr(xlate(e.body?.error || e.message)); }
    finally { setBusy(false); }
  }
  async function doVerifyNew(e) {
    e.preventDefault();
    setBusy(true); setErr(''); setMsg('');
    try {
      const r = await window.YY_API.emailChangeVerifyNew(codeNew.trim());
      onDone(r.user);
    } catch (e) { setErr(xlate(e.body?.error || e.message)); }
    finally { setBusy(false); }
  }
  async function resend() {
    setBusy(true); setErr(''); setMsg('');
    try {
      await window.YY_API.emailChangeResend(step === 'new' ? 'new' : 'old');
      setMsg(tx('验证码已重新发送', 'A new code has been sent.'));
    } catch (e) { setErr(xlate(e.body?.error || e.message)); }
    finally { setBusy(false); }
  }

  return (
    <div className="yy-auth-backdrop" onClick={busy ? null : onClose}>
      <div className="yy-auth-modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 460 }}>
        <div className="yy-auth-tabs">
          <div className="yy-auth-tab on">{tx('修改邮箱', 'Change email')}</div>
          <button className="yy-auth-close" onClick={onClose} aria-label="Close">×</button>
        </div>
        <div className="yy-auth-body">
          {/* progress indicator */}
          <div style={{ display: 'flex', gap: 8, marginBottom: 14, fontSize: 11, color: 'var(--fg-muted)' }}>
            <StepDot n="1" label={tx('输入', 'Enter')}   state={step === 'start' ? 'active' : 'done'}/>
            <StepDot n="2" label={tx('旧邮箱', 'Old email')} state={step === 'old' ? 'active' : (step === 'start' ? 'pending' : 'done')}/>
            <StepDot n="3" label={tx('新邮箱', 'New email')} state={step === 'new' ? 'active' : (step === 'start' || step === 'old' ? 'pending' : 'done')}/>
          </div>

          {msg && <div className="yy-uc-msg ok" style={{ marginTop: 0 }}>{msg}</div>}
          {err && <div className="yy-uc-msg err" style={{ marginTop: 0 }}>{err}</div>}

          {step === 'start' && (
            <form onSubmit={doStart} className="yy-uc-form" style={{ maxWidth: 'none', marginTop: 10 }}>
              <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
                {tx('为了安全,修改邮箱需要分别在 ',
                    'For security, changing email requires a 6-digit code sent to ')}
                <strong>{tx('旧邮箱', 'your old email')}</strong>
                {tx(' 和 ', ' and ')}
                <strong>{tx('新邮箱', 'new email')}</strong>
                {tx(' 收到一次 6 位验证码。', '.')}
              </div>
              <div className="yy-uc-field">
                <label className="yy-uc-label">{tx('新邮箱地址', 'New email address')}</label>
                <input className="yy-uc-input" type="email" required value={form.new_email}
                       onChange={e => setForm(f => ({ ...f, new_email: e.target.value }))}/>
              </div>
              <div className="yy-uc-field">
                <label className="yy-uc-label">{tx('当前密码', 'Current password')}</label>
                <input className="yy-uc-input" type="password" required value={form.password}
                       onChange={e => setForm(f => ({ ...f, password: e.target.value }))}/>
              </div>
              <button type="submit" className="yy-uc-btn" disabled={busy} style={{ marginTop: 6 }}>
                {busy ? '…' : tx('发送验证码到旧邮箱', 'Send code to old email')}
              </button>
            </form>
          )}

          {step === 'old' && (
            <form onSubmit={doVerifyOld} className="yy-uc-form" style={{ maxWidth: 'none', marginTop: 10 }}>
              <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
                {tx('请输入发送到 ', 'Enter the 6-digit code sent to ')}<strong>{user.email}</strong>
                {tx(' 的 6 位验证码。', '.')}
              </div>
              <div className="yy-uc-field">
                <label className="yy-uc-label">{tx('旧邮箱验证码', 'Old-email code')}</label>
                <input className="yy-uc-input yy-uc-code-input" required maxLength="6" inputMode="numeric"
                       value={codeOld} onChange={e => setCodeOld(e.target.value.replace(/\D/g, '').slice(0, 6))}/>
              </div>
              <div style={{ display: 'flex', gap: 10 }}>
                <button type="submit" className="yy-uc-btn" disabled={busy || codeOld.length !== 6}>
                  {busy ? '…' : tx('验证并继续', 'Verify & continue')}
                </button>
                <button type="button" className="yy-uc-btn ghost" disabled={busy} onClick={resend}>
                  {tx('重新发送', 'Resend')}
                </button>
              </div>
            </form>
          )}

          {step === 'new' && (
            <form onSubmit={doVerifyNew} className="yy-uc-form" style={{ maxWidth: 'none', marginTop: 10 }}>
              <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
                {tx('请输入发送到 ', 'Enter the 6-digit code sent to ')}<strong>{newAddr}</strong>
                {tx(' 的 6 位验证码,即可完成邮箱修改。', '.')}
              </div>
              <div className="yy-uc-field">
                <label className="yy-uc-label">{tx('新邮箱验证码', 'New-email code')}</label>
                <input className="yy-uc-input yy-uc-code-input" required maxLength="6" inputMode="numeric"
                       value={codeNew} onChange={e => setCodeNew(e.target.value.replace(/\D/g, '').slice(0, 6))}/>
              </div>
              <div style={{ display: 'flex', gap: 10 }}>
                <button type="submit" className="yy-uc-btn" disabled={busy || codeNew.length !== 6}>
                  {busy ? '…' : tx('完成修改', 'Confirm change')}
                </button>
                <button type="button" className="yy-uc-btn ghost" disabled={busy} onClick={resend}>
                  {tx('重新发送', 'Resend')}
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

function StepDot({ n, label, state }) {
  const bg = state === 'active' ? 'var(--accent)'
           : state === 'done'   ? 'rgba(34,160,90,0.18)'
           : 'var(--surface)';
  const fg = state === 'active' ? 'var(--accent-fg)'
           : state === 'done'   ? '#2a7'
           : 'var(--fg-muted)';
  const bd = state === 'active' ? 'var(--accent)'
           : state === 'done'   ? 'rgba(34,160,90,0.35)'
           : 'var(--border)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <span style={{ width: 20, height: 20, borderRadius: 999, display: 'inline-flex',
                     alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 600,
                     background: bg, color: fg, border: `1px solid ${bd}` }}>
        {state === 'done' ? '✓' : n}
      </span>
      <span style={{ color: state === 'active' ? 'var(--fg)' : 'var(--fg-muted)' }}>{label}</span>
    </div>
  );
}

// ============================================================================
// Support tab — FAQ + ticket form.
// ============================================================================
function UC_Support({ user, tx }) {
  const [form, setForm] = React.useState({ subject: '', body: '' });
  const [msg,  setMsg]  = React.useState('');
  const [err,  setErr]  = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [open, setOpen] = React.useState(-1);

  const faqs = [
    { q: tx('多久能收到货?', 'How long does delivery take?'),
      a: tx('国内一般 3-5 个工作日,国际 7-14 个工作日。订单确认后会发送物流追踪链接到您的邮箱。',
             'Domestic orders usually arrive in 3-5 business days; international 7-14. A tracking link is emailed once your order ships.') },
    { q: tx('如何退换货?', 'How do I return or exchange?'),
      a: tx('收到商品后 14 天内,联系客服发起退换。请保持商品吊牌完整且未洗涤未穿着。',
             'Contact us within 14 days of receipt. Items must be unworn, unwashed, with original tags attached.') },
    { q: tx('可以开发票吗?', 'Can I get an invoice?'),
      a: tx('可以。下单后联系客服并提供抬头信息,我们会将电子发票发到您的邮箱。',
             'Yes — email us after checkout with your billing info and we will send an e-invoice to your email.') },
    { q: tx('支持哪些支付方式?', 'Which payment methods do you accept?'),
      a: tx('目前支持信用卡、微信支付、支付宝、PayPal。更多方式即将上线。',
             'Credit cards, WeChat Pay, Alipay, and PayPal. More options coming soon.') },
  ];

  async function submit(e) {
    e.preventDefault();
    setBusy(true); setErr(''); setMsg('');
    try {
      await window.YY_API.submitTicket({
        subject: form.subject,
        body:    form.body,
        email:   user?.email,
        name:    user?.name,
      });
      setForm({ subject: '', body: '' });
      setMsg(tx('已提交,我们会尽快通过邮件回复您。', "We've received your message — we'll reply by email shortly."));
    } catch (e) { setErr(e.body?.error || e.message); }
    finally { setBusy(false); }
  }

  return (
    <div>
      <h2 className="yy-uc-section-title">{tx('帮助与客服', 'Help & support')}</h2>

      <h3 className="yy-uc-subtitle">{tx('常见问题', 'FAQ')}</h3>
      <div className="yy-uc-faq">
        {faqs.map((f, i) => (
          <div key={i} className="yy-uc-faq-item">
            <div className="yy-uc-faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
              <span>{f.q}</span>
              <span className="chev">{open === i ? '−' : '+'}</span>
            </div>
            {open === i && <div className="yy-uc-faq-a">{f.a}</div>}
          </div>
        ))}
      </div>

      <h3 className="yy-uc-subtitle">{tx('联系客服', 'Contact support')}</h3>
      <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginBottom: 12 }}>
        {tx('或直接发送邮件至 ', 'Or email us at ')}
        <a href="mailto:yyshop@bitsfactor.com" style={{ color: 'var(--accent)', borderBottom: '1px solid var(--accent)' }}>yyshop@bitsfactor.com</a>
        {tx(',我们通常 24 小时内回复。', ' — typical response within 24 hours.')}
      </div>
      {msg && <div className="yy-uc-msg ok">{msg}</div>}
      {err && <div className="yy-uc-msg err">{err}</div>}
      <form onSubmit={submit} className="yy-uc-form" style={{ maxWidth: 560 }}>
        <div className="yy-uc-field">
          <label className="yy-uc-label">{tx('主题', 'Subject')}</label>
          <input className="yy-uc-input" required value={form.subject}
                 onChange={e => setForm(f => ({ ...f, subject: e.target.value }))}/>
        </div>
        <div className="yy-uc-field">
          <label className="yy-uc-label">{tx('问题描述', 'Description')}</label>
          <textarea className="yy-uc-textarea" required rows="5" value={form.body}
                    onChange={e => setForm(f => ({ ...f, body: e.target.value }))}/>
        </div>
        <button type="submit" className="yy-uc-btn" disabled={busy} style={{ justifySelf: 'start' }}>
          {busy ? '…' : tx('提交', 'Submit')}
        </button>
      </form>
    </div>
  );
}
