// Company — 公司帳戶與股權（學員/隊輔可看）
(() => {
const { Panel, Badge, Button, ProgressBar, SectionTitle } = window.WCATalentGameDesignSystem_377d00;

const TYPE_LABEL = {
  founding_in:     "創始注資",
  angel_in:        "天使注資",
  pre_a_in:        "Pre-A",
  a_round_in:      "A輪",
  ai_spend:        "營運支出",
  bet_out:         "WCAX押注",
  bet_payout:      "WCAX配發",
  ma_merge:        "併購移轉",
  liquidation_out: "清算出帳",
  admin_adjust:    "控台調整",
};

// ── SVG 圓餅圖 ────────────────────────────────────────────────
// 金色系深淺色板：最多 8 段
const PIE_COLORS = [
  "#D4AF37", "#A07820", "#F2D96B", "#7A5C10",
  "#E8C84A", "#5A420A", "#C9A030", "#F8E9A0",
];

function polarToXY(cx, cy, r, angleDeg) {
  const rad = (angleDeg - 90) * (Math.PI / 180);
  return {
    x: cx + r * Math.cos(rad),
    y: cy + r * Math.sin(rad),
  };
}

function pieSlicePath(cx, cy, r, startDeg, endDeg) {
  if (Math.abs(endDeg - startDeg) >= 359.99) {
    // 全圓：畫兩個半圓
    const top = polarToXY(cx, cy, r, 0);
    const bot = polarToXY(cx, cy, r, 180);
    return `M ${top.x} ${top.y} A ${r} ${r} 0 1 1 ${bot.x} ${bot.y} A ${r} ${r} 0 1 1 ${top.x} ${top.y} Z`;
  }
  const largeArc = (endDeg - startDeg) > 180 ? 1 : 0;
  const s = polarToXY(cx, cy, r, startDeg);
  const e = polarToXY(cx, cy, r, endDeg);
  return `M ${cx} ${cy} L ${s.x} ${s.y} A ${r} ${r} 0 ${largeArc} 1 ${e.x} ${e.y} Z`;
}

function PieChart({ entries }) {
  if (!entries || entries.length === 0) {
    return <div style={{ color: "var(--text-muted)", fontSize: 13, padding: "12px 0" }}>尚無股權資料</div>;
  }
  const cx = 90, cy = 90, r = 80;
  let cursor = 0;
  const slices = entries.map((en, i) => {
    const deg = (en.pct / 100) * 360;
    const start = cursor;
    const end = cursor + deg;
    cursor = end;
    return { ...en, start, end, color: PIE_COLORS[i % PIE_COLORS.length] };
  });

  const POSITION_LABEL = {
    CEO: "執行長", CPO: "產品長", CBO: "商務長",
    COO: "營運長", CFO: "財務長", CMO: "行銷長", CTO: "技術長",
  };

  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 20, alignItems: "flex-start" }}>
      <svg width={180} height={180} viewBox="0 0 180 180" style={{ flexShrink: 0 }}>
        {slices.map((s, i) => (
          <path key={i} d={pieSlicePath(cx, cy, r, s.start, s.end)}
            fill={s.color} stroke="var(--navy-950)" strokeWidth={1.5} />
        ))}
      </svg>
      <div style={{ flex: 1, minWidth: 160 }}>
        {slices.map((s, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 7 }}>
            <span style={{ width: 12, height: 12, borderRadius: 2, background: s.color, flexShrink: 0, display: "inline-block" }} />
            <span style={{ fontSize: 13, color: "var(--text-secondary)", flex: 1 }}>
              {s.name}
              {s.position && (
                <span style={{ fontSize: 11, color: "var(--text-muted)", marginLeft: 5 }}>
                  {POSITION_LABEL[s.position] || s.position}
                </span>
              )}
            </span>
            <span style={{ fontSize: 13, color: "var(--gold-300)", fontWeight: 700, minWidth: 50, textAlign: "right" }}>
              {s.pct.toFixed(1)}%
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── 稀釋歷程小型堆疊條 ───────────────────────────────────────
function DilutionBar({ entries, onClick, active }) {
  return (
    <div onClick={onClick} style={{
      cursor: "pointer", display: "flex", height: 18, borderRadius: 4,
      overflow: "hidden", border: active ? "1.5px solid var(--gold-300)" : "1.5px solid transparent",
      width: 140, flexShrink: 0,
    }}>
      {entries.map((en, i) => (
        <div key={i} style={{
          width: en.pct + "%", background: PIE_COLORS[i % PIE_COLORS.length],
          minWidth: en.pct < 3 ? 2 : undefined,
        }} title={`${en.name} ${en.pct.toFixed(1)}%`} />
      ))}
    </div>
  );
}

// ── 主元件 ────────────────────────────────────────────────────
function Company() {
  const [data, setData]       = React.useState(null);
  const [capData, setCapData] = React.useState(null);
  const [activeVer, setActiveVer] = React.useState(null);   // 選中的 cap table 版本 index

  const load = () => {
    api("/api/company").then(setData).catch(() => {});
    api("/api/company/captable").then((versions) => {
      setCapData(versions);
      if (versions && versions.length) setActiveVer(versions.length - 1);
    }).catch(() => {});
  };
  React.useEffect(() => { load(); }, []);

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

  const balanceWan = (data.balance / 10000).toLocaleString("zh-TW", { maximumFractionDigits: 2 });

  // 能量核心
  const cores = data.cores || [];
  const activeCore = cores.find((c) => c.status === "active");

  // 交易明細中文化
  const txns = data.txns || [];

  // cap table
  const versions = capData || [];
  const selectedVer = activeVer != null && versions[activeVer] ? versions[activeVer] : null;
  const VERSION_REASON = {
    angel: "天使輪", founding: "創始輪", pre_a: "Pre-A", a_round: "A輪",
    ma_merge: "併購", admin: "控台調整",
  };

  return (
    <div>
      <SectionTitle eyebrow="COMPANY" align="left" size="h2" subtitle={data.team.sponsor_topic || ""}>
        {data.team.name}
      </SectionTitle>

      {/* 頂部總覽卡 */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 16, margin: "18px 0" }}>
        {/* 公司帳戶餘額 */}
        <Panel header="公司帳戶">
          <div style={{ textAlign: "center", margin: "10px 0 6px" }}>
            <span style={{ fontFamily: '"Press Start 2P",monospace', fontSize: 26, color: "var(--gold-300)" }}>
              {balanceWan}
            </span>
            <span style={{ color: "var(--text-muted)", fontSize: 12, marginLeft: 8 }}>萬元</span>
          </div>
          <div style={{ fontSize: 11, color: "var(--text-muted)", textAlign: "center" }}>
            原始金額：{data.balance.toLocaleString()} 元
          </div>
          {data.team.status === "merged" && (
            <div style={{ marginTop: 10, textAlign: "center" }}>
              <Badge tone="neutral" size="sm">已被併購</Badge>
            </div>
          )}
        </Panel>

        {/* 能量核心狀態 */}
        <Panel header="能量核心">
          {cores.length === 0 ? (
            <div style={{ color: "var(--text-muted)", fontSize: 13, padding: "10px 0" }}>尚未配發核心</div>
          ) : cores.map((c) => {
            const pct = c.status === "depleted" ? 0 : Math.max(0, Math.round((1 - c.used_wau / c.capacity_wau) * 100));
            return (
              <div key={c.seq} style={{ marginBottom: 12 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                  <span style={{ fontSize: 13, color: "var(--gold-300)" }}>第 {c.seq} 顆核心</span>
                  <Badge tone={c.status === "active" ? "gold" : "neutral"} size="sm">
                    {c.status === "active" ? "使用中" : "已耗盡"}
                  </Badge>
                </div>
                <ProgressBar value={pct} max={100} height={10} />
                <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 3 }}>
                  {c.used_wau.toLocaleString()} / {c.capacity_wau.toLocaleString()} WAU
                </div>
              </div>
            );
          })}
        </Panel>
      </div>

      {/* 股權結構 */}
      {versions.length > 0 && (
        <Panel header="股權結構">
          {/* 多版本稀釋歷程 */}
          {versions.length > 1 && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 8 }}>稀釋歷程（點選查看）</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 12, alignItems: "center" }}>
                {versions.map((v, i) => (
                  <div key={i} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4, cursor: "pointer" }}
                    onClick={() => setActiveVer(i)}>
                    <span style={{ fontSize: 11, color: i === activeVer ? "var(--gold-300)" : "var(--text-muted)" }}>
                      v{v.version} {VERSION_REASON[v.reason] || v.reason}
                    </span>
                    <DilutionBar entries={v.entries} active={i === activeVer} onClick={() => setActiveVer(i)} />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 圓餅圖 */}
          {selectedVer && (
            <>
              <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 12 }}>
                v{selectedVer.version}
                {selectedVer.reason ? `・${VERSION_REASON[selectedVer.reason] || selectedVer.reason}` : ""}
                {selectedVer.created_at ? `・${selectedVer.created_at.slice(0, 10)}` : ""}
              </div>
              <PieChart entries={selectedVer.entries} />
            </>
          )}
        </Panel>
      )}

      {/* 交易明細 */}
      <Panel header={`交易明細（最近 ${txns.length} 筆）`} style={{ marginTop: 16 }}>
        {txns.length === 0 ? (
          <div style={{ color: "var(--text-muted)", fontSize: 13, padding: "10px 0" }}>尚無交易紀錄</div>
        ) : (
          <div style={{ overflowX: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
              <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,.3)" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {txns.map((tx, i) => {
                  const wan = (tx.amount / 10000);
                  const positive = tx.amount >= 0;
                  return (
                    <tr key={i} style={{ borderTop: "1px solid rgba(212,175,55,.1)", color: "var(--text-secondary)" }}>
                      <td style={{ padding: "6px 8px", color: "var(--text-muted)" }}>{tx.created_at.slice(5, 16)}</td>
                      <td style={{ padding: "6px 8px" }}>{TYPE_LABEL[tx.type] || tx.type}</td>
                      <td style={{ padding: "6px 8px", textAlign: "right",
                          color: positive ? "var(--success,#7fc97f)" : "var(--danger,#e07a6a)", fontWeight: 700 }}>
                        {positive ? "+" : ""}{wan.toLocaleString("zh-TW", { maximumFractionDigits: 2 })}
                      </td>
                      <td style={{ padding: "6px 8px", color: "var(--text-muted)", fontSize: 11 }}>
                        {tx.ref || ""}
                        {tx.created_by ? ` (${tx.created_by})` : ""}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
        <div style={{ marginTop: 10 }}>
          <Button size="sm" variant="ghost" onClick={load}>重新整理</Button>
        </div>
      </Panel>
    </div>
  );
}

window.Company = Company;
})();
