// Invest — 導師/評審/觀眾投資下單
(() => {
const { Panel, Badge, Button, SectionTitle } = window.WCATalentGameDesignSystem_377d00;

const inputStyle = {
  background: "var(--navy-950)", border: "1px solid rgba(212,175,55,.28)", borderRadius: 6,
  color: "var(--text-primary)", padding: "8px 10px", fontSize: 13, outline: "none", boxSizing: "border-box",
};

const INVESTOR_LABEL = { mentor: "導師", sponsor: "企業評審", audience: "專業觀眾" };

function Invest({ me }) {
  const [data, setData] = React.useState(null);
  const [phase, setPhase] = React.useState(null);
  const [form, setForm] = React.useState({ team_id: "", amount: 0, round: "pre_a" });
  const [submitting, setSubmitting] = React.useState(false);
  const [msg, setMsg] = React.useState(null);

  const load = () => api("/api/invest/quota").then((d) => {
    setData(d);
    setPhase(d.phase);
    // 自動判斷 round
    const autoRound = d.phase === "pre_a" ? "pre_a" : "a_round";
    setForm((f) => ({ ...f, round: autoRound, amount: d.unit || 0 }));
  }).catch((e) => alert(e.message));

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

  if (!data) return <div style={{ color: "var(--text-muted)", padding: 40, textAlign: "center" }}>載入中…</div>;

  const unit = data.unit || 1;
  const canOrder = ["pre_a", "pitch", "bet_window"].includes(phase);

  const stepAmount = (delta) => {
    setForm((f) => ({ ...f, amount: Math.max(unit, (f.amount || unit) + delta * unit) }));
  };

  const submitOrder = async () => {
    if (!form.team_id) { setMsg({ ok: false, text: "請選擇隊伍" }); return; }
    setSubmitting(true);
    setMsg(null);
    try {
      await api("/api/invest", { method: "POST", body: { team_id: Number(form.team_id), amount: form.amount, round: form.round } });
      setMsg({ ok: true, text: "下單成功！" });
      load();
    } catch (e) {
      setMsg({ ok: false, text: e.message });
    } finally {
      setSubmitting(false);
    }
  };

  const cancelOrder = async (id) => {
    if (!confirm("確定作廢此筆下單？資金將退回公司帳戶。")) return;
    try {
      await api(`/api/invest/${id}`, { method: "DELETE" });
      setMsg({ ok: true, text: "下單已作廢。" });
      load();
    } catch (e) {
      setMsg({ ok: false, text: e.message });
    }
  };

  const caps = data.caps || {};
  const spent = data.spent || {};
  const orders = data.orders || [];
  const teams = data.teams || [];

  return (
    <div style={{ maxWidth: 720, margin: "0 auto" }}>
      <SectionTitle eyebrow="INVESTOR" align="left" size="h2" subtitle="投資下單">
        投資管理台
      </SectionTitle>

      {!canOrder && (
        <div style={{ margin: "14px 0", padding: "12px 16px", background: "rgba(224,122,106,.12)", borderRadius: 8, color: "var(--danger,#e07a6a)", fontSize: 13 }}>
          目前階段不開放投資下單（僅 Pre-A / Pitch / 認購窗口期開放）。
        </div>
      )}

      {msg && (
        <div style={{ margin: "14px 0", padding: "12px 16px", borderRadius: 8, fontSize: 13,
          background: msg.ok ? "rgba(127,201,127,.12)" : "rgba(224,122,106,.12)",
          color: msg.ok ? "var(--success,#7fc97f)" : "var(--danger,#e07a6a)" }}>
          {msg.text}
          <span onClick={() => setMsg(null)} style={{ float: "right", cursor: "pointer", opacity: .6 }}>✕</span>
        </div>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16, margin: "18px 0" }}>
        {/* 身份與額度 */}
        <Panel header="我的投資身分與額度">
          <div style={{ marginBottom: 12 }}>
            <Badge tone="gold" size="md">{INVESTOR_LABEL[data.investor_type] || data.investor_type}</Badge>
          </div>
          <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>單位金額</div>
          <div style={{ fontSize: 20, color: "var(--gold-300)", fontWeight: 700, marginBottom: 14 }}>
            {unit >= 10000 ? (unit / 10000).toFixed(unit % 10000 === 0 ? 0 : 1) + " 萬" : unit.toLocaleString()} 元
          </div>
          {Object.entries(caps).map(([rnd, cap]) => {
            const s = spent[rnd] || 0;
            return (
              <div key={rnd} style={{ marginBottom: 10 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-muted)", marginBottom: 3 }}>
                  <span>{rnd === "pre_a" ? "Pre-A" : "A 輪"} 額度</span>
                  <span style={{ color: "var(--text-secondary)" }}>{s.toLocaleString()} / {cap.toLocaleString()} 元</span>
                </div>
                <div style={{ height: 6, borderRadius: 3, background: "rgba(212,175,55,.15)", overflow: "hidden" }}>
                  <div style={{ height: "100%", borderRadius: 3, background: cap > 0 && s >= cap ? "var(--danger,#e07a6a)" : "var(--gold-400)", width: cap > 0 ? Math.min(100, Math.round(s / cap * 100)) + "%" : "0%" }} />
                </div>
              </div>
            );
          })}
        </Panel>

        {/* 下單表單 */}
        <Panel header="新增投資">
          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>選擇隊伍</div>
            <select
              style={{ ...inputStyle, width: "100%" }}
              value={form.team_id}
              onChange={(e) => setForm({ ...form, team_id: e.target.value })}>
              <option value="">— 選隊伍 —</option>
              {teams.map((t) => (
                <option key={t.id} value={t.id}>{t.name}{t.is_own ? "（輔導隊）" : ""}</option>
              ))}
            </select>
          </div>
          <div style={{ marginBottom: 10 }}>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>輪別</div>
            <select
              style={{ ...inputStyle, width: "100%" }}
              value={form.round}
              onChange={(e) => setForm({ ...form, round: e.target.value })}
              disabled={phase === "pre_a"}>
              <option value="pre_a">Pre-A</option>
              <option value="a_round">A 輪</option>
            </select>
            {phase === "pre_a" && <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 3 }}>目前為 Pre-A 階段，已自動選定</div>}
          </div>
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 4 }}>金額（{unit >= 10000 ? unit / 10000 + " 萬" : unit} 元／單位）</div>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <button onClick={() => stepAmount(-1)} style={{ ...inputStyle, width: 40, textAlign: "center", cursor: "pointer", padding: "8px 0", fontSize: 18 }}>－</button>
              <div style={{ flex: 1, ...inputStyle, textAlign: "center", fontWeight: 700, fontSize: 16 }}>
                {form.amount >= 10000 ? (form.amount / 10000).toFixed(form.amount % 10000 === 0 ? 0 : 2) + " 萬" : form.amount.toLocaleString()} 元
              </div>
              <button onClick={() => stepAmount(1)} style={{ ...inputStyle, width: 40, textAlign: "center", cursor: "pointer", padding: "8px 0", fontSize: 18 }}>＋</button>
            </div>
          </div>
          <Button onClick={submitOrder} disabled={!canOrder || submitting}>
            {submitting ? "送出中…" : "確認下單"}
          </Button>
        </Panel>
      </div>

      {/* 有效下單清單 */}
      <Panel header={`我的有效下單（${orders.length}）`}>
        {orders.length === 0 ? (
          <div style={{ color: "var(--text-muted)", fontSize: 13, padding: "8px 0" }}>尚無下單</div>
        ) : (
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, minWidth: 360 }}>
              <thead>
                <tr style={{ color: "var(--gold-300)", textAlign: "left" }}>
                  {["隊伍", "輪別", "金額", "動作"].map((h) => (
                    <th key={h} style={{ padding: "6px 8px", borderBottom: "1px solid rgba(212,175,55,.25)" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {orders.map((o) => {
                  const t = teams.find((x) => x.id === o.team_id);
                  return (
                    <tr key={o.id} style={{ borderBottom: "1px solid rgba(212,175,55,.1)", color: "var(--text-secondary)" }}>
                      <td style={{ padding: "8px" }}>
                        {t ? t.name : o.team_id}
                        {t && t.is_own && <Badge tone="info" size="sm" style={{ marginLeft: 6 }}>輔導隊</Badge>}
                      </td>
                      <td style={{ padding: "8px" }}>{o.round === "pre_a" ? "Pre-A" : "A 輪"}</td>
                      <td style={{ padding: "8px", color: "var(--gold-300)", fontWeight: 700 }}>
                        {o.amount >= 10000 ? (o.amount / 10000).toFixed(o.amount % 10000 === 0 ? 0 : 1) + " 萬" : o.amount.toLocaleString()} 元
                      </td>
                      <td style={{ padding: "8px" }}>
                        {canOrder
                          ? <Button size="sm" variant="ghost" onClick={() => cancelOrder(o.id)}>作廢</Button>
                          : <span style={{ fontSize: 12, color: "var(--text-muted)" }}>截止</span>}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </Panel>

      {/* 隊伍卡清單 */}
      <div style={{ marginTop: 16 }}>
        <Panel header="創業隊一覽">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 10 }}>
            {teams.map((t) => (
              <div key={t.id} style={{ padding: "12px 14px", borderRadius: 8, border: "1px solid rgba(212,175,55,.2)", background: "rgba(212,175,55,.04)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                  <span style={{ fontWeight: 700, color: "var(--gold-100,#f2ead2)", fontSize: 14 }}>{t.name}</span>
                  {t.is_own && <Badge tone="info" size="sm">輔導隊</Badge>}
                </div>
                {t.sponsor_topic && (
                  <div style={{ fontSize: 11, color: "var(--text-muted)" }}>{t.sponsor_topic}</div>
                )}
              </div>
            ))}
          </div>
        </Panel>
      </div>
    </div>
  );
}

window.Invest = Invest;
})();
