const { useState } = React;
const { Icon, ProtoNav, StateSwitcher, Topbar, Sidebar, Footer, USER_STATES, showToast } = window;

// 6 态主推卡片配置（page-designs §2.7.1 + component-specs §3.1）
const CARD_STATES = {
  REGISTERED: {
    tag: { text: "体验用户", tone: "info" },
    bannerGradient: "linear-gradient(120deg, #0085D0 0%, #1A91D5 100%)",
    balanceLabel: "营销金余额", balanceNum: "$0.00", balanceMuted: true,
    voucherLabel: null,
    entitlement: { tone: "", title: "当前权益：页面体验（无 API Key）", items: ["浏览模型广场与活动", "提交企业信息可领取 $20 + 固定 Key"] },
    cta: { primary: { text: "提交企业信息", icon: Icon.File }, secondary: null },
    progress: { active: 0, status: "注册完成，请提交企业信息" },
    apikey: { locked: true, lockedText: "提交企业信息并通过 DICT 审核后，系统将分配固定 API Key" },
  },
  LEAD_APPLIED: {
    tag: { text: "资料审核中", tone: "info" },
    bannerGradient: "linear-gradient(120deg, #F49800 0%, #0085D0 120%)",
    balanceLabel: "营销金余额", balanceNum: "$0.00", balanceMuted: true,
    voucherLabel: null,
    entitlement: { tone: "warning", title: "当前权益：页面受限", items: ["三个并行审核进行中：DICT / EB / iBOSS", "任一未完成均显示「资料审核中」", "审核通过后自动发放对应额度"] },
    cta: { primary: null, secondary: { text: "查看进度", icon: Icon.Clock } },
    progress: { active: 1, status: "资料审核中 · 等待 DICT、EB、iBOSS 并行审核完成" },
    apikey: { locked: true, lockedText: "审核通过后将分配固定 API Key" },
  },
  LEAD_APPROVED: {
    tag: { text: "试用中", tone: "info" },
    bannerGradient: "linear-gradient(120deg, #8EC31E 0%, #0085D0 120%)",
    balanceLabel: "营销金余额", balanceNum: "$20.00", balanceMuted: false,
    voucherLabel: null,
    balanceMeta: "还剩 30 天",
    entitlement: { tone: "success", title: "当前权益：页面体验 + 固定 API Key", items: ["$20 营销金已到账（30 天有效）", "1 个系统固定 Key，可调用模型", "等待 EB 审批追加 $180"] },
    cta: { primary: { text: "开始模型体验", icon: Icon.Robot }, secondary: null },
    progress: { active: 1, status: "DICT 审核通过 · 下一步等待 EB 审批追加 $180" },
    apikey: { locked: false, name: "系统固定 Key", value: "sk-llm2026-8f3a9c2e1b7d4e6f0a2c5b8d" },
  },
  EB_APPROVED: {
    tag: { text: "试用中", tone: "info" },
    bannerGradient: "linear-gradient(120deg, #0098AD 0%, #0085D0 100%)",
    balanceLabel: "营销金余额", balanceNum: "$200.00", balanceMuted: false,
    voucherLabel: null,
    balanceMeta: "还剩 30 天（$180 已追加）",
    entitlement: { tone: "", title: "当前权益：页面体验 + 固定 API Key", items: ["累计 $200（$20 + $180 追加）", "1 个固定 Key，同一 Key 追加额度", "等待 iBOSS 企业认证完成"] },
    cta: { primary: { text: "去完成企业认证", icon: Icon.Building }, secondary: { text: "复制 Key", icon: Icon.Copy } },
    progress: { active: 2, status: "EB 审批通过 · 下一步完成 iBOSS 认证，领取 $800 抵扣券资格" },
    apikey: { locked: false, name: "系统固定 Key", value: "sk-llm2026-8f3a9c2e1b7d4e6f0a2c5b8d" },
  },
  VERIFIED: {
    tag: { text: "待订购", tone: "warning" },
    bannerGradient: "linear-gradient(120deg, #F49800 0%, #A6165F 130%)",
    balanceLabel: "营销金余额", balanceNum: "$200.00", balanceMuted: false,
    voucherLabel: "AI Hub 抵扣券资格", voucherNum: "$800.00", voucherTone: "success",
    balanceMeta: "还剩 30 天",
    entitlement: { tone: "warning", title: "认证已通过，订购 AI Hub 领取 $800 抵扣券", items: ["$800 抵扣券由 AI Hub 在订购时生成", "订购时默认勾选，首月结算抵扣", "1 个月有效（可配置）"] },
    cta: { primary: { text: "去订购 AI Hub", icon: Icon.External }, secondary: { text: "复制 Key", icon: Icon.Copy } },
    progress: { active: 3, status: "已通过（待订购）· 完成订购 AI Hub 激活完整服务" },
    apikey: { locked: false, name: "系统固定 Key", value: "sk-llm2026-8f3a9c2e1b7d4e6f0a2c5b8d" },
  },
  SUBSCRIBED: {
    tag: { text: "已订购", tone: "success" },
    bannerGradient: "linear-gradient(120deg, #8EC31E 0%, #0098AD 100%)",
    balanceLabel: "营销金余额", balanceNum: "$200.00", balanceMuted: false,
    voucherLabel: null,
    balanceMeta: "还剩 30 天 · iBOSS 计费",
    entitlement: { tone: "success", title: "完整服务已激活", items: ["页面体验 · 自行创建/管理 API Key", "智算云服务可用", "AI Hub 首月抵扣券已生效"] },
    cta: { primary: { text: "管理 API Key", icon: Icon.Key }, secondary: { text: "充值", icon: Icon.Wallet, ghost: true } },
    progress: { active: 4, status: "已完成 · 全流程结束", done: true },
    apikey: { locked: false, manageable: true, name: "系统固定 Key", value: "sk-llm2026-8f3a9c2e1b7d4e6f0a2c5b8d", extra: [{ name: "生产环境 Key", value: "sk-prod-a1b2c3d4e5f6a7b8c9d0e1f2a3b4" }] },
  },
  ELIGIBLE: {
    tag: { text: "有资格", tone: "success" },
    bannerGradient: "linear-gradient(120deg, #8EC31E 0%, #0098AD 100%)",
    balanceLabel: null, balanceNum: null, balanceMuted: false,
    voucherLabel: "AI Hub 首月抵扣券资格", voucherNum: "$1000.00", voucherTone: "success",
    balanceMeta: null,
    entitlement: { tone: "success", title: "企业认证已通过，具备订购资格", items: ["$1000 首月抵扣券资格已就绪", "订购 AI Hub 时自动抵扣", "请联系销售确认订购方案"] },
    cta: { primary: { text: "去订购 AI Hub", icon: Icon.External }, secondary: null },
    progress: { active: 3, status: "企业认证已通过，具备订购资格 · 点击订购 AI Hub" },
    apikey: { locked: true, lockedText: "订购 AI Hub 后系统将分配 API Key" },
  },
  INELIGIBLE: {
    tag: { text: "无资格", tone: "neutral" },
    bannerGradient: "linear-gradient(120deg, #8EC31E 0%, #0098AD 100%)",
    balanceLabel: null, balanceNum: null, balanceMuted: false,
    voucherLabel: "AI Hub 首月抵扣券资格", voucherNum: "$1000.00", voucherTone: "success",
    balanceMeta: null,
    entitlement: { tone: "success", title: "企业认证已通过，具备订购资格", items: ["$1000 首月抵扣券资格已就绪", "订购 AI Hub 时自动抵扣", "请联系销售确认订购方案"] },
    cta: { primary: { text: "去订购 AI Hub", icon: Icon.External }, secondary: null },
    progress: { active: 3, status: "企业认证已通过，具备订购资格 · 点击订购 AI Hub" },
    apikey: { locked: true, lockedText: "订购 AI Hub 后系统将分配 API Key" },
  },
};

const PROGRESS_STEPS = ["注册", "DICT 审核", "EB 审批", "认证完成", "订购激活"];

function BalanceBlock({ s }) {
  // 存量 VERIFIED 态不显示余额，仅显示抵扣券
  const isLegacy = s.balanceLabel === null && s.balanceNum === null;
  return (
    <div className="balance-block">
      {!isLegacy && (
        <div className={"balance-item balance-item--primary"}>
          <span className="balance-label"><Icon.Wallet size={14} /> {s.balanceLabel}</span>
          <span className={"balance-num" + (s.balanceMuted ? " balance-num--muted" : "")}>{s.balanceNum}</span>
          {s.balanceMeta && <span className="balance-meta"><Icon.Clock size={12} /> {s.balanceMeta}</span>}
        </div>
      )}
      {s.voucherLabel ? (
        <div className={"balance-item" + (isLegacy ? " balance-item--primary" : " balance-item--accent")}>
          <span className="balance-label"><Icon.Gift size={14} /> {s.voucherLabel}</span>
          <span className="balance-num balance-num--success">{s.voucherNum}</span>
          <span className="balance-meta"><Icon.Sparkles size={12} /> 订购 AI Hub 时生成</span>
        </div>
      ) : (!isLegacy && (
        <div className="balance-item">
          <span className="balance-label"><Icon.TrendingUp size={14} /> 累计获得</span>
          <span className="balance-num">{s.balanceNum === "$0.00" ? "$0.00" : s.balanceNum}</span>
          <span className="balance-meta">三层递进体系</span>
        </div>
      ))}
    </div>
  );
}

function ProgressBar({ s }) {
  return (
    <div className="progress-block">
      <h4 className="progress-block-title">申请进度</h4>
      <div className="steps">
        {PROGRESS_STEPS.map((label, i) => {
          let st = "todo";
          if (s.progress.done) st = "done";
          else if (i < s.progress.active) st = "done";
          else if (i === s.progress.active) st = "active";
          return (
            <div className={"step step--" + st} key={label}>
              <span className="step-dot">
                {st === "done" && !s.progress.done ? <Icon.Check size={12} /> : st === "done" && s.progress.done ? <Icon.Check size={12} /> : i + 1}
              </span>
              <span className="step-label">{label}</span>
            </div>
          );
        })}
      </div>
      <p className="progress-block-note">{s.progress.status}</p>
    </div>
  );
}

function ApiKeyBlock({ s }) {
  if (s.apikey.locked) {
    return (
      <div className="apikey-block">
        <h4 className="apikey-block-title"><Icon.Key size={16} /> API Key</h4>
        <div className="apikey-locked"><Icon.Info size={16} /> {s.apikey.lockedText}</div>
      </div>
    );
  }
  const keys = [s.apikey, ...(s.apikey.extra || [])];
  return (
    <div className="apikey-block">
      <h4 className="apikey-block-title">
        <Icon.Key size={16} /> API Key {s.apikey.manageable && <span className="tag tag--neutral" style={{ marginLeft: 8 }}>可新建</span>}
      </h4>
      {keys.map((k, i) => (
        <div className="apikey-row" key={i} style={{ marginBottom: 8 }}>
          <span className="apikey-name">{k.name}</span>
          <span className="apikey-value">{k.value}</span>
          <button className="btn btn--secondary btn--sm apikey-copy"><Icon.Copy size={14} /> 复制</button>
        </div>
      ))}
      <p className="apikey-hint">{s.apikey.manageable ? "已完成订购，可在 AI Hub 新建多个 Key" : "试用阶段仅 1 个固定 Key，订购后可新建"}</p>
      {s.apikey.manageable && <button className="btn btn--outline btn--sm" style={{ marginTop: 8 }}><Icon.Key size={14} /> + 新建 API Key</button>}
    </div>
  );
}

function CampaignCard({ state }) {
  const s = CARD_STATES[state];
  return (
    <div className="campaign-card" data-screen-label={"campaign-card-" + state}>
      <div className="campaign-card-banner" style={{ background: s.bannerGradient }}>
        <div className="campaign-card-title-row">
          <h2 className="campaign-card-title">2026大模型拉新促销</h2>
        </div>
        <div className="campaign-card-tag-row">
          <span className={"tag tag--lg tag--" + s.tag.tone}><span className="tag-dot" /> {s.tag.text}</span>
        </div>
      </div>
      <div className="campaign-card-body">
        <BalanceBlock s={s} />

        <div className={"entitlement" + (s.entitlement.tone ? " entitlement--" + s.entitlement.tone : "")}>
          <strong>{s.entitlement.title}</strong>
          <ul>{s.entitlement.items.map((it, i) => <li key={i}>{it}</li>)}</ul>
        </div>

        <div className="card-cta-row">
          {s.cta.primary && (
            <button className={"btn btn--lg btn--" + (s.cta.primary.ghost ? "ghost" : "primary")} onClick={() => {
              if (state === "ELIGIBLE" || state === "VERIFIED") {
                // 新标签页跳转 AI Hub 订购页
                window.open("https://aihub.cmi.chinamobile.com/order?ref=marketing", "_blank");
              } else if (state === "INELIGIBLE") {
                showToast("您当前账号无领取资格，请联系企业主账号管理员", "warning");
              }
            }}>
              <s.cta.primary.icon size={18} /> {s.cta.primary.text}
            </button>
          )}
          {s.cta.secondary && (
            <button className={"btn btn--lg btn--" + (s.cta.secondary.ghost ? "ghost" : "secondary")}>
              <s.cta.secondary.icon size={16} /> {s.cta.secondary.text}
            </button>
          )}
        </div>

        <ProgressBar s={s} />
        <ApiKeyBlock s={s} />
      </div>
    </div>
  );
}

// 权益领取历史 mock
const BENEFIT_HISTORY = [
  { time: "2026-06-15 14:30", campaign: "2026大模型拉新促销", type: "营销金", amount: "$20.00" },
  { time: "2026-06-10 09:15", campaign: "2026大模型拉新促销", type: "追加", amount: "$180.00" },
  { time: "2026-05-28 16:45", campaign: "MCP 服务试用", type: "体验金", amount: "$50.00" },
  { time: "2026-05-20 11:20", campaign: "智算云弹性试用", type: "体验金", amount: "$150.00" },
  { time: "2026-04-18 08:30", campaign: "视频生成模型内测", type: "体验金", amount: "$100.00" },
  { time: "2026-03-10 10:00", campaign: "文生图促销活动", type: "营销金", amount: "$80.00" },
  { time: "2026-02-25 14:30", campaign: "2025 年末大促", type: "营销金", amount: "$50.00" },
  { time: "2026-01-15 09:00", campaign: "新春活动", type: "抵扣券", amount: "$200.00" },
];

// 近期营销活动 mock
const RECENT_CAMPAIGNS = [
  { name: "2026大模型拉新促销", desc: "提交资料并通过审核，最高领取 $1000 AI Hub 抵扣券", cta: "立即参与", href: "campaign-landing.html" },
  { name: "MCP 服务试用", desc: "MCP 工具调用免费额度，无需审批，按需领取", cta: "立即领取", href: "#" },
  { name: "智算云弹性试用", desc: "GPU 训练/推理资源，新用户专享 $150 试用金", cta: "立即体验", href: "#" },
  { name: "视频生成模型内测", desc: "文生视频能力抢先体验，限量 1000 名", cta: "申请内测", href: "#" },
];

function BenefitHistory() {
  return (
    <section className="history-section" data-region="benefits-history">
      <div className="history-section-header">
        <h3 className="history-section-title"><Icon.Clock size={18} /> 权益领取历史</h3>
        <span className="tag tag--neutral">最近 20 条</span>
      </div>
      <div className="history-table-wrap">
        <table className="history-table">
          <thead>
            <tr>
              <th>时间</th><th>活动名称</th><th>类型</th><th>金额</th>
            </tr>
          </thead>
          <tbody>
            {BENEFIT_HISTORY.map((h, i) => (
              <tr key={i}>
                <td>{h.time}</td>
                <td>{h.campaign}</td>
                <td><span className={"tag tag--" + (h.type === "追加" ? "success" : h.type === "抵扣券" ? "warning" : "info")}>{h.type}</span></td>
                <td className="history-amount">{h.amount}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

function RecentCampaigns() {
  return (
    <section className="recent-section" data-region="benefits-recent">
      <div className="recent-section-header">
        <h3 className="recent-section-title"><Icon.Sparkles size={18} /> 近期营销活动</h3>
      </div>
      <div className="recent-list">
        {RECENT_CAMPAIGNS.map((c, i) => (
          <div className="recent-item" key={i}>
            <div className="recent-item-main">
              <span className="recent-item-name">{c.name}</span>
              <span className="recent-item-desc">{c.desc}</span>
            </div>
            <a className="btn btn--secondary btn--sm" href={c.href}>{c.cta}</a>
          </div>
        ))}
      </div>
    </section>
  );
}

// 多活动网格 mock（page-designs §2.7.2 mock 数据 5 个活动）
const PAST_CAMPAIGNS = [
  { name: "智算云弹性试用", status: "已通过", tone: "success", icon: Icon.Cloud, iconTone: "success", balance: "$150.00", expiry: "2026-09-15", desc: "GPU 训练/推理服务", cta: "前往智算云", progress: [2,2] },
  { name: "MCP 服务试用", status: "审核中", tone: "warning", icon: Icon.Cpu, iconTone: "info", balance: "$50.00", expiry: "2026-07-30", desc: "试用申请已提交，等待 EB 审批", cta: "查看详情", progress: [1,2] },
  { name: "视频生成模型内测", status: "未参与", tone: "neutral", icon: Icon.Robot, iconTone: "warning", balance: "$100", expiry: "90 天", desc: "可获得营销体验金", cta: "立即参与", progress: null },
  { name: "文生图促销活动", status: "已过期", tone: "neutral", icon: Icon.Sparkles, iconTone: "neutral", balance: "$0", expiry: "已结束", desc: "余额已回收，曾获 $80 体验金", cta: "查看历史", progress: null, expired: true },
];

function PastCard({ c }) {
  return (
    <div className={"past-card" + (c.expired ? " past-card--expired" : "")}>
      <div className="past-card-header">
        <span className={"past-card-icon past-card-icon--" + c.iconTone}><c.icon size={22} /></span>
        <span className={"tag tag--" + c.tone}>{c.status}</span>
      </div>
      <h3 className="past-card-name">{c.name}</h3>
      <div>
        <span className={"past-card-balance" + (c.expired ? " past-card-balance--muted" : "")}>{c.balance}</span>
      </div>
      <div className="past-card-meta">
        <span className="past-card-meta-row"><Icon.Clock size={12} /> 有效期 {c.expiry}</span>
        <span className="past-card-meta-row">{c.desc}</span>
      </div>
      <button className={"btn btn--sm " + (c.expired ? "btn--ghost" : "btn--secondary") + " past-card-cta"}>{c.cta}</button>
    </div>
  );
}

function StateBanner({ state }) {
  const map = {
    REGISTERED: { tone: "", icon: Icon.Info, title: "体验用户", desc: "提交企业信息即可领取 $20 营销金 + 固定 API Key" },
    LEAD_APPLIED: { tone: "warning", icon: Icon.Clock, title: "资料审核中", desc: "DICT / EB / iBOSS 三个并行审核进行中，任一未完成均显示审核中" },
    LEAD_APPROVED: { tone: "success", icon: Icon.Wallet, title: "DICT 审核通过", desc: "$20 已到账，等待 EB 审批追加 $180（累计 $200）" },
    EB_APPROVED: { tone: "", icon: Icon.Wallet, title: "EB 审批通过", desc: "累计 $200 已到账，继续完成 iBOSS 认证领取 $800 抵扣券资格" },
    VERIFIED: { tone: "warning", icon: Icon.Gift, title: "认证通过 · 待订购", desc: "订购 AI Hub 即可领取 $800 首月抵扣券" },
    SUBSCRIBED: { tone: "success", icon: Icon.Check, title: "已订购 · 完整服务", desc: "全流程已完成，可自行管理 API Key 与使用智算云" },
    ELIGIBLE: { tone: "success", icon: Icon.Check, title: "企业认证已通过 · 有领取资格", desc: "您具备 $1000 AI Hub 首月抵扣券资格，点击下方按钮前往订购" },
    INELIGIBLE: { tone: "success", icon: Icon.Check, title: "企业认证已通过", desc: "您的企业已完成认证。如需领取权益，请联系企业主账号管理员" },
  };
  const c = map[state]; if (!c) return null;
  return (
    <div className={"state-banner" + (c.tone ? " state-banner--" + c.tone : "")}>
      <span className="state-banner-icon"><c.icon size={20} /></span>
      <div className="state-banner-text">
        <p className="state-banner-title">{c.title}</p>
        <p className="state-banner-desc">{c.desc}</p>
      </div>
    </div>
  );
}

function App() {
  const [state, setState] = useState("REGISTERED");
  const balance = {
    REGISTERED: 0, LEAD_APPLIED: 0, LEAD_APPROVED: 20, EB_APPROVED: 200,
    VERIFIED: 200, SUBSCRIBED: 200, ELIGIBLE: null, INELIGIBLE: null,
  }[state];
  return (
    <div className="proto-root">
      <ProtoNav active="benefits" />
      <StateSwitcher states={USER_STATES.filter(s => s.key !== "GUEST")} active={state} onChange={setState} title="用户状态 → 卡片切换" variant="top-collapsible" />
      <div className="app-shell">
        <Sidebar active="benefits" />
        <div className="app-main">
          <Topbar crumbs={[{ label: "首页", href: "marketing-home.html" }, { label: "我的权益" }]} state={state} balance={balance} />
          <main className="app-content benefits-content" data-screen-label="benefits">
            <div className="benefits-container">
              <div className="benefits-header">
                <h1 className="benefits-title">我的权益</h1>
                <p className="benefits-sub">营销活动聚合 · 权益卡片 · API Key · 抵扣券</p>
              </div>

              <StateBanner state={state} />

              <section data-region="benefits-main">
                <CampaignCard state={state} />
              </section>

              <BenefitHistory />

              <RecentCampaigns />

              <section className="past-section" data-region="benefits-past">
                <div className="past-section-header">
                  <h3 className="past-section-title">往期有效营销</h3>
                  <span className="tag tag--neutral">共 {PAST_CAMPAIGNS.length} 个活动</span>
                </div>
                <div className="past-grid">
                  {PAST_CAMPAIGNS.map(c => <PastCard key={c.name} c={c} />)}
                </div>
              </section>
            </div>
          </main>
          <Footer variant="standard" />
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
