// === Dashboard screen ===
function Dashboard({ goto }) {
  const { PRODUCTS, ORDERS, SALES_TREND } = window.MOCK;

  const totalRevenue = SALES_TREND.reduce((s, d) => s + d.revenue, 0);
  const totalOrders = SALES_TREND.reduce((s, d) => s + d.orders, 0);
  const todayRevenue = SALES_TREND[SALES_TREND.length - 1].revenue;
  const yesterdayRevenue = SALES_TREND[SALES_TREND.length - 2].revenue;
  const revenueChange = ((todayRevenue - yesterdayRevenue) / yesterdayRevenue) * 100;
  const newOrders = ORDERS.filter(o => o.status === "paid").length;
  const outOfStock = PRODUCTS.filter(p => p.status === "outofstock").length;

  const topProducts = [...PRODUCTS].sort((a, b) => b.sales30d - a.sales30d).slice(0, 5);
  const recentOrders = ORDERS.slice(0, 5);

  // chart bars
  const chartMax = Math.max(...SALES_TREND.map(d => d.revenue));
  const todayD = "05/10";

  return (
    <div className="page">
      <div className="page-header">
        <h1 className="page-title">대시보드</h1>
        <p className="page-desc">2026년 5월 10일 일요일 · 스마트스토어 판매 현황</p>
      </div>

      <div className="stat-grid" style={{ marginBottom: 16 }}>
        <StatTile
          label="오늘의 매출"
          value={formatKRW(todayRevenue)}
          delta={revenueChange}
          icon={<window.I.Wallet size={14} />}
          spark={SALES_TREND.map(d => d.revenue)}
        />
        <StatTile
          label="신규 주문"
          value={`${newOrders}건`}
          deltaText={`발송 대기 ${newOrders}건`}
          deltaPositive
          icon={<window.I.ShoppingCart size={14} />}
        />
        <StatTile
          label="진행 중 상품"
          value={`${PRODUCTS.filter(p => p.status === "active").length}개`}
          deltaText={`품절 ${outOfStock}개`}
          deltaPositive={false}
          icon={<window.I.Package size={14} />}
        />
        <StatTile
          label="14일 누적 매출"
          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 }}>최근 14일</div>
            </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" }}>
            <div style={{ display: "flex", alignItems: "flex-end", gap: 6, height: 200, paddingBottom: 22, position: "relative" }}>
              {SALES_TREND.map((d, i) => {
                const h = (d.revenue / chartMax) * 178;
                const isToday = d.d === todayD;
                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: h,
                        background: isToday ? "var(--accent)" : "var(--accent-soft)",
                        borderRadius: "4px 4px 0 0",
                        position: "relative",
                        transition: "height 0.4s",
                      }} title={`${d.d}: ${formatKRW(d.revenue)}`}>
                        {isToday && (
                          <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={`${ORDERS.filter(o => o.status === "paid").length}건 발송 대기`} 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">베스트 상품 TOP 5</div>
            <button className="btn btn-ghost btn-sm right" onClick={() => goto("products")}>
              전체 <window.I.ChevronRight size={12} />
            </button>
          </div>
          <div>
            {topProducts.map((p, i) => (
              <div key={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>
                <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" }}>{p.name}</div>
                  <div className="text-xs muted">{formatKRW(p.price)} · 재고 {p.stock}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div className="tabular" style={{ fontSize: 13, fontWeight: 600 }}>{p.sales30d}건</div>
                  <div className="text-xs muted">30일 판매</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.map((o, i) => {
              const totalPrice = 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);
              const firstItem = window.MOCK.PRODUCTS.find(x => x.id === o.items[0].pid);
              return (
                <div key={o.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 16px", borderTop: i ? "1px solid var(--border)" : "none" }}>
                  <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" }}>
                      {o.buyer} · {o.items.length === 1 ? firstItem?.name : `${firstItem?.name} 외 ${o.items.length - 1}건`}
                    </div>
                    <div className="text-xs muted">{o.date.split(" ")[1]} · {o.id.slice(-5)}</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;
  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;
