// Dashboard — operations overview for 堆堆

// ===== Summary KPI card =====
const SummaryCard = ({ icon, iconTone = "default", label, children, sublines, footer, onClick }) => {
  const toneBg = iconTone === "default" ? "var(--surface-2)" : `var(--${iconTone}-soft)`;
  const toneFg = iconTone === "default" ? "var(--ink-3)" : `var(--${iconTone})`;
  return (
    <Card padding={20} interactive={!!onClick} onClick={onClick}
      style={{ display: "flex", flexDirection: "column", gap: 14, minHeight: 148 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ width: 34, height: 34, borderRadius: 10, background: toneBg, color: toneFg, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name={icon} size={17}/>
        </div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 500 }}>{label}</div>
      </div>
      <div style={{ flex: 1 }}>{children}</div>
      {sublines && (
        <div style={{ display: "flex", gap: 14, fontSize: 11.5, color: "var(--ink-3)" }}>
          {sublines.map((s, i) => (
            <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: s.color || "var(--ink-4)" }}/>
              {s.label} <b style={{ color: "var(--ink-2)", fontWeight: 500 }}>{s.value}</b>
            </span>
          ))}
        </div>
      )}
      {footer}
    </Card>
  );
};

const BigNumber = ({ value, unit, suffix }) => (
  <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
    {unit === "NT$" && <span style={{ fontSize: 14, color: "var(--ink-3)", fontWeight: 500 }}>NT$</span>}
    <div className="serif" style={{ fontSize: 34, lineHeight: 1, letterSpacing: -0.5 }}>{fmtNum(value)}</div>
    {suffix && <span style={{ fontSize: 13, color: "var(--ink-3)" }}>{suffix}</span>}
  </div>
);

const DeltaChip = ({ delta, label = "vs 昨日" }) => {
  const pos = delta >= 0;
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11.5, color: pos ? "var(--success)" : "var(--danger)", fontWeight: 500 }}>
      <Icon name={pos ? "arrow-up" : "arrow-down"} size={11}/>
      <span>{Math.abs(delta)}%</span>
      <span style={{ color: "var(--ink-4)", fontWeight: 400, marginLeft: 2 }}>{label}</span>
    </div>
  );
};

// ===== Date range picker =====
const DateRangePicker = ({ range, onChange }) => {
  const [open, setOpen] = React.useState(false);
  const [viewDate, setViewDate] = React.useState(() => {
    const d = new Date(); return { year: d.getFullYear(), month: d.getMonth() };
  });
  const [picking, setPicking] = React.useState(null);
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const handler = e => { if (ref.current && !ref.current.contains(e.target)) { setOpen(false); setPicking(null); } };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  const today = new Date(); today.setHours(23, 59, 59, 999);

  const presets = [
    { label: "今日",     from: () => { const d = new Date(); d.setHours(0,0,0,0); return d; }, to: () => today },
    { label: "近 7 天",  from: () => { const d = new Date(); d.setDate(d.getDate()-6); d.setHours(0,0,0,0); return d; }, to: () => today },
    { label: "近 30 天", from: () => { const d = new Date(); d.setDate(d.getDate()-29); d.setHours(0,0,0,0); return d; }, to: () => today },
    { label: "近 90 天", from: () => { const d = new Date(); d.setDate(d.getDate()-89); d.setHours(0,0,0,0); return d; }, to: () => today },
    { label: "全部時間", from: () => null, to: () => null },
  ];

  function applyPreset(p) {
    onChange({ label: p.label, from: p.from(), to: p.to() });
    setOpen(false); setPicking(null);
  }

  const { year, month } = viewDate;
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const startOffset = (new Date(year, month, 1).getDay() + 6) % 7; // Mon=0
  const WDAYS = ["一","二","三","四","五","六","日"];

  function dayDate(d) { return new Date(year, month, d); }
  function sameDay(a, b) { return a && b && a.toDateString() === b.toDateString(); }
  function inRange(d) {
    if (!range.from || !range.to) return false;
    const date = dayDate(d);
    return date >= range.from && date <= range.to;
  }

  function clickDay(d) {
    const date = dayDate(d);
    if (!picking) { setPicking(date); }
    else {
      const start = picking <= date ? picking : date;
      const end   = picking <= date ? date : picking;
      end.setHours(23, 59, 59, 999);
      const fmt = x => `${x.getMonth()+1}/${x.getDate()}`;
      onChange({ label: `${fmt(start)}–${fmt(end)}`, from: start, to: end });
      setPicking(null); setOpen(false);
    }
  }

  const cells = Array(startOffset).fill(null).concat(Array.from({ length: daysInMonth }, (_, i) => i + 1));
  while (cells.length % 7) cells.push(null);

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <Button variant="secondary" icon="calendar" onClick={() => setOpen(o => !o)}>
        {range.label}
      </Button>
      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 6px)", right: 0, zIndex: 1000,
          background: "var(--surface)", border: "1px solid var(--border)",
          borderRadius: 12, boxShadow: "0 8px 28px rgba(0,0,0,.13)",
          display: "flex", overflow: "hidden",
        }}>
          {/* Presets */}
          <div style={{ padding: "10px 0", borderRight: "1px solid var(--border)", minWidth: 108 }}>
            {presets.map(p => {
              const active = range.label === p.label;
              return (
                <button key={p.label} onClick={() => applyPreset(p)} style={{
                  display: "block", width: "100%", textAlign: "left",
                  padding: "8px 16px", fontSize: 13,
                  color: active ? "var(--ink)" : "var(--ink-2)",
                  fontWeight: active ? 600 : 400,
                  background: active ? "var(--surface-2)" : "transparent",
                }}
                  onMouseEnter={e => { if (!active) e.currentTarget.style.background = "var(--surface-2)"; }}
                  onMouseLeave={e => { if (!active) e.currentTarget.style.background = "transparent"; }}
                >{p.label}</button>
              );
            })}
          </div>
          {/* Calendar */}
          <div style={{ padding: "16px 18px", minWidth: 224 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
              <button onClick={() => setViewDate(v => { const d = new Date(v.year, v.month - 1, 1); return { year: d.getFullYear(), month: d.getMonth() }; })}
                style={{ padding: "2px 6px", color: "var(--ink-3)" }}><Icon name="arrow-left" size={13}/></button>
              <span style={{ fontSize: 13.5, fontWeight: 600 }}>{year} 年 {month + 1} 月</span>
              <button onClick={() => setViewDate(v => { const d = new Date(v.year, v.month + 1, 1); return { year: d.getFullYear(), month: d.getMonth() }; })}
                style={{ padding: "2px 6px", color: "var(--ink-3)" }}><Icon name="arrow-right" size={13}/></button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 2, marginBottom: 4 }}>
              {WDAYS.map(w => <div key={w} style={{ textAlign: "center", fontSize: 10.5, color: "var(--ink-4)", padding: "2px 0" }}>{w}</div>)}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 2 }}>
              {cells.map((d, i) => {
                if (!d) return <div key={i}/>;
                const isToday = sameDay(dayDate(d), new Date());
                const isStart = sameDay(dayDate(d), range.from);
                const isEnd   = sameDay(dayDate(d), range.to);
                const inR     = inRange(d);
                const isPick  = sameDay(dayDate(d), picking);
                const hilite  = isStart || isEnd || isPick;
                return (
                  <button key={i} onClick={() => clickDay(d)} style={{
                    height: 28, borderRadius: 6, fontSize: 12, cursor: "pointer",
                    background: hilite ? "var(--ink)" : inR ? "var(--surface-2)" : "transparent",
                    color: hilite ? "#fff" : isToday ? "var(--accent)" : "var(--ink-2)",
                    fontWeight: hilite || isToday ? 600 : 400,
                    outline: isToday && !hilite ? "1.5px solid var(--accent)" : "none",
                    outlineOffset: -1,
                  }}>{d}</button>
                );
              })}
            </div>
            {picking && (
              <div style={{ marginTop: 10, fontSize: 11, color: "var(--ink-3)", textAlign: "center" }}>
                已選起始日，請點選結束日
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

// ===== Chart: placeholder (no real data yet) =====
const EmptyChart = ({ title, subtitle }) => (
  <Card padding={24} style={{ height: "100%" }}>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18 }}>
      <div>
        <div style={{ fontSize: 13.5, fontWeight: 600 }}>{title}</div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{subtitle}</div>
      </div>
    </div>
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", height: 160, color: "var(--ink-4)", gap: 8 }}>
      <Icon name="chart" size={28}/>
      <div style={{ fontSize: 13 }}>暫無歷史數據</div>
    </div>
  </Card>
);

const UserGrowthChart = ({ onNav, dateRange }) => {
  const [data, setData] = React.useState([]);
  const [hovered, setHovered] = React.useState(null); // { index, x, y }
  React.useEffect(() => {
    const fmt = d => d ? d.toISOString().slice(0, 10) : null;
    const from = fmt(dateRange?.from);
    const to = fmt(dateRange?.to);
    const params = new URLSearchParams();
    if (from) params.set("from", from);
    if (to)   params.set("to", to);
    fetch(`/api/admin/stats/growth${params.size ? "?" + params : ""}`)
      .then(r => r.ok ? r.json() : [])
      .then(d => setData(Array.isArray(d) ? d : []));
  }, [dateRange?.from?.getTime?.(), dateRange?.to?.getTime?.()]);

  const total = data.reduce((s, d) => s + d.total, 0);
  const max = Math.max(...data.map(d => d.total), 1);
  const VW = 600; const VH = 120;
  const n = data.length || 30;
  const slotW = VW / n;
  const barW = Math.max(slotW - 3, 2);

  return (
    <Card padding={24} style={{ height: "100%", cursor: onNav ? "pointer" : "default" }} onClick={() => onNav?.("growth")}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600 }}>用戶成長</div>
          <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{dateRange?.label ?? "近 30 天"}每日新增　→ 點擊查看詳情</div>
        </div>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.5 }}>+{fmtNum(total)}</div>
      </div>
      <div style={{ display: "flex", gap: 12, fontSize: 11.5, marginBottom: 12 }}>
        <span style={{ display: "flex", alignItems: "center", gap: 4, color: "var(--ink-3)" }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: "var(--success)", display: "inline-block" }}/>創作者
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: 4, color: "var(--ink-3)" }}>
          <span style={{ width: 8, height: 8, borderRadius: 2, background: "var(--info)", display: "inline-block" }}/>委託人
        </span>
      </div>
      {data.length === 0 ? (
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", height: VH, 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}`} width="100%" height={VH} style={{ display: "block", overflow: "visible" }}>
            {data.map((d, i) => {
              const totalH = Math.max(d.total > 0 ? 4 : 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 isRecent = i >= data.length - 5;
              const opacity = isRecent ? 1 : 0.5;
              return (
                <g key={d.date}
                  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)}
                >
                  <rect x={x} y={VH - clientH} width={barW} height={clientH} fill="var(--info)" opacity={opacity} />
                  <rect x={x} y={VH - totalH} width={barW} height={creatorH} rx={2} fill="var(--success)" opacity={opacity} />
                </g>
              );
            })}
          </svg>
          {hovered !== null && data[hovered.index] && (
            <div style={{
              position: "absolute", bottom: VH + 6, left: hovered.svgX,
              transform: "translateX(-50%)",
              background: "var(--ink)", color: "#fff",
              fontSize: 11.5, fontWeight: 500, whiteSpace: "nowrap",
              padding: "5px 9px", borderRadius: 6, pointerEvents: "none", lineHeight: 1.7,
            }}>
              <div>{data[hovered.index].date.slice(5)}</div>
              <div style={{ color: "#6ee7b7" }}>創作者 +{data[hovered.index].creators}</div>
              <div style={{ color: "#93c5fd" }}>委託人 +{data[hovered.index].clients}</div>
            </div>
          )}
        </div>
      )}
    </Card>
  );
};


const OrderRevenueChart = () => <EmptyChart title="訂單量 + 營收" subtitle="近 30 天每日"/>;

const DisputeRateChart = () => <EmptyChart title="糾紛率" subtitle="糾紛訂單 / 總訂單 · 近 30 天"/>;

// ===== Quick actions =====
const QuickActionsPanel = ({ onGo }) => {
  const items = [
    { key: "disputes", icon: "alert", tone: "danger", label: "處理調解", desc: "無進行中調解", count: 0 },
    { key: "finance", icon: "coin", tone: "accent", label: "提領審核", desc: "無待審核", count: 0 },
    { key: "applications", icon: "palette", tone: "info", label: "創作者申請", desc: "無待審核申請", count: 0 },
  ];
  return (
    <Card padding={0} style={{ overflow: "hidden", height: "100%" }}>
      <div style={{ padding: "18px 22px 14px", borderBottom: "1px solid var(--border)" }}>
        <div style={{ fontSize: 13.5, fontWeight: 600 }}>快速操作</div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>需要你立即處理的事項</div>
      </div>
      <div style={{ display: "flex", flexDirection: "column" }}>
        {items.map((a, i) => (
          <button key={a.key} onClick={() => onGo?.(a.key)} style={{
            padding: "18px 22px", textAlign: "left",
            borderBottom: i < items.length - 1 ? "1px solid var(--border)" : "none",
            display: "flex", gap: 14, alignItems: "center",
            transition: "background .12s",
          }}
            onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"}
            onMouseLeave={e => e.currentTarget.style.background = "transparent"}
          >
            <div style={{ width: 40, height: 40, borderRadius: 10, background: `var(--${a.tone}-soft)`, color: `var(--${a.tone})`, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name={a.icon} size={19}/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 14, fontWeight: 500 }}>{a.label}</span>
                <Badge tone={a.tone} size="sm">{a.count}</Badge>
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 3 }}>{a.desc}</div>
            </div>
            <Icon name="arrow-right" size={16} style={{ color: "var(--ink-4)" }}/>
          </button>
        ))}
      </div>
    </Card>
  );
};

// ===== Main =====
const DashboardPage = ({ adminEmail, onNav }) => {
  const toast = useToast?.();
  const [stats, setStats] = React.useState({ users: null, r18Products: null });

  const initRange = () => {
    const from = new Date(); from.setDate(from.getDate() - 29); from.setHours(0, 0, 0, 0);
    const to = new Date(); to.setHours(23, 59, 59, 999);
    return { label: "近 30 天", from, to };
  };
  const [dateRange, setDateRange] = React.useState(initRange);

  React.useEffect(() => {
    fetch("/api/admin/stats")
      .then(r => r.ok ? r.json() : null)
      .then(d => { if (d) setStats(d); });
  }, []);

  const today = new Date().toLocaleDateString("zh-TW", { year: "numeric", month: "long", day: "numeric" });

  const goTo = (key) => { onNav?.(key); };

  return (
    <div className="fade-in">
      <PageHeader
        title={<span>早安，{adminEmail ? adminEmail.split("@")[0] : "你"} <span style={{ fontSize: 20, fontWeight: 400, color: "var(--ink-3)" }}>— {today}</span></span>}
        subtitle="堆堆平台今日營運概況"
        actions={<>
          <DateRangePicker range={dateRange} onChange={setDateRange}/>
          <Button variant="secondary" icon="download" onClick={() => {
            csvDownload(`dashboard_${Date.now()}.csv`,
              ["指標","數值"],
              [
                ["累計用戶", stats.users ?? ""],
                ["成人內容商品", stats.r18Products ?? ""],
                ["匯出時間", new Date().toLocaleString("zh-TW")],
              ]
            );
          }}>匯出報表</Button>
        </>}
      />

      {/* Summary cards row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 14, marginBottom: 20 }}>
        <SummaryCard
          icon="users" iconTone="info" label="累計用戶"
        >
          <BigNumber value={stats.users ?? "—"}/>
        </SummaryCard>

        <SummaryCard
          icon="order" iconTone="default" label="今日新訂單"
          sublines={[{ label: "金額", value: "NT$ 0", color: "var(--ink)" }]}
        >
          <BigNumber value={0} suffix="筆"/>
        </SummaryCard>

        <SummaryCard
          icon="coin" iconTone="accent" label="託管中金額"
          sublines={[{ label: "進行中訂單", value: 0, color: "var(--accent)" }]}
        >
          <BigNumber value={0} unit="NT$"/>
        </SummaryCard>

        <SummaryCard
          icon="clipboard" iconTone="warn" label="待處理事項"
          sublines={[
            { label: "審核", value: 0, color: "var(--warn)" },
            { label: "客服", value: 0, color: "var(--info)" },
          ]}
        >
          <BigNumber value={0} suffix="件"/>
        </SummaryCard>

        <SummaryCard
          icon="flag" iconTone="danger" label="新增檢舉 (24h)"
          sublines={[
            { label: "作品", value: 0, color: "var(--danger)" },
            { label: "用戶", value: 0, color: "var(--warn)" },
          ]}
        >
          <BigNumber value={0} suffix="件"/>
        </SummaryCard>
      </div>

      {/* Charts row 1 */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
        <UserGrowthChart onNav={onNav} dateRange={dateRange}/>
        <OrderRevenueChart/>
      </div>

      {/* Charts row 2 + quick actions */}
      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 16, marginBottom: 16 }}>
        <DisputeRateChart/>
        <QuickActionsPanel onGo={goTo}/>
      </div>

      {/* R18 專區 */}
      <Card padding={0} style={{ overflow: "hidden" }}>
        <button onClick={() => goTo("r18")} style={{
          width: "100%", padding: "14px 22px", borderBottom: "1px solid var(--border)",
          display: "flex", alignItems: "center", gap: 10, textAlign: "left",
          transition: "background .12s",
        }}
          onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"}
          onMouseLeave={e => e.currentTarget.style.background = "transparent"}
        >
          <div style={{
            width: 30, height: 30, borderRadius: 8,
            background: "var(--danger-soft)", color: "var(--danger)",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 13, fontWeight: 700, flexShrink: 0,
          }}>R</div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>R18 專區</div>
            <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 1 }}>限制級內容監控 · 需成年驗證方可瀏覽</div>
          </div>
          <div style={{ flex: 1 }}/>
          <Icon name="arrow-right" size={15} style={{ color: "var(--ink-4)" }}/>
        </button>
        <div style={{ padding: "18px 22px", display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 0 }}>
          {[
            { label: "R18 商品數", value: stats.r18Products ?? "—", unit: "件", tone: "danger", desc: "含 R18 標籤的上架商品" },
            { label: "占全部商品", value: stats.r18Products != null && stats.products ? Math.round(stats.r18Products / stats.products * 100) + "%" : "—", unit: "", tone: "default", desc: "R18 / 全部商品比例" },
            { label: "待審核內容", value: "—", unit: "件", tone: "warn", desc: "尚未接入審核流程" },
            { label: "成年驗證用戶", value: "—", unit: "位", tone: "info", desc: "尚未接入驗證資料庫" },
          ].map((m, i, arr) => (
            <div key={m.label} style={{
              padding: "14px 20px",
              borderRight: i < arr.length - 1 ? "1px solid var(--border)" : "none",
            }}>
              <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginBottom: 6 }}>{m.label}</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
                <span className="mono" style={{ fontSize: 26, fontWeight: 600, color: m.tone === "default" ? "var(--ink)" : `var(--${m.tone})` }}>
                  {m.value}
                </span>
                {m.unit && <span style={{ fontSize: 12, color: "var(--ink-3)" }}>{m.unit}</span>}
              </div>
              <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 4 }}>{m.desc}</div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
};

window.DashboardPage = DashboardPage;
