page.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. 'use client';
  2. import { useCallback, useEffect, useState } from 'react';
  3. import Link from 'next/link';
  4. import { useRouter, useSearchParams } from 'next/navigation';
  5. import { Gamepad2, Package, Ticket } from 'lucide-react';
  6. import { fetchApi } from '@/lib/utils/client';
  7. import Loading from '@/app/component/Loading';
  8. import Pagination from '@/app/component/Pagination';
  9. import type {
  10. ProductListResponse,
  11. ProductListRow,
  12. ProductType,
  13. SortKey,
  14. GameOption,
  15. GameListResponse
  16. } from '@/types/store';
  17. import { SORT_OPTIONS } from '@/types/store';
  18. const PER_PAGE = 20;
  19. const TYPE_BADGE_CLASS: Record<ProductType, string> = {
  20. 1: 'bg-sky-100 text-sky-800 dark:bg-sky-900/40 dark:text-sky-300',
  21. 2: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300'
  22. };
  23. const TYPE_LABEL: Record<ProductType, string> = { 1: '실물', 2: '쿠폰' };
  24. function TypeBadge({ type }: { type: ProductType })
  25. {
  26. const Icon = type === 2 ? Ticket : Package;
  27. return (
  28. <span
  29. title={TYPE_LABEL[type]}
  30. aria-label={TYPE_LABEL[type]}
  31. className={`inline-flex items-center justify-center p-1 rounded ${TYPE_BADGE_CLASS[type]}`}
  32. >
  33. <Icon className="size-3" />
  34. </span>
  35. );
  36. }
  37. function formatPrice(n: number): string
  38. {
  39. return n.toLocaleString('ko-KR');
  40. }
  41. export default function StorePage()
  42. {
  43. const router = useRouter();
  44. const search = useSearchParams();
  45. const initialKeyword = search.get('keyword') ?? '';
  46. const initialType = search.get('type') ?? '';
  47. const initialGameID = search.get('gameID') ?? '';
  48. const initialSort = (search.get('sort') as SortKey|null) ?? 'latest';
  49. const initialPage = (() => {
  50. const raw = parseInt(search.get('page') ?? '1', 10);
  51. return Number.isNaN(raw) || raw < 1 ? 1 : raw;
  52. })();
  53. const [products, setProducts] = useState<ProductListRow[]>([]);
  54. const [games, setGames] = useState<GameOption[]>([]);
  55. const [total, setTotal] = useState(0);
  56. const [loading, setLoading] = useState(true);
  57. const [keyword, setKeyword] = useState(initialKeyword);
  58. const [submittedKeyword, setSubmittedKeyword] = useState(initialKeyword);
  59. const [typeFilter, setTypeFilter] = useState<string>(initialType);
  60. const [gameIDFilter, setGameIDFilter] = useState<string>(initialGameID);
  61. const [sort, setSort] = useState<SortKey>(initialSort);
  62. const [page, setPage] = useState<number>(initialPage);
  63. // 게임 목록은 mount 시 1회만 fetch
  64. useEffect(() => {
  65. (async () => {
  66. const res = await fetchApi<GameListResponse>('/api/store/games', { silent: true });
  67. if (res.success && res.data) {
  68. setGames(res.data.list);
  69. }
  70. })();
  71. }, []);
  72. const load = useCallback(async () => {
  73. setLoading(true);
  74. const params = new URLSearchParams();
  75. params.set('page', String(page));
  76. params.set('perPage', String(PER_PAGE));
  77. params.set('sort', sort);
  78. if (submittedKeyword) {
  79. params.set('keyword', submittedKeyword);
  80. }
  81. if (typeFilter) {
  82. params.set('type', typeFilter);
  83. }
  84. if (gameIDFilter) {
  85. params.set('gameID', gameIDFilter);
  86. }
  87. const res = await fetchApi<ProductListResponse>(`/api/store/products?${params.toString()}`, { silent: true });
  88. if (res.success && res.data) {
  89. setProducts(res.data.list);
  90. setTotal(res.data.total);
  91. }
  92. else {
  93. setProducts([]);
  94. setTotal(0);
  95. }
  96. setLoading(false);
  97. }, [submittedKeyword, typeFilter, gameIDFilter, sort, page]);
  98. // 필터/정렬/게임/검색 키워드 변경 시 1페이지로 리셋
  99. useEffect(() => {
  100. setPage(1);
  101. }, [sort, typeFilter, gameIDFilter, submittedKeyword]);
  102. // page 변경 또는 의존 필터/검색 변경 시 자동 재조회
  103. useEffect(() => {
  104. load();
  105. }, [sort, typeFilter, gameIDFilter, submittedKeyword, page]); // eslint-disable-line react-hooks/exhaustive-deps
  106. const syncUrl = useCallback((nextPage: number, kw: string = submittedKeyword) => {
  107. const params = new URLSearchParams();
  108. if (kw) {
  109. params.set('keyword', kw);
  110. }
  111. if (typeFilter) {
  112. params.set('type', typeFilter);
  113. }
  114. if (gameIDFilter) {
  115. params.set('gameID', gameIDFilter);
  116. }
  117. if (sort !== 'latest') {
  118. params.set('sort', sort);
  119. }
  120. if (nextPage > 1) {
  121. params.set('page', String(nextPage));
  122. }
  123. router.replace(`/store${params.toString() ? `?${params.toString()}` : ''}`);
  124. }, [submittedKeyword, typeFilter, gameIDFilter, sort, router]);
  125. const handleSearch = (e: React.FormEvent) => {
  126. e.preventDefault();
  127. const trimmed = keyword.trim();
  128. setSubmittedKeyword(trimmed);
  129. setPage(1);
  130. syncUrl(1, trimmed);
  131. };
  132. const handlePageChange = (next: number) => {
  133. setPage(next);
  134. syncUrl(next);
  135. if (typeof window !== 'undefined') {
  136. window.scrollTo({ top: 0, behavior: 'smooth' });
  137. }
  138. };
  139. return (
  140. <div className="mx-auto px-2 sm:px-4 py-6">
  141. <h1 className="text-2xl font-bold mb-4">
  142. 상점{' '}
  143. <span className="text-red-600 dark:text-red-400 text-xl font-extrabold">
  144. ({total.toLocaleString()}개)
  145. </span>
  146. </h1>
  147. <form onSubmit={handleSearch} className="mb-6 space-y-2 sm:space-y-0 sm:flex sm:flex-wrap sm:items-center sm:gap-2">
  148. <div className="grid grid-cols-3 gap-2 sm:contents">
  149. <select
  150. title="sort"
  151. value={sort}
  152. onChange={(e) => { setSort(e.target.value as SortKey); }}
  153. className="w-full sm:w-auto border rounded px-3 py-2 text-sm bg-white dark:bg-neutral-900"
  154. >
  155. {SORT_OPTIONS.map(o => (
  156. <option key={o.value} value={o.value}>{o.label}</option>
  157. ))}
  158. </select>
  159. <select
  160. title="gameID"
  161. value={gameIDFilter}
  162. onChange={(e) => { setGameIDFilter(e.target.value); }}
  163. className="w-full sm:w-auto border rounded px-3 py-2 text-sm bg-white dark:bg-neutral-900"
  164. >
  165. <option value="">전체 게임</option>
  166. {games.map(g => (
  167. <option key={g.id} value={g.id}>{g.korName}</option>
  168. ))}
  169. </select>
  170. <select
  171. title="type"
  172. value={typeFilter}
  173. onChange={(e) => { setTypeFilter(e.target.value); }}
  174. className="w-full sm:w-auto border rounded px-3 py-2 text-sm bg-white dark:bg-neutral-900"
  175. >
  176. <option value="">전체 유형</option>
  177. <option value="1">실물</option>
  178. <option value="2">쿠폰</option>
  179. </select>
  180. </div>
  181. <input
  182. type="search"
  183. value={keyword}
  184. onChange={(e) => { setKeyword(e.target.value); }}
  185. placeholder="상품명 또는 게임 검색"
  186. className="w-full sm:flex-1 border rounded px-3 py-2 text-sm bg-white dark:bg-neutral-900"
  187. maxLength={100}
  188. />
  189. <button type="submit" className="w-full sm:w-auto bg-blue-600 text-white px-4 py-2 rounded text-sm hover:bg-blue-700">
  190. 검색
  191. </button>
  192. </form>
  193. {loading ? (
  194. <Loading />
  195. ) : products.length === 0 ? (
  196. <div className="text-center py-20 text-neutral-500">판매 중인 상품이 없습니다.</div>
  197. ) : (
  198. <>
  199. <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
  200. {products.map((p) => (
  201. <Link
  202. key={p.id}
  203. href={`/store/${p.id}`}
  204. className="group block rounded-lg border border-neutral-200 dark:border-neutral-800 overflow-hidden hover:shadow-lg transition-shadow bg-white dark:bg-neutral-900"
  205. >
  206. <div className="aspect-square bg-neutral-100 dark:bg-neutral-800 overflow-hidden flex items-center justify-center relative">
  207. {p.thumbnail ? (
  208. // eslint-disable-next-line @next/next/no-img-element
  209. <img
  210. src={p.thumbnail}
  211. alt={p.name}
  212. className="w-full h-full max-w-[calc(100%/1.6)] object-scale-down group-hover:scale-105 transition-transform duration-300"
  213. />
  214. ) : (
  215. <span className="text-neutral-400 text-xs">이미지 없음</span>
  216. )}
  217. {p.stock === 0 && (
  218. <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
  219. <span className="text-white text-sm font-bold tracking-widest">SOLD OUT</span>
  220. </div>
  221. )}
  222. </div>
  223. <div className="p-3">
  224. <div className="flex items-center gap-1.5 mb-1.5">
  225. <TypeBadge type={p.type} />
  226. <Gamepad2 className="size-3.5 shrink-0 text-purple-600 dark:text-purple-400" />
  227. <span className="text-xs font-semibold truncate text-purple-600 dark:text-purple-400" title={p.gameName}>
  228. {p.gameName}
  229. </span>
  230. </div>
  231. <div className="text-sm font-semibold mb-1.5 line-clamp-2 min-h-[1.6rem]" title={p.name}>
  232. {p.name}
  233. </div>
  234. {p.discountType !== 0 && p.salePrice !== p.price ? (
  235. <>
  236. <div className="text-lg font-extrabold text-red-600 dark:text-red-400">
  237. {formatPrice(p.salePrice)}P
  238. </div>
  239. <div className="flex items-baseline gap-1.5 text-xs">
  240. <span className="line-through text-yellow-600 dark:text-yellow-400">{formatPrice(p.price)}P</span>
  241. <span className="font-semibold text-green-600 dark:text-green-400">
  242. {p.discountType === 1 ? `-${p.discountValue}%` : `-${formatPrice(p.discountValue)}P`}
  243. </span>
  244. </div>
  245. </>
  246. ) : (
  247. <div className="text-lg font-extrabold text-red-600 dark:text-red-400">
  248. {formatPrice(p.price)}P
  249. </div>
  250. )}
  251. </div>
  252. </Link>
  253. ))}
  254. </div>
  255. <hr className="my-4 border-neutral-200 dark:border-neutral-800" />
  256. <Pagination total={total} page={page} perPage={PER_PAGE} onChange={handlePageChange} />
  257. </>
  258. )}
  259. </div>
  260. );
  261. }