// User Growth detail page — monthly breakdown

const GrowthPage = ({ onNav }) => {
  const [data, setData] = React.useState([]);
  const [hovered, setHovered] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    fetch("/api/admin/stats/growth?monthly=1")
      .then(r => r.ok ? r.json() : [])
      .then(d => { setData(Array.isArray(d) ? d : []); setLoading(false); });
  }, []);

  const max = Math.max(...data.map(d => d.total), 1);
  const totalAll = data.reduce((s, d) => s + d.total, 0);
  const totalCreators = data.reduce((s, d) => s + d.creators, 0);
  const totalClients = data.reduce((s, d) => s + d.clients, 0);

  let cum = 0;
  const rows = data.map(d => { cum += d.total; return { ...d, cumulative: cum }; });

  const VW = 600; const VH = 180;
  const n = data.length || 1;
  const slotW = VW / n;
  const barW = Math.max(slotW - 6, 4);

  const MONTH_LABELS = ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"];
  const COLOR_CLIENT  = "var(--info)";
  const COLOR_CREATOR = "var(--success)";

  return (
    <div className="fade-in">
      <PageHeader
        title="用戶成長"
        subtitle="每月新增用戶統計"
        actions={
          <Button variant="secondary" icon="arrow-left" onClick={() => onNav?.("dashboard")}>
            返回儀表板
          </Button>
        }
      />

      {/* Summary */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 20 }}>
        <Card padding={20}>
          <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 500, marginBottom: 8 }}>累計用戶</div>
          <div className="serif" style={{ fontSize: 32, letterSpacing: -0.5 }}>{fmtNum(totalAll)}</div>
        </Card>
        <Card padding={20}>
          <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 500, marginBottom: 8 }}>本月新增</div>
          <div className="serif" style={{ fontSize: 32, letterSpacing: -0.5 }}>
            {data.length ? fmtNum(data[data.length - 1].total) : "—"}
          </div>
        </Card>
        <Card padding={20}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: COLOR_CREATOR, display: "inline-block" }}/>
            <span style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 500 }}>創作者</span>
          </div>
          <div className="serif" style={{ fontSize: 32, letterSpacing: -0.5, color: "var(--success)" }}>{fmtNum(totalCreators)}</div>
        </Card>
        <Card padding={20}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: COLOR_CLIENT, display: "inline-block" }}/>
            <span style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 500 }}>委託人</span>
          </div>
          <div className="serif" style={{ fontSize: 32, letterSpacing: -0.5, color: "var(--info)" }}>{fmtNum(totalClients)}</div>
        </Card>
      </div>

      {/* Chart */}
      <Card padding={24} style={{ marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
          <div>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>每月新增用戶</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>各月份新增人數</div>
          </div>
          {/* Legend */}
          <div style={{ display: "flex", gap: 16, fontSize: 12, color: "var(--ink-3)" }}>
            <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
              <span style={{ width: 10, height: 10, borderRadius: 2, background: COLOR_CREATOR, display: "inline-block" }}/>
              創作者
            </span>
            <span style={{ display: "flex", alignItems: "center", gap: 5 }}>
              <span style={{ width: 10, height: 10, borderRadius: 2, background: COLOR_CLIENT, display: "inline-block" }}/>
              委託人
            </span>
          </div>
        </div>

        {loading ? (
          <div style={{ height: VH, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-4)", fontSize: 13 }}>載入中…</div>
        ) : data.length === 0 ? (
          <div style={{ height: VH, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", color: "var(--ink-4)", gap: 8 }}>
            <Icon name="chart" size={28}/>
            <div style={{ fontSize: 13 }}>暫無歷史數據</div>
          </div>
        ) : (
          <div style={{ position: "relative" }}>
            <svg viewBox={`0 0 ${VW} ${VH + 20}`} width="100%" height={VH + 20} style={{ display: "block" }}>
              {data.map((d, i) => {
                const totalH = Math.max(d.total > 0 ? 6 : 2, Math.round((d.total / max) * VH));
                const clientH = d.total > 0 ? Math.round((d.clients / d.total) * totalH) : 0;
                const creatorH = totalH - clientH;
                const x = i * slotW + (slotW - barW) / 2;
                const isLatest = i === data.length - 1;
                const opacity = isLatest ? 1 : 0.7;
                return (
                  <g key={d.month}
                    style={{ cursor: "pointer" }}
                    onMouseEnter={e => {
                      const svgRect = e.currentTarget.closest("svg").getBoundingClientRect();
                      const svgX = (i * slotW + slotW / 2) / VW * svgRect.width;
                      setHovered({ index: i, svgX });
                    }}
                    onMouseLeave={() => setHovered(null)}
                  >
                    {/* Client portion (bottom) */}
                    <rect x={x} y={VH - clientH} width={barW} height={clientH} rx={0}
                      fill={COLOR_CLIENT} opacity={opacity} />
                    {/* Creator portion (top) */}
                    <rect x={x} y={VH - totalH} width={barW} height={creatorH} rx={3}
                      fill={COLOR_CREATOR} opacity={opacity} />
                    {/* Round bottom corners on client bar only if no creator */}
                    {creatorH === 0 && clientH > 0 && (
                      <rect x={x} y={VH - clientH} width={barW} height={Math.min(6, clientH)} rx={3}
                        fill={COLOR_CLIENT} opacity={opacity} />
                    )}
                    {/* Month label */}
                    <text x={x + barW / 2} y={VH + 14} textAnchor="middle"
                      style={{ fontSize: 9, fill: "var(--ink-4)", fontFamily: "var(--font-sans)" }}>
                      {MONTH_LABELS[parseInt(d.month.slice(5, 7)) - 1]}
                    </text>
                  </g>
                );
              })}
            </svg>
            {hovered !== null && data[hovered.index] && (
              <div style={{
                position: "absolute", bottom: VH + 28, left: hovered.svgX,
                transform: "translateX(-50%)",
                background: "var(--ink)", color: "#fff",
                fontSize: 12, fontWeight: 500, whiteSpace: "nowrap",
                padding: "6px 10px", borderRadius: 7, pointerEvents: "none",
                lineHeight: 1.7,
              }}>
                <div>{data[hovered.index].month}</div>
                <div style={{ color: "#6ee7b7" }}>創作者 +{data[hovered.index].creators}</div>
                <div style={{ color: "#93c5fd" }}>委託人 +{data[hovered.index].clients}</div>
              </div>
            )}
          </div>
        )}
      </Card>

      {/* Monthly table */}
      <Card padding={0} style={{ overflow: "hidden" }}>
        <div style={{ padding: "18px 22px 14px", borderBottom: "1px solid var(--border)" }}>
          <div style={{ fontSize: 13.5, fontWeight: 600 }}>月份明細</div>
        </div>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
          <thead>
            <tr style={{ background: "var(--surface-2)" }}>
              {["月份", "新增總計", "創作者", "委託人", "累計用戶"].map(h => (
                <th key={h} style={{ padding: "10px 22px", textAlign: "left", fontSize: 11.5, fontWeight: 600, color: "var(--ink-3)", letterSpacing: 0.3 }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {[...rows].reverse().map((r, i) => (
              <tr key={r.month} style={{ borderTop: "1px solid var(--border)", background: i === 0 ? "var(--accent-soft)" : "transparent" }}>
                <td style={{ padding: "12px 22px", fontWeight: 500 }}>{r.month}</td>
                <td style={{ padding: "12px 22px", fontWeight: 600 }}>+{fmtNum(r.total)}</td>
                <td style={{ padding: "12px 22px", color: "var(--success)", fontWeight: 500 }}>+{fmtNum(r.creators)}</td>
                <td style={{ padding: "12px 22px", color: "var(--info)", fontWeight: 500 }}>+{fmtNum(r.clients)}</td>
                <td style={{ padding: "12px 22px", color: "var(--ink-2)" }}>{fmtNum(r.cumulative)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
};

window.GrowthPage = GrowthPage;
