// Wallet — 學員/隊輔個人錢包＋投票卡
(() => {
const { Panel, Badge, Button, SectionTitle } = window.WCATalentGameDesignSystem_377d00;

const TXN_TYPE_LABEL = {
  game_win: "試煉勝",
  game_lose: "試煉敗",
  founding_out: "注資公司",
  liquidation_in: "清算入帳",
  admin_adjust: "控台調整",
};

function Wallet({ me }) {
  const [wallet, setWallet] = React.useState(null);
  const [voteData, setVoteData] = React.useState(null);
  const [selected, setSelected] = React.useState([]);
  const [phase, setPhase] = React.useState(null);
  const [voting, setVoting] = React.useState(false);
  const [voteMsg, setVoteMsg] = React.useState(null);

  const loadWallet = () => api("/api/wallet").then(setWallet).catch((e) => alert(e.message));
  const loadVotes = () => api("/api/votes/mine").then((d) => {
    setVoteData(d);
    setSelected(d.my_votes || []);
    setPhase(d.phase);
  }).catch(() => {});

  React.useEffect(() => {
    loadWallet();
    loadVotes();
    const t = setInterval(() => {
      api("/api/phase").then((d) => setPhase(d.phase)).catch(() => {});
    }, 10000);
    return () => clearInterval(t);
  }, []);

  if (!wallet) return <div style={{ color: "var(--text-muted)", padding: 40, textAlign: "center" }}>錢包開鎖中…</div>;

  if (wallet.hidden) {
    return (
      <div style={{ maxWidth: 520, margin: "0 auto" }}>
        <SectionTitle eyebrow="WALLET" align="left" size="h2" subtitle="個人 Token 帳戶">個人錢包</SectionTitle>
        <Panel>
          <div style={{ textAlign: "center", padding: "40px 20px" }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>🔒</div>
            <div style={{ fontSize: 18, color: "var(--gold-300)", fontWeight: 700, marginBottom: 8 }}>組隊階段暫不顯示</div>
            <div style={{ fontSize: 13, color: "var(--text-muted)" }}>{wallet.message || "先憑感覺找隊友！"}</div>
          </div>
        </Panel>
      </div>
    );
  }

  const toggleTeam = (id) => {
    if (selected.includes(id)) {
      setSelected(selected.filter((x) => x !== id));
    } else {
      if (voteData && selected.length >= Number(voteData.max_votes ?? 3)) return;
      setSelected([...selected, id]);
    }
  };

  const submitVote = async () => {
    setVoting(true);
    setVoteMsg(null);
    try {
      await api("/api/votes", { method: "POST", body: { team_ids: selected } });
      setVoteMsg({ ok: true, text: `已投票給 ${selected.length} 隊。` });
      loadVotes();
    } catch (e) {
      setVoteMsg({ ok: false, text: e.message });
    } finally {
      setVoting(false);
    }
  };

  const isBetWindow = phase === "bet_window";
  const maxVotes = voteData ? Number(voteData.max_votes ?? 3) : 3;

  return (
    <div style={{ maxWidth: 640, margin: "0 auto" }}>
      <SectionTitle eyebrow="WALLET" align="left" size="h2" subtitle="個人 Token 帳戶">個人錢包</SectionTitle>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 16, margin: "18px 0" }}>
        {/* 餘額大字 */}
        <Panel header="我的 Token">
          <div style={{ textAlign: "center", padding: "20px 0 10px" }}>
            <div style={{ fontFamily: '"Press Start 2P",monospace', fontSize: 32, color: "var(--gold-300)", lineHeight: 1.1 }}>
              {wallet.balance != null ? (wallet.balance / 10000).toLocaleString() : "—"}
            </div>
            <div style={{ color: "var(--text-muted)", fontSize: 12, marginTop: 6 }}>萬（遊戲 Token）</div>
          </div>
          <div style={{ fontSize: 12, color: "var(--text-muted)", textAlign: "center", marginTop: 4 }}>
            {me && me.display_name ? `@${me.display_name}` : ""}
          </div>
        </Panel>

        {/* 交易明細 */}
        <Panel header="交易明細">
          {wallet.txns && wallet.txns.length > 0 ? (
            <div style={{ maxHeight: 260, overflow: "auto" }}>
              {wallet.txns.map((t, i) => (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12, padding: "6px 2px", borderBottom: "1px solid rgba(212,175,55,.1)" }}>
                  <span style={{ color: "var(--text-secondary)", flex: 1 }}>{TXN_TYPE_LABEL[t.type] || t.type}</span>
                  <span style={{ color: "var(--text-muted)", fontSize: 11, marginRight: 8 }}>{(t.created_at || "").slice(5, 16)}</span>
                  <span style={{ color: t.amount >= 0 ? "var(--success,#7fc97f)" : "var(--danger,#e07a6a)", fontWeight: 700, minWidth: 48, textAlign: "right" }}>
                    {t.amount >= 0 ? "+" : ""}{(t.amount / 10000).toLocaleString()} 萬
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ color: "var(--text-muted)", fontSize: 13, padding: "10px 0" }}>尚無交易紀錄</div>
          )}
        </Panel>
      </div>

      {/* 投票卡：僅在 bet_window 且開放票數 > 0 顯示（人氣獎取消時 votes_per_person=0 整卡隱藏） */}
      {isBetWindow && voteData && maxVotes > 0 && (
        <Panel header={`投票卡（最多選 ${maxVotes} 隊，已選 ${selected.length}）`}>
          <div style={{ fontSize: 13, color: "var(--text-muted)", marginBottom: 12 }}>
            選出你認為最有潛力的創業隊（排除自己的隊）。可改票。
          </div>

          {voteMsg && (
            <div style={{ marginBottom: 12, padding: "10px 14px", borderRadius: 6, fontSize: 13,
              background: voteMsg.ok ? "rgba(127,201,127,.12)" : "rgba(224,122,106,.12)",
              color: voteMsg.ok ? "var(--success,#7fc97f)" : "var(--danger,#e07a6a)" }}>
              {voteMsg.text}
            </div>
          )}

          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 14 }}>
            {(voteData.teams || []).map((t) => {
              const sel = selected.includes(t.id);
              const disabled = !sel && selected.length >= maxVotes;
              return (
                <div key={t.id}
                  onClick={() => !disabled && toggleTeam(t.id)}
                  style={{
                    display: "flex", alignItems: "center", gap: 12, padding: "12px 16px", borderRadius: 8,
                    border: sel ? "2px solid var(--gold-400)" : "1px solid rgba(212,175,55,.25)",
                    background: sel ? "rgba(212,175,55,.15)" : "rgba(212,175,55,.04)",
                    cursor: disabled ? "not-allowed" : "pointer", opacity: disabled ? .5 : 1,
                    transition: "background .15s, border-color .15s",
                  }}>
                  <div style={{ width: 24, height: 24, borderRadius: "50%", border: sel ? "2px solid var(--gold-400)" : "2px solid rgba(212,175,55,.3)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                    {sel && <div style={{ width: 12, height: 12, borderRadius: "50%", background: "var(--gold-400)" }} />}
                  </div>
                  <span style={{ fontWeight: sel ? 700 : 400, color: sel ? "var(--gold-100,#f2ead2)" : "var(--text-primary)", fontSize: 15 }}>{t.name}</span>
                </div>
              );
            })}
          </div>

          <Button onClick={submitVote} disabled={voting || selected.length === 0}>
            {voting ? "送出中…" : `送出投票（${selected.length} 票）`}
          </Button>

          {voteData.my_votes && voteData.my_votes.length > 0 && (
            <div style={{ marginTop: 10, fontSize: 12, color: "var(--text-muted)" }}>
              上次提交：{(voteData.teams || []).filter((t) => voteData.my_votes.includes(t.id)).map((t) => t.name).join("、")}
            </div>
          )}
        </Panel>
      )}

      {!isBetWindow && (
        <div style={{ margin: "16px 0", padding: "10px 14px", background: "rgba(212,175,55,.06)", borderRadius: 8, fontSize: 12, color: "var(--text-muted)" }}>
          投票卡將在 WCAX 認購階段開放。
        </div>
      )}
    </div>
  );
}

window.Wallet = Wallet;
})();
