// === Dashboard screen ===
function Dashboard({ goto, products, orders, productsSource, ordersSource, ordersLoading, ordersDays, productsMeta }) {
  const { PRODUCTS, ORDERS, SALES_TREND } = window.MOCK;
  const isLive = productsSource === "live" || ordersSource === "live";

  // 사용할 데이터 소스
  const usedProducts = productsSource === "live" ? products : PRODUCTS;
  const usedOrders = ordersSource === "live" ? orders : ORDERS;

  // 라이브 통계 계산 (orders 기반)
  const liveStats = useMemo(() => {
    if (ordersSource !== "live") return null;
    // 매출 인정 상태: paid/shipped/delivered (취소/반품 제외)
    const validOrders = usedOrders.filter(o => ["paid", "shipped", "delivered"].includes(o.status));

    // 일별 매출/주문수
    const byDate = new Map();
    validOrders.forEach(o => {
      const date = (o.date || "").slice(0, 10);
      if (!date) return;
      if (!byDate.has(date)) byDate.set(date, { revenue: 0, orders: 0 });
      const e = byDate.get(date);
      e.revenue += o.totalPaymentAmount || 0;
      e.orders++;
    });

    // 트렌드 라인 (ordersDays 기간만큼)
    const trendDays = ordersDays || 7;
    const trend = [];
    for (let i = trendDays - 1; i >= 0; i--) {
      const d = new Date(Date.now() - i * 24 * 3600 * 1000);
      const isoDate = d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
      const label = String(d.getMonth() + 1).padStart(2, "0") + "/" + String(d.getDate()).padStart(2, "0");
      const entry = byDate.get(isoDate) || { revenue: 0, orders: 0 };
      trend.push({ d: label, isToday: i === 0, revenue: entry.revenue, orders: entry.orders });
    }

    // 베스트 상품 (orders item 합산)
    const productSales = new Map();
    validOrders.forEach(o => {
      o.items.forEach(it => {
        const pid = it.pid;
        if (!pid) return;
        if (!productSales.has(pid)) productSales.set(pid, { pid, name: it.name || "", qty: 0, revenue: 0 });
        const e = productSales.get(pid);
        e.qty += it.qty;
        e.revenue += (it.price || 0) * it.qty;
      });
    });
    const topProducts = Array.from(productSales.values()).sort((a, b) => b.qty - a.qty).slice(0, 5);

    return {
      trend,
      todayRevenue: trend[trend.length - 1]?.revenue || 0,
      yesterdayRevenue: trend[trend.length - 2]?.revenue || 0,
      totalRevenue: trend.reduce((s, e) => s + e.revenue, 0),
      totalOrders: trend.reduce((s, e) => s + e.orders, 0),
      newOrders: usedOrders.filter(o => o.status === "paid").length,
      canceledOrders: usedOrders.filter(o => o.status === "canceled").length,
      topProducts,
      recentOrders: usedOrders.slice(0, 5),
      validCount: validOrders.length,
    };
  }, [ordersSource, usedOrders, ordersDays]);

  // 표시할 값 (라이브 vs mock)
  const todayRevenue = liveStats ? liveStats.todayRevenue : SALES_TREND[SALES_TREND.length - 1].revenue;
  const yesterdayRevenue = liveStats ? liveStats.yesterdayRevenue : SALES_TREND[SALES_TREND.length - 2].revenue;
  const revenueChange = yesterdayRevenue > 0 ? ((todayRevenue - yesterdayRevenue) / yesterdayRevenue) * 100 : 0;
  const totalRevenue = liveStats ? liveStats.totalRevenue : SALES_TREND.reduce((s, d) => s + d.revenue, 0);
  const totalOrders = liveStats ? liveStats.totalOrders : SALES_TREND.reduce((s, d) => s + d.orders, 0);
  const newOrders = liveStats ? liveStats.newOrders : usedOrders.filter(o => o.status === "paid").length;
  const outOfStock = usedProducts.filter(p => p.status === "outofstock").length;
  const activeProducts = usedProducts.filter(p => p.status === "active").length;
  const totalProducts = productsSource === "live" ? (productsMeta?.totalElements || usedProducts.length) : usedProducts.length;

  const topProducts = liveStats
    ? liveStats.topProducts
    : [...usedProducts].sort((a, b) => b.sales30d - a.sales30d).slice(0, 5);
  const recentOrders = liveStats ? liveStats.recentOrders : usedOrders.slice(0, 5);

  const trendData = liveStats ? liveStats.trend : SALES_TREND.map(d => ({ ...d, isToday: d.d === "05/10" }));
  const chartMax = Math.max(1, ...trendData.map(d => d.revenue));
  const trendLabel = liveStats ? `최근 ${ordersDays || 7}일` : "최근 14일";

  const today = new Date();
  const todayLabel = `${today.getFullYear()}년 ${today.getMonth() + 1}월 ${today.getDate()}일`;

  return (
    <div className="page">
      <div className="page-header">
        <h1 className="page-title">대시보드</h1>
        <p className="page-desc">
          {todayLabel} · {isLive ? "네이버 라이브" : "샘플 데이터"}
          {isLive && liveStats && ` · 실 매출 인정 주문 ${liveStats.validCount}건${liveStats.canceledOrders > 0 ? ` · 취소 ${liveStats.canceledOrders}` : ""}`}
        </p>
      </div>

      {ordersLoading && (
        <div style={{ padding: "8px 14px", marginBottom: 12, background: "var(--accent-soft)", borderRadius: 8, fontSize: 12 }}>
          <window.I.Refresh size={14} stroke="var(--accent)" style={{ verticalAlign: "middle", marginRight: 6 }} />
          네이버에서 주문 데이터 불러오는 중...
        </div>
      )}

      <div className="stat-grid" style={{ marginBottom: 16 }}>
        <StatTile
          label="오늘의 매출"
          value={formatKRW(todayRevenue)}
          delta={revenueChange}
          icon={<window.I.Wallet size={14} />}
          spark={trendData.map(d => d.revenue)}
        />
        <StatTile
          label="신규 주문 (결제완료)"
          value={`${newOrders}건`}
          deltaText={newOrders > 0 ? `발송 대기 ${newOrders}건` : "대기 주문 없음"}
          deltaPositive={newOrders > 0}
          icon={<window.I.ShoppingCart size={14} />}
        />
        <StatTile
          label="진행 중 상품"
          value={`${activeProducts}개${productsSource === "live" ? " / " + totalProducts : ""}`}
          deltaText={`품절 ${outOfStock}개`}
          deltaPositive={outOfStock === 0}
          icon={<window.I.Package size={14} />}
        />
        <StatTile
          label={`${trendLabel} 누적 매출`}
          value={formatKRW(totalRevenue)}
          deltaText={`주문 ${totalOrders}건`}
          deltaPositive
          icon={<window.I.Calendar size={14} />}
        />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 12, marginBottom: 12 }} className="dash-grid">
        {/* Sales chart */}
        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">매출 추이</div>
              <div className="text-xs muted" style={{ marginTop: 2 }}>
                {trendLabel}{isLive && " (paid/shipped/delivered 합산)"}
              </div>
            </div>
            {isLive ? (
              <div className="right text-xs muted" style={{ alignSelf: "center" }}>
                기간 변경은 주문/판매 내역에서
              </div>
            ) : (
              <div className="right seg">
                <button className="seg-btn">7일</button>
                <button className="seg-btn active">14일</button>
                <button className="seg-btn">30일</button>
              </div>
            )}
          </div>
          <div className="card-body" style={{ padding: "20px 16px" }}>
            {trendData.every(d => d.revenue === 0) ? (
              <div className="empty" style={{ padding: 40 }}>
                <window.I.Calendar size={32} className="empty-icon" />
                <div>{trendLabel} 동안 매출 데이터가 없습니다</div>
              </div>
            ) : (
              <div style={{ display: "flex", alignItems: "flex-end", gap: 6, height: 200, paddingBottom: 22, position: "relative" }}>
                {trendData.map((d, i) => {
                  const h = (d.revenue / chartMax) * 178;
                  return (
                    <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                      <div style={{ flex: 1, width: "100%", display: "flex", alignItems: "flex-end", justifyContent: "center" }}>
                        <div style={{
                          width: "70%",
                          height: Math.max(2, h),
                          background: d.isToday ? "var(--accent)" : "var(--accent-soft)",
                          borderRadius: "4px 4px 0 0",
                          position: "relative",
                          transition: "height 0.4s",
                        }} title={`${d.d}: ${formatKRW(d.revenue)} · ${d.orders}건`}>
                          {d.isToday && d.revenue > 0 && (
                            <div style={{
                              position: "absolute", top: -22, left: "50%", transform: "translateX(-50%)",
                              background: "var(--text)", color: "var(--bg)", fontSize: 10, fontWeight: 600,
                              padding: "2px 6px", borderRadius: 4, whiteSpace: "nowrap"
                            }}>
                              {Math.round(d.revenue / 10000)}만
                            </div>
                          )}
                        </div>
                      </div>
                      <div style={{ fontSize: 10, color: "var(--text-subtle)" }}>{d.d}</div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>

        {/* Quick actions */}
        <div className="card">
          <div className="card-header">
            <div className="card-title">빠른 작업</div>
          </div>
          <div className="card-body" style={{ padding: 12, display: "flex", flexDirection: "column", gap: 6 }}>
            <QuickAction icon={<window.I.Edit size={14} />} label="상품 가격 수정" desc="개별 또는 일괄 수정" onClick={() => goto("products")} />
            <QuickAction icon={<window.I.Tag size={14} />} label="일괄 가격 변경" desc="키워드/카테고리 필터로 일괄" onClick={() => goto("bulk")} accent />
            <QuickAction icon={<window.I.Truck size={14} />} label="로젠 송장 출력" desc={`${newOrders}건 발송 대기`} onClick={() => goto("shipping")} />
            <QuickAction icon={<window.I.Plug size={14} />} label="ISVM 상품 등록" desc="공급사 카탈로그 → 스토어 연동" onClick={() => goto("isvm")} />
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="dash-grid">
        {/* Top products */}
        <div className="card">
          <div className="card-header">
            <div className="card-title">베스트 상품 {liveStats ? `(${trendLabel} 판매 기준)` : "TOP 5"}</div>
            <button className="btn btn-ghost btn-sm right" onClick={() => goto("products")}>
              전체 <window.I.ChevronRight size={12} />
            </button>
          </div>
          <div>
            {topProducts.length === 0 ? (
              <div className="empty" style={{ padding: 24 }}>
                <div className="text-sm">판매 데이터가 없습니다</div>
              </div>
            ) : topProducts.map((p, i) => (
              <div key={p.pid || p.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 16px", borderTop: i ? "1px solid var(--border)" : "none" }}>
                <div style={{ width: 18, color: "var(--text-subtle)", fontWeight: 600, fontSize: 12, fontVariantNumeric: "tabular-nums" }}>{i + 1}</div>
                {!isLive && <ProductThumb tone={p.tone} name={p.name} size={36} />}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }} title={p.name}>{p.name}</div>
                  <div className="text-xs muted">
                    {liveStats ? `매출 ${formatKRW(p.revenue)}` : `${formatKRW(p.price)} · 재고 ${p.stock}`}
                  </div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div className="tabular" style={{ fontSize: 13, fontWeight: 600 }}>
                    {liveStats ? `${p.qty}개` : `${p.sales30d}건`}
                  </div>
                  <div className="text-xs muted">{trendLabel} 판매</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Recent orders */}
        <div className="card">
          <div className="card-header">
            <div className="card-title">최근 주문</div>
            <button className="btn btn-ghost btn-sm right" onClick={() => goto("orders")}>
              전체 <window.I.ChevronRight size={12} />
            </button>
          </div>
          <div>
            {recentOrders.length === 0 ? (
              <div className="empty" style={{ padding: 24 }}>
                <div className="text-sm">{trendLabel} 동안 주문이 없습니다</div>
              </div>
            ) : recentOrders.map((o, i) => {
              const isLiveOrder = ordersSource === "live";
              const firstItem = !isLiveOrder ? window.MOCK.PRODUCTS.find(x => x.id === o.items[0].pid) : null;
              const productName = isLiveOrder ? (o.items[0]?.name || "") : (firstItem?.name || "");
              const totalPrice = o.totalPaymentAmount || (isLiveOrder
                ? (o.items[0]?.price || 0) * (o.items[0]?.qty || 0)
                : o.items.reduce((s, it) => {
                    const p = window.MOCK.PRODUCTS.find(x => x.id === it.pid);
                    return s + (p ? p.price * it.qty : 0);
                  }, 0));
              return (
                <div key={o.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 16px", borderTop: i ? "1px solid var(--border)" : "none" }}>
                  {!isLiveOrder && <ProductThumb tone={firstItem?.tone || 0} name={firstItem?.name || ""} size={32} />}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }} title={`${o.buyer} · ${productName}`}>
                      {o.buyer} · {o.items.length === 1 ? productName : `${productName} 외 ${o.items.length - 1}건`}
                    </div>
                    <div className="text-xs muted">{(o.date || "").split(" ")[1]} · {String(o.id || "").slice(-8)}</div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <div className="tabular" style={{ fontSize: 13, fontWeight: 600 }}>{formatKRW(totalPrice)}</div>
                    <StatusBadge status={o.status} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function StatTile({ label, value, delta, deltaText, deltaPositive, icon, spark }) {
  const showDelta = delta !== undefined && delta !== 0 && !isNaN(delta);
  const isUp = showDelta ? delta >= 0 : deltaPositive;
  return (
    <div className="stat-tile">
      <div className="stat-label">{icon} {label}</div>
      <div className="stat-value">{value}</div>
      <div className="row" style={{ justifyContent: "space-between", marginTop: 6 }}>
        {showDelta ? (
          <div className={"stat-delta " + (isUp ? "up" : "down")}>
            {isUp ? <window.I.ArrowUp size={12} /> : <window.I.ArrowDown size={12} />}
            {Math.abs(delta).toFixed(1)}% (전일 대비)
          </div>
        ) : (
          <div className={"stat-delta " + (isUp ? "up" : "down")}>{deltaText}</div>
        )}
        {spark && <div style={{ width: 80 }}><MiniSpark data={spark} height={28} /></div>}
      </div>
    </div>
  );
}

function QuickAction({ icon, label, desc, onClick, accent }) {
  return (
    <button onClick={onClick} style={{
      display: "flex", alignItems: "center", gap: 12, padding: "10px 12px",
      borderRadius: 8, transition: "background 0.1s", textAlign: "left", width: "100%",
      cursor: "pointer", border: "1px solid transparent", background: accent ? "var(--accent-soft)" : "transparent",
    }} onMouseEnter={e => { if (!accent) e.currentTarget.style.background = "var(--surface-hover)"; }}
       onMouseLeave={e => { if (!accent) e.currentTarget.style.background = "transparent"; }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8,
        background: accent ? "var(--accent)" : "var(--bg-elev)",
        color: accent ? "white" : "var(--text)",
        display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
      }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>{label}</div>
        <div className="text-xs muted">{desc}</div>
      </div>
      <window.I.ChevronRight size={14} className="muted" />
    </button>
  );
}

window.Dashboard = Dashboard;
