const BB_ACCOUNT_PLANS = {
  free: {
    id: 'free',
    name: 'Free',
    monthlyLimit: 5,
    monthlyPrice: 0,
    badge: 'Trial',
    description: '适合快速体验算量和报价审核。',
  },
  plus: {
    id: 'plus',
    name: 'Plus',
    monthlyLimit: 20,
    monthlyPrice: 9.9,
    badge: 'Popular',
    description: '适合个人业主和小型装修项目。',
  },
  pro: {
    id: 'pro',
    name: 'Pro',
    monthlyLimit: 50,
    monthlyPrice: 19.9,
    badge: 'Studio',
    description: '适合设计师、监理和连续审核场景。',
  },
};

const BB_ACCOUNT_KEY = 'bb:account:v1';
const BB_ACCOUNT_MODES = [
  { id: 'quantity', name: '图纸算量', icon: 'ruler' },
  { id: 'quote', name: '报价审核', icon: 'search-check' },
  { id: 'compare', name: '多报价对比', icon: 'scale' },
  { id: 'combined', name: '报价算量联审', icon: 'layers' },
];

const currentMonthKey = () => new Date().toISOString().slice(0, 7);

const emptyModeUsage = () => BB_ACCOUNT_MODES.reduce((acc, mode) => {
  acc[mode.id] = 0;
  return acc;
}, {});

const normalizeModeUsage = (value = {}) => {
  const next = emptyModeUsage();
  BB_ACCOUNT_MODES.forEach(mode => {
    next[mode.id] = Math.max(0, Number(value?.[mode.id] || 0));
  });
  return next;
};

const formatAccountDate = (value) => {
  if (!value) return '—';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '—';
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
};

const nextBillingDate = (payment, billing) => {
  if (!payment?.at) return null;
  const date = new Date(payment.at);
  if (Number.isNaN(date.getTime())) return null;
  if (billing === 'yearly') date.setFullYear(date.getFullYear() + 1);
  else date.setMonth(date.getMonth() + 1);
  return date.toISOString();
};

const normalizeAccount = (value = {}) => {
  const plan = BB_ACCOUNT_PLANS[value.plan] ? value.plan : 'free';
  const usage = value.usage && value.usage.month === currentMonthKey()
    ? value.usage
    : { month: currentMonthKey(), used: 0 };
  return {
    user: value.user || null,
    plan,
    billing: value.billing === 'yearly' ? 'yearly' : 'monthly',
    usage,
    modeUsage: normalizeModeUsage(value.modeUsage),
    billingHistory: Array.isArray(value.billingHistory) ? value.billingHistory.slice(0, 12) : [],
    subscriptionStatus: ['active', 'canceled', 'past_due'].includes(value.subscriptionStatus) ? value.subscriptionStatus : 'active',
    lastPayment: value.lastPayment || null,
    provider: value.provider || null,
    customerPortalUrl: value.customerPortalUrl || '',
    currentPeriodStart: value.currentPeriodStart || null,
    currentPeriodEnd: value.currentPeriodEnd || null,
    renewsAt: value.renewsAt || null,
    endsAt: value.endsAt || null,
    cancelledAt: value.cancelledAt || null,
    checkoutSessions: Array.isArray(value.checkoutSessions) ? value.checkoutSessions.slice(0, 5) : [],
    refundRequests: Array.isArray(value.refundRequests) ? value.refundRequests.slice(0, 10) : [],
    pendingCheckout: value.pendingCheckout || null,
  };
};

const readAccount = () => {
  try {
    return normalizeAccount(JSON.parse(localStorage.getItem(BB_ACCOUNT_KEY) || '{}'));
  } catch (e) {
    return normalizeAccount();
  }
};

const saveAccount = (value) => {
  const next = normalizeAccount(value);
  localStorage.setItem(BB_ACCOUNT_KEY, JSON.stringify(next));
  return next;
};

const accountUsageView = (account) => {
  const normalized = normalizeAccount(account);
  const plan = BB_ACCOUNT_PLANS[normalized.plan] || BB_ACCOUNT_PLANS.free;
  const used = Math.max(0, Number(normalized.usage.used || 0));
  const limit = plan.monthlyLimit;
  return {
    used,
    limit,
    remaining: Math.max(0, limit - used),
    percent: Math.max(0, Math.min(100, (used / Math.max(1, limit)) * 100)),
  };
};

const bumpAccountUsage = (account, modeId) => {
  const next = normalizeAccount(account);
  const usage = accountUsageView(next);
  const modeUsage = normalizeModeUsage(next.modeUsage);
  if (modeUsage[modeId] !== undefined) {
    modeUsage[modeId] += 1;
  }
  return normalizeAccount({
    ...next,
    usage: {
      month: currentMonthKey(),
      used: usage.used + 1,
    },
    modeUsage,
  });
};

const planPrice = (plan, billing) => {
  if (!plan.monthlyPrice) return '$0';
  if (billing === 'yearly') return `$${(plan.monthlyPrice * 10).toFixed(0)}`;
  return `$${plan.monthlyPrice.toFixed(1)}`;
};

const planPeriodLabel = (billing) => billing === 'yearly' ? '/年' : '/月';

const AccountModal = ({ initialView = 'login', account, onChange, onClose }) => {
  const [view, setView] = React.useState(initialView);
  const [form, setForm] = React.useState({ name: '', email: '', password: '', confirm: '', remember: true });
  const [billing, setBilling] = React.useState(account.billing || 'monthly');
  const [selectedPlan, setSelectedPlan] = React.useState(account.plan === 'free' ? 'plus' : account.plan);
  const [processing, setProcessing] = React.useState(false);
  const [authBusy, setAuthBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const [refundReason, setRefundReason] = React.useState('');
  const [refundMessage, setRefundMessage] = React.useState('');
  const [securityForm, setSecurityForm] = React.useState({ current: '', next: '', confirm: '' });
  const [securityMessage, setSecurityMessage] = React.useState('');

  React.useEffect(() => {
    setView(initialView);
    setBilling(account.billing || 'monthly');
    setSelectedPlan(account.plan === 'free' ? 'plus' : account.plan);
  }, [initialView]);

  const currentPlan = BB_ACCOUNT_PLANS[account.plan] || BB_ACCOUNT_PLANS.free;
  const usage = accountUsageView(account);
  const modeUsage = normalizeModeUsage(account.modeUsage);
  const modeUsageTotal = BB_ACCOUNT_MODES.reduce((sum, mode) => sum + modeUsage[mode.id], 0);
  const selected = BB_ACCOUNT_PLANS[selectedPlan] || BB_ACCOUNT_PLANS.plus;
  const isLoggedIn = !!account.user;
  const renewalDate = account.renewsAt || account.currentPeriodEnd || (
    account.plan !== 'free' && account.subscriptionStatus !== 'canceled'
      ? nextBillingDate(account.lastPayment, account.billing)
      : null
  );
  const latestRefund = (account.refundRequests || [])[0] || null;
  const subscriptionStatusLabel = {
    active: '有效',
    canceled: account.endsAt || account.currentPeriodEnd ? '取消中' : '已取消',
    past_due: '支付异常',
  }[account.subscriptionStatus] || account.subscriptionStatus;
  const billingStatusLabel = (status) => ({
    paid: '已支付',
    refunded: '已退款',
    pending: '处理中',
    pending_review: '待审核',
    approved: '审核通过，待平台退款',
    rejected: '已拒绝',
    manual_review: '人工复核中',
    failed: '失败',
  }[status] || status || '—');

  const update = (patch) => onChange(normalizeAccount({ ...account, ...patch }));
  const authConfigured = window.BB_AUTH?.isConfigured?.();

  const finishLogin = (user) => {
    update({ user });
    setError('');
    setView(initialView === 'subscription' || initialView === 'subscribe' ? 'subscription' : 'overview');
  };

  const submitLogin = async () => {
    if (!form.email.trim() || !form.password.trim()) {
      setError('请输入邮箱和密码。');
      return;
    }
    try {
      setAuthBusy(true);
      const next = await window.BB_AUTH.signInEmail({ email: form.email.trim(), password: form.password });
      onChange(next);
      setError('');
      setView(initialView === 'subscription' || initialView === 'subscribe' ? 'subscription' : 'overview');
    } catch (err) {
      setError(err.message || '登录失败');
    } finally {
      setAuthBusy(false);
    }
  };

  const submitRegister = async () => {
    if (!form.name.trim() || !form.email.trim() || !form.password.trim()) {
      setError('请填写姓名、邮箱和密码。');
      return;
    }
    if (form.password !== form.confirm) {
      setError('两次输入的密码不一致。');
      return;
    }
    try {
      setAuthBusy(true);
      const next = await window.BB_AUTH.signUpEmail({ name: form.name.trim(), email: form.email.trim(), password: form.password });
      onChange(next);
      setError('');
      if (next.user) {
        setView(initialView === 'subscription' || initialView === 'subscribe' ? 'subscription' : 'overview');
      } else {
        setError('注册已提交，请查收邮箱完成验证后再登录。');
      }
    } catch (err) {
      setError(err.message || '注册失败');
    } finally {
      setAuthBusy(false);
    }
  };

  const googleLogin = async () => {
    try {
      setAuthBusy(true);
      const next = await window.BB_AUTH.signInGoogle();
      if (next) {
        onChange(next);
        setView(initialView === 'subscription' || initialView === 'subscribe' ? 'subscription' : 'overview');
      }
      setError('');
    } catch (err) {
      setError(err.message || 'Google 登录失败');
    } finally {
      setAuthBusy(false);
    }
  };

  const startCheckout = (planId) => {
    if (!isLoggedIn) {
      setSelectedPlan(planId);
      setView('register');
      return;
    }
    if (planId !== 'plus') {
      setError('首版仅开放 Plus 月付，Pro 和年付稍后接入。');
      return;
    }
    setSelectedPlan(planId);
    setBilling('monthly');
    setView('checkout');
  };

  const completePayment = async () => {
    setProcessing(true);
    try {
      const checkout = await window.BB_AUTH.createCheckout();
      if (checkout?.checkout_url) {
        const checkoutUrl = new URL(checkout.checkout_url);
        const isLemonSqueezy = checkoutUrl.protocol === 'https:'
          && (checkoutUrl.hostname === 'lemonsqueezy.com' || checkoutUrl.hostname.endsWith('.lemonsqueezy.com'));
        if (!isLemonSqueezy) {
          throw new Error('支付服务返回了无效链接，请联系管理员。');
        }
        window.location.assign(checkoutUrl.toString());
        return;
      }
      setError('未获取到 Lemon Squeezy 支付链接，请稍后重试。');
    } catch (err) {
      setError(err.message || '创建支付链接失败');
    } finally {
      setProcessing(false);
    }
  };

  const logout = async () => {
    try {
      const next = await window.BB_AUTH.signOut();
      onChange(next);
      setView('login');
      onClose?.();
    } catch (err) {
      setError(err.message || '退出失败');
    }
  };

  const cancelSubscription = () => {
    if (!isLoggedIn) {
      setView('login');
      return;
    }
    if (account.plan === 'free') return;
    if (account.customerPortalUrl) {
      window.open(account.customerPortalUrl, '_blank', 'noopener,noreferrer');
      return;
    }
    setError('当前还没有 Lemon Squeezy 订阅管理链接，请等待支付 webhook 同步后刷新。');
  };

  const requestRefund = async () => {
    try {
      setProcessing(true);
      setRefundMessage('');
      const payload = await window.BB_AUTH.requestRefund({ reason: refundReason });
      if (payload?.account) onChange(payload.account);
      setRefundReason('');
      setRefundMessage('申请已提交到 BitBuild 后台，不会直接发送给 Lemon Squeezy。审核通过后，管理员还需在 Lemon Squeezy 执行退款。');
    } catch (err) {
      setRefundMessage(err.message || '退款申请失败');
    } finally {
      setProcessing(false);
    }
  };

  const changePassword = async () => {
    if (!securityForm.current.trim() || !securityForm.next.trim()) {
      setSecurityMessage('请填写当前密码和新密码。');
      return;
    }
    if (securityForm.next.length < 6) {
      setSecurityMessage('新密码至少 6 位。');
      return;
    }
    if (securityForm.next !== securityForm.confirm) {
      setSecurityMessage('两次输入的新密码不一致。');
      return;
    }
    try {
      await window.BB_AUTH.updatePassword(securityForm.next, securityForm.current);
      setSecurityForm({ current: '', next: '', confirm: '' });
      setSecurityMessage(authConfigured ? '密码已更新。' : '密码已更新。当前未配置 Supabase，仍为本地原型。');
    } catch (err) {
      setSecurityMessage(err.message || '密码更新失败');
    }
  };

  const deleteAccount = async () => {
    if (!window.confirm('确认删除当前账号？这会清空登录、订阅和用量数据。')) return;
    try {
      const next = await window.BB_AUTH.deleteAccount();
      onChange(next);
      setSecurityMessage('');
      setView('login');
    } catch (err) {
      setSecurityMessage(err.message || '删除账号失败');
    }
  };

  const renderAuth = (mode) => (
    <div className="account-pane">
      <div className="account-switch">
        <button className={mode === 'login' ? 'active' : ''} onClick={() => { setView('login'); setError(''); }}>登录</button>
        <button className={mode === 'register' ? 'active' : ''} onClick={() => { setView('register'); setError(''); }}>注册</button>
      </div>

      <button className="account-google" onClick={googleLogin} disabled={authBusy}>
        <span className="account-google-mark">G</span>
        {authBusy ? '处理中...' : '使用 Google 继续'}
      </button>

      <div className="account-divider"><span>或使用邮箱</span></div>

      {mode === 'register' && (
        <label className="account-field">
          <span>姓名</span>
          <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="陈明" />
        </label>
      )}
      <label className="account-field">
        <span>邮箱</span>
        <input value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} placeholder="you@example.com" />
      </label>
      <label className="account-field">
        <span>密码</span>
        <input type="password" value={form.password} onChange={e => setForm({ ...form, password: e.target.value })} placeholder="至少 6 位" />
      </label>
      {mode === 'register' && (
        <label className="account-field">
          <span>确认密码</span>
          <input type="password" value={form.confirm} onChange={e => setForm({ ...form, confirm: e.target.value })} placeholder="再次输入密码" />
        </label>
      )}
      {mode === 'login' && (
        <label className="account-check">
          <input type="checkbox" checked={form.remember} onChange={e => setForm({ ...form, remember: e.target.checked })} />
          记住登录状态
        </label>
      )}
      {error && <div className="account-error">{error}</div>}
      <button className="btn btn-primary account-submit" disabled={authBusy} onClick={mode === 'login' ? submitLogin : submitRegister}>
        {authBusy ? '处理中...' : (mode === 'login' ? '登录' : '创建账号')}
      </button>
      <p className="account-note">{authConfigured ? '账号由 Supabase Auth 托管，密码不会进入 BitBuild 前端代码。' : '当前未配置 Supabase，登录仍使用本地原型数据。'}</p>
    </div>
  );

  const renderOverview = () => (
    <div className="account-pane">
      <div className="account-profile-row">
        <div className="account-profile-avatar">{(account.user?.name || account.user?.email || 'U').slice(0, 1).toUpperCase()}</div>
        <div>
          <div className="account-profile-name">{account.user?.name || '未命名用户'}</div>
          <div className="account-profile-email">{account.user?.email}</div>
        </div>
      </div>

      <div className="account-metrics">
        <div>
          <span>当前套餐</span>
          <strong>{currentPlan.name}</strong>
        </div>
        <div>
          <span>本月已用</span>
          <strong>{usage.used}</strong>
        </div>
        <div>
          <span>剩余次数</span>
          <strong>{usage.remaining}</strong>
        </div>
      </div>

      <div className="account-usage-line">
        <div><span style={{ width: `${usage.percent}%` }} /></div>
        <p>每月额度 {usage.limit} 次，四种模式共用本月总额度。</p>
      </div>

      <div className="account-section">
        <div className="account-section-head">
          <strong>累计使用</strong>
          <span>合计 {modeUsageTotal} 次</span>
        </div>
        <div className="account-mode-grid">
          {BB_ACCOUNT_MODES.map(mode => (
            <div className="account-mode-card" key={mode.id}>
              <div className="account-mode-icon"><Icon name={mode.icon} size={15} /></div>
              <div>
                <span>{mode.name}</span>
                <strong>{modeUsage[mode.id]}</strong>
              </div>
            </div>
          ))}
        </div>
      </div>

      {account.lastPayment && (
        <div className="account-receipt">
          最近订阅：{BB_ACCOUNT_PLANS[account.lastPayment.plan]?.name} {account.lastPayment.amount}{planPeriodLabel(account.lastPayment.billing)}
        </div>
      )}
      {account.pendingCheckout && (
        <div className="account-receipt">
          支付确认中：请完成 Lemon Squeezy 付款，系统收到 webhook 后自动生效。
        </div>
      )}

      <div className="account-actions">
        <button className="btn btn-primary" onClick={() => setView('subscription')}>管理订阅</button>
        <button className="btn btn-ghost" onClick={logout}>退出登录</button>
      </div>
    </div>
  );

  const renderSubscription = () => (
    <div className="account-pane">
      <div className="account-section account-cycle">
        <div className="account-section-head">
          <strong>订阅周期</strong>
          <span>{subscriptionStatusLabel}</span>
        </div>
        <div className="account-cycle-grid">
          <div>
            <span>当前套餐</span>
            <strong>{currentPlan.name}</strong>
          </div>
          <div>
            <span>账单周期</span>
            <strong>{account.plan === 'free' ? '无续费' : (account.billing === 'yearly' ? '年付' : '月付')}</strong>
          </div>
          <div>
            <span>{account.subscriptionStatus === 'canceled' ? '权益到期' : '下次续费'}</span>
            <strong>{renewalDate ? formatAccountDate(renewalDate) : '—'}</strong>
          </div>
        </div>
        {account.plan !== 'free' && (
          <button className="account-cancel" onClick={cancelSubscription}>打开订阅管理</button>
        )}
      </div>

      <div className="account-billing-toggle">
        <button className={billing === 'monthly' ? 'active' : ''} onClick={() => setBilling('monthly')}>月付</button>
        <button className={billing === 'yearly' ? 'active' : ''} onClick={() => setError('首版仅开放 Plus 月付。')}>年付 <span>稍后开放</span></button>
      </div>

      <div className="account-plan-list">
        {Object.values(BB_ACCOUNT_PLANS).filter(plan => plan.id !== 'pro').map(plan => (
          <button
            key={plan.id}
            className={`account-plan ${account.plan === plan.id ? 'current' : ''} ${selectedPlan === plan.id ? 'selected' : ''}`}
            onClick={() => {
              setSelectedPlan(plan.id);
              if (plan.id === 'free') {
                if (account.plan !== 'free') cancelSubscription();
                return;
              }
              startCheckout(plan.id);
            }}
          >
            <div>
              <strong>{plan.name}</strong>
              <span>{plan.description}</span>
            </div>
            <div className="account-plan-price">
              <b>{planPrice(plan, billing)}</b>
              <em>{plan.monthlyPrice ? planPeriodLabel(billing) : ''}</em>
              <small>每月 {plan.monthlyLimit} 次</small>
            </div>
            <i>{account.plan === plan.id ? '当前' : plan.badge}</i>
          </button>
        ))}
      </div>

      <div className="account-section">
        <div className="account-section-head">
          <strong>账单</strong>
          <span>{account.billingHistory?.length || 0} 条</span>
        </div>
        <div className="account-billing-list">
          {(account.billingHistory || []).length > 0 ? account.billingHistory.map(invoice => (
            <div className="account-billing-row" key={invoice.id || `${invoice.plan}-${invoice.at}`}>
              <div>
                <strong>{BB_ACCOUNT_PLANS[invoice.plan]?.name || invoice.plan}</strong>
                <span>{formatAccountDate(invoice.at)} · {invoice.billing === 'yearly' ? '年付' : '月付'}</span>
              </div>
              <div>
                <b>{invoice.amount}</b>
                {invoice.receipt_url ? <a href={invoice.receipt_url} target="_blank" rel="noreferrer">收据</a> : null}
                <em>{billingStatusLabel(invoice.status)}</em>
              </div>
            </div>
          )) : (
            <div className="account-empty">暂无账单。完成 Lemon Squeezy 支付并收到 webhook 后会显示记录。</div>
          )}
        </div>
      </div>

      {account.plan !== 'free' && (
        <div className="account-section">
          <div className="account-section-head">
            <strong>退款申请</strong>
            <span>{latestRefund ? billingStatusLabel(latestRefund.status) : '0-2 次可申请'}</span>
          </div>
          <p className="account-note">退款政策：当前周期累计使用 0-2 次可申请退款，使用 3 次及以上不退款。提交申请不代表退款完成，以状态显示“已退款”为准。</p>
          <label className="account-field">
            <span>申请原因</span>
            <input value={refundReason} onChange={e => setRefundReason(e.target.value)} placeholder="可选，方便管理员审核" />
          </label>
          {latestRefund && (
            <div className="account-receipt">
              最近申请：{billingStatusLabel(latestRefund.status)} · 当期已用 {latestRefund.usage_count || 0} 次
            </div>
          )}
          {refundMessage ? <div className="account-security-message">{refundMessage}</div> : null}
          <button className="btn btn-ghost account-submit" disabled={processing} onClick={requestRefund}>
            {processing ? '提交中...' : '申请退款'}
          </button>
        </div>
      )}
    </div>
  );

  const renderSecurity = () => (
    <div className="account-pane">
      <div className="account-section">
        <div className="account-section-head">
          <strong>修改密码</strong>
          <span>{authConfigured ? 'Supabase Auth' : '本地原型'}</span>
        </div>
        <label className="account-field">
          <span>当前密码</span>
          <input type="password" value={securityForm.current} onChange={e => setSecurityForm({ ...securityForm, current: e.target.value })} placeholder="输入当前密码" />
        </label>
        <label className="account-field">
          <span>新密码</span>
          <input type="password" value={securityForm.next} onChange={e => setSecurityForm({ ...securityForm, next: e.target.value })} placeholder="至少 6 位" />
        </label>
        <label className="account-field">
          <span>确认新密码</span>
          <input type="password" value={securityForm.confirm} onChange={e => setSecurityForm({ ...securityForm, confirm: e.target.value })} placeholder="再次输入新密码" />
        </label>
        {securityMessage && <div className="account-security-message">{securityMessage}</div>}
        <button className="btn btn-primary account-submit" onClick={changePassword}>更新密码</button>
      </div>

      <div className="account-section account-danger-zone">
        <div className="account-section-head">
          <strong>删除账号</strong>
          <span>危险操作</span>
        </div>
        <p>{authConfigured ? '删除会移除当前 Supabase Auth 用户，并清空该用户在 BitBuild 的订阅、账单、用量和任务归属数据。' : '删除会清空本地原型账号、订阅、账单和累计使用数据。'}</p>
        <button className="account-danger-btn" onClick={deleteAccount}>删除账号</button>
      </div>
    </div>
  );

  const renderCheckout = () => (
    <div className="account-pane account-checkout">
      <div className="account-order">
        <div>
          <span>BitBuild {selected.name}</span>
          <strong>{planPrice(BB_ACCOUNT_PLANS.plus, 'monthly')}/月</strong>
        </div>
        <p>每月 20 次 AI 工程审核额度，四种模式共用，支付成功后以 Lemon Squeezy webhook 确认为准。</p>
      </div>

      <label className="account-field">
        <span>账单邮箱</span>
        <input value={account.user?.email || ''} readOnly />
      </label>

      <div className="account-lemon-box">
        <div className="account-lemon-head">
          <span>Lemon Squeezy 正式支付</span>
          <b>安全结算</b>
        </div>
        <button className="account-lemon-pay" disabled={processing} onClick={completePayment}>
          {processing ? '正在创建订单...' : `前往安全支付 ${planPrice(BB_ACCOUNT_PLANS.plus, 'monthly')}`}
        </button>
      </div>

      <button className="account-back" onClick={() => setView('subscription')}>返回选择套餐</button>
    </div>
  );

  const renderSuccess = () => (
    <div className="account-pane account-success">
      <div className="account-success-icon"><Icon name="check" size={22} /></div>
      <h3>支付确认中</h3>
      <p>完成 Lemon Squeezy 支付后，系统会通过 webhook 自动更新套餐。</p>
      <button className="btn btn-primary account-submit" onClick={() => setView('overview')}>查看个人中心</button>
    </div>
  );

  const viewTitle = {
    login: '登录 BitBuild',
    register: '创建账号',
    overview: '个人中心',
    subscription: '订阅与额度',
    security: '安全设置',
    checkout: '确认订阅',
    success: '支付成功',
  }[view] || '账号';

  const viewSubtitle = {
    login: '登录后可保存订阅状态和每月额度。',
    register: '用邮箱或 Google 快速创建演示账号。',
    overview: '查看当前套餐、本月额度、累计使用次数和各模式分布。',
    subscription: '查看订阅周期、账单记录，选择或取消套餐。',
    security: '修改密码或删除本地原型账号。',
    checkout: '将跳转至 Lemon Squeezy 正式支付页面，确认付款后会真实扣款。',
    success: '支付状态将以 Lemon Squeezy Webhook 同步结果为准。',
  }[view] || '';

  return (
    <div className="account-backdrop" onClick={onClose}>
      <div className="account-modal" onClick={e => e.stopPropagation()}>
        <div className="account-head">
          <div className="account-head-icon"><Icon name={view === 'checkout' ? 'credit-card' : 'user-round'} size={18} /></div>
          <div>
            <div className="account-title">{viewTitle}</div>
            <div className="account-subtitle">{viewSubtitle}</div>
          </div>
          <button className="account-close" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        {isLoggedIn && view !== 'checkout' && view !== 'success' && (
          <div className="account-tabs">
            <button className={view === 'overview' ? 'active' : ''} onClick={() => setView('overview')}>概览</button>
            <button className={view === 'subscription' ? 'active' : ''} onClick={() => setView('subscription')}>订阅</button>
            <button className={view === 'security' ? 'active' : ''} onClick={() => setView('security')}>安全</button>
          </div>
        )}
        {view === 'login' && renderAuth('login')}
        {view === 'register' && renderAuth('register')}
        {view === 'overview' && renderOverview()}
        {view === 'subscription' && renderSubscription()}
        {view === 'security' && renderSecurity()}
        {view === 'checkout' && renderCheckout()}
        {view === 'success' && renderSuccess()}
      </div>
    </div>
  );
};

window.BB_ACCOUNT = {
  PLANS: BB_ACCOUNT_PLANS,
  MODES: BB_ACCOUNT_MODES,
  read: readAccount,
  save: saveAccount,
  normalize: normalizeAccount,
  usageView: accountUsageView,
  bumpUsage: bumpAccountUsage,
};
window.AccountModal = AccountModal;
