"use client";

/**
 * DataGrid — 하드코딩 페이지용 공통 데이터 테이블 컴포넌트
 *
 * 기능:
 * - 드래그로 컬럼 순서 변경 (@dnd-kit)
 * - 컬럼 헤더 클릭 정렬 (asc/desc)
 * - 컬럼 헤더 필터: 필터 아이콘 → Popover → 고유값 체크박스 다중 선택
 * - 셀 더블클릭 인라인 편집 (text/number/date/select)
 * - 천단위 구분자 (number 타입)
 * - 셀 값 truncate + tooltip
 */

import React, { useState, useEffect, useRef, useCallback, useMemo } from "react";
import {
  DndContext, closestCenter, PointerSensor, useSensor, useSensors, DragEndEvent,
} from "@dnd-kit/core";
import { SortableContext, horizontalListSortingStrategy, useSortable, arrayMove } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Input } from "@/components/ui/input";
import { Filter, Check, Search, ImageIcon, X, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { apiClient } from "@/lib/api/client";

// --- 타입 ---

export interface DataGridColumn {
  key: string;
  label: string;
  width?: string;
  minWidth?: string;
  editable?: boolean;
  inputType?: "text" | "number" | "date" | "select";
  sortable?: boolean;
  filterable?: boolean;
  truncate?: boolean;
  align?: "left" | "center" | "right";
  formatNumber?: boolean;
  /** 이미지 타입 — 값을 /api/files/preview/{objid} 이미지로 렌더링 */
  renderType?: "image";
  selectOptions?: { value: string; label: string }[];
}

export interface DataGridProps {
  columns: DataGridColumn[];
  data: any[];
  onRowClick?: (row: any, index: number) => void;
  onRowDoubleClick?: (row: any, index: number) => void;
  selectedId?: string | null;
  onSelect?: (id: string | null) => void;
  onCellEdit?: (rowId: string, columnKey: string, newValue: any, row: any) => void;
  tableName?: string;
  showRowNumber?: boolean;
  /** 체크박스 다중선택 모드 */
  showCheckbox?: boolean;
  /** 체크된 행 ID 배열 */
  checkedIds?: string[];
  /** 체크 변경 콜백 */
  onCheckedChange?: (ids: string[]) => void;
  emptyMessage?: string;
  loading?: boolean;
  onColumnOrderChange?: (columns: DataGridColumn[]) => void;
  gridId?: string;
  /** 페이지네이션 표시 여부 (기본: true) */
  showPagination?: boolean;
  /** 초기 페이지 크기 (기본: 50) */
  defaultPageSize?: number;
}

const fmtNum = (val: any) => {
  if (val == null || val === "") return "";
  const n = Number(String(val).replace(/,/g, ""));
  if (isNaN(n)) return String(val);
  return n.toLocaleString();
};

// --- Sortable Header Cell ---
function SortableHeaderCell({
  col, sortKey, sortDir, onSort,
  headerFilterValues, uniqueValues, onToggleFilter, onClearFilter,
}: {
  col: DataGridColumn;
  sortKey: string | null;
  sortDir: "asc" | "desc";
  onSort: (key: string) => void;
  headerFilterValues: Set<string>;
  uniqueValues: string[];
  onToggleFilter: (colKey: string, value: string) => void;
  onClearFilter: (colKey: string) => void;
}) {
  const [filterSearch, setFilterSearch] = useState("");
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: col.key });

  const style: React.CSSProperties = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
    cursor: "grab",
  };

  const isSorted = sortKey === col.key;
  const hasFilter = headerFilterValues.size > 0;

  return (
    <TableHead
      ref={setNodeRef}
      style={style}
      className={cn(col.width, col.minWidth, "select-none relative")}
    >
      <div className="inline-flex items-center gap-1">
        <div
          {...attributes}
          {...listeners}
          className="flex items-center gap-0.5 cursor-pointer min-w-0"
          onClick={(e) => {
            e.stopPropagation();
            if (col.sortable !== false) onSort(col.key);
          }}
        >
          <span className="text-xs font-medium truncate">{col.label}</span>
          {isSorted && (
            <span className="text-primary text-xs shrink-0">{sortDir === "asc" ? "↑" : "↓"}</span>
          )}
        </div>

        {/* 컬럼 필터 아이콘 → Popover */}
        {col.filterable !== false && uniqueValues.length > 0 && (
          <Popover>
            <PopoverTrigger asChild>
              <button
                onClick={(e) => e.stopPropagation()}
                className={cn(
                  "hover:bg-primary/20 rounded p-0.5 transition-colors shrink-0",
                  hasFilter && "text-primary bg-primary/10",
                )}
                title="필터"
              >
                <Filter className="h-3 w-3" />
              </button>
            </PopoverTrigger>
            <PopoverContent className="w-52 p-2" align="start" onClick={(e) => e.stopPropagation()}>
              <div className="space-y-2">
                <div className="flex items-center justify-between border-b pb-2">
                  <span className="text-xs font-medium">필터: {col.label}</span>
                  {hasFilter && (
                    <button onClick={() => onClearFilter(col.key)} className="text-destructive text-xs hover:underline">
                      초기화
                    </button>
                  )}
                </div>
                {/* 검색 */}
                <div className="relative">
                  <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground" />
                  <Input
                    value={filterSearch}
                    onChange={(e) => setFilterSearch(e.target.value)}
                    placeholder="검색..."
                    className="h-7 text-xs pl-7"
                  />
                </div>
                <div className="max-h-48 space-y-1 overflow-y-auto">
                  {uniqueValues
                    .filter((v) => !filterSearch || v.toLowerCase().includes(filterSearch.toLowerCase()))
                    .slice(0, 50).map((val) => {
                    const isSelected = headerFilterValues.has(val);
                    return (
                      <div
                        key={val}
                        className={cn(
                          "hover:bg-muted flex cursor-pointer items-center gap-2 rounded px-2 py-1 text-xs",
                          isSelected && "bg-primary/10",
                        )}
                        onClick={() => onToggleFilter(col.key, val)}
                      >
                        <div className={cn(
                          "flex h-4 w-4 items-center justify-center rounded border shrink-0",
                          isSelected ? "bg-primary border-primary" : "border-input",
                        )}>
                          {isSelected && <Check className="text-primary-foreground h-3 w-3" />}
                        </div>
                        <span className="truncate">{val || "(빈 값)"}</span>
                      </div>
                    );
                  })}
                  {uniqueValues.filter((v) => !filterSearch || v.toLowerCase().includes(filterSearch.toLowerCase())).length > 50 && (
                    <div className="text-muted-foreground px-2 py-1 text-xs">
                      ...외 {uniqueValues.filter((v) => !filterSearch || v.toLowerCase().includes(filterSearch.toLowerCase())).length - 50}개
                    </div>
                  )}
                </div>
              </div>
            </PopoverContent>
          </Popover>
        )}
      </div>
    </TableHead>
  );
}

// --- DataGrid ---

export function DataGrid({
  columns: initialColumns,
  data,
  onRowClick,
  onRowDoubleClick,
  selectedId,
  onSelect,
  onCellEdit,
  tableName,
  showRowNumber = true,
  showCheckbox = false,
  checkedIds = [],
  onCheckedChange,
  emptyMessage = "데이터가 없습니다",
  loading = false,
  onColumnOrderChange,
  gridId,
  showPagination = true,
  defaultPageSize = 50,
}: DataGridProps) {
  const [columns, setColumns] = useState(initialColumns);
  useEffect(() => { setColumns(initialColumns); }, [initialColumns]);

  // 정렬
  const [sortKey, setSortKey] = useState<string | null>(null);
  const [sortDir, setSortDir] = useState<"asc" | "desc">("asc");

  // 헤더 필터 (컬럼별 선택된 값 Set)
  const [headerFilters, setHeaderFilters] = useState<Record<string, Set<string>>>({});

  // 페이지네이션
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(defaultPageSize);
  const [pageSizeInput, setPageSizeInput] = useState(String(defaultPageSize));

  // 인라인 편집
  const [editingCell, setEditingCell] = useState<{ rowIdx: number; colKey: string } | null>(null);
  // 이미지 확대 모달
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [editValue, setEditValue] = useState("");
  const editRef = useRef<HTMLInputElement>(null);

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 8 } })
  );

  // localStorage에서 컬럼 순서 복원
  useEffect(() => {
    if (!gridId) return;
    const saved = localStorage.getItem(`datagrid_col_order_${gridId}`);
    if (saved) {
      try {
        const order = JSON.parse(saved) as string[];
        const reordered = order
          .map((key) => initialColumns.find((c) => c.key === key))
          .filter(Boolean) as DataGridColumn[];
        const remaining = initialColumns.filter((c) => !order.includes(c.key));
        setColumns([...reordered, ...remaining]);
      } catch { /* skip */ }
    }
  }, [gridId]); // eslint-disable-line react-hooks/exhaustive-deps

  // 컬럼별 고유값 계산 (필터 팝오버용)
  const columnUniqueValues = useMemo(() => {
    const result: Record<string, string[]> = {};
    for (const col of columns) {
      const values = new Set<string>();
      data.forEach((row) => {
        const val = row[col.key];
        if (val !== null && val !== undefined && val !== "") {
          values.add(String(val));
        }
      });
      result[col.key] = Array.from(values).sort();
    }
    return result;
  }, [data, columns]);

  // 드래그 완료
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (!over || active.id === over.id) return;
    setColumns((prev) => {
      const oldIndex = prev.findIndex((c) => c.key === active.id);
      const newIndex = prev.findIndex((c) => c.key === over.id);
      const next = arrayMove(prev, oldIndex, newIndex);
      if (gridId) localStorage.setItem(`datagrid_col_order_${gridId}`, JSON.stringify(next.map((c) => c.key)));
      onColumnOrderChange?.(next);
      return next;
    });
  };

  // 정렬
  const handleSort = (key: string) => {
    if (sortKey === key) setSortDir((d) => (d === "asc" ? "desc" : "asc"));
    else { setSortKey(key); setSortDir("asc"); }
  };

  // 헤더 필터 토글
  const toggleHeaderFilter = (colKey: string, value: string) => {
    setHeaderFilters((prev) => {
      const next = { ...prev };
      const set = new Set(next[colKey] || []);
      if (set.has(value)) set.delete(value); else set.add(value);
      if (set.size === 0) delete next[colKey]; else next[colKey] = set;
      return next;
    });
  };

  const clearHeaderFilter = (colKey: string) => {
    setHeaderFilters((prev) => {
      const next = { ...prev };
      delete next[colKey];
      return next;
    });
  };

  // 필터 + 정렬 적용
  const processedData = useMemo(() => {
    let result = [...data];

    // 헤더 필터 적용
    if (Object.keys(headerFilters).length > 0) {
      result = result.filter((row) => {
        return Object.entries(headerFilters).every(([colKey, values]) => {
          if (values.size === 0) return true;
          const cellVal = row[colKey] != null ? String(row[colKey]) : "";
          return values.has(cellVal);
        });
      });
    }

    // 정렬
    if (sortKey) {
      result.sort((a, b) => {
        const av = a[sortKey] ?? "";
        const bv = b[sortKey] ?? "";
        const na = Number(av);
        const nb = Number(bv);
        if (!isNaN(na) && !isNaN(nb)) return sortDir === "asc" ? na - nb : nb - na;
        return sortDir === "asc" ? String(av).localeCompare(String(bv)) : String(bv).localeCompare(String(av));
      });
    }

    return result;
  }, [data, headerFilters, sortKey, sortDir]);

  // 필터/데이터 변경 시 1페이지로 리셋
  useEffect(() => {
    setCurrentPage(1);
  }, [data, headerFilters]);

  // 페이지네이션 계산
  const totalItems = processedData.length;
  const totalPages = Math.max(1, Math.ceil(totalItems / pageSize));
  const safePage = Math.min(currentPage, totalPages);

  useEffect(() => {
    if (currentPage > totalPages) setCurrentPage(totalPages);
  }, [currentPage, totalPages]);

  const pageOffset = (safePage - 1) * pageSize;
  const paginatedData = showPagination
    ? processedData.slice(pageOffset, pageOffset + pageSize)
    : processedData;

  // 페이지 크기 입력 적용
  const applyPageSize = () => {
    const n = parseInt(pageSizeInput, 10);
    if (!isNaN(n) && n >= 1) {
      setPageSize(n);
      setCurrentPage(1);
      setPageSizeInput(String(n));
    } else {
      setPageSizeInput(String(pageSize));
    }
  };

  // 페이지 번호 배열 생성
  const getPageNumbers = () => {
    const delta = 2;
    let start = Math.max(1, safePage - delta);
    let end = Math.min(totalPages, safePage + delta);
    if (end - start < delta * 2) {
      if (start === 1) end = Math.min(totalPages, start + delta * 2);
      else if (end === totalPages) start = Math.max(1, end - delta * 2);
    }
    const pages: (number | "...")[] = [];
    if (start > 1) { pages.push(1); if (start > 2) pages.push("..."); }
    for (let i = start; i <= end; i++) pages.push(i);
    if (end < totalPages) { if (end < totalPages - 1) pages.push("..."); pages.push(totalPages); }
    return pages;
  };

  // 인라인 편집
  const startEdit = (rowIdx: number, colKey: string, currentVal: any) => {
    const col = columns.find((c) => c.key === colKey);
    if (!col?.editable) return;
    setEditingCell({ rowIdx, colKey });
    setEditValue(currentVal != null ? String(currentVal) : "");
  };

  const saveEdit = useCallback(async () => {
    if (!editingCell) return;
    const { rowIdx, colKey } = editingCell;
    const row = paginatedData[rowIdx];
    if (!row) { setEditingCell(null); return; }

    const originalVal = String(row[colKey] ?? "");
    if (originalVal === editValue) { setEditingCell(null); return; }

    if (tableName && row.id) {
      try {
        await apiClient.put(`/table-management/tables/${tableName}/edit`, {
          originalData: { id: row.id },
          updatedData: { [colKey]: editValue || null },
        });
        row[colKey] = editValue;
        toast.success("저장됨");
      } catch (err) {
        toast.error("저장에 실패했습니다.");
        setEditingCell(null);
        return;
      }
    }

    onCellEdit?.(row.id, colKey, editValue, row);
    setEditingCell(null);
  }, [editingCell, editValue, paginatedData, tableName, onCellEdit]);

  const cancelEdit = () => setEditingCell(null);

  const handleEditKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") { e.preventDefault(); saveEdit(); }
    else if (e.key === "Escape") { e.preventDefault(); cancelEdit(); }
    else if (e.key === "Tab") { e.preventDefault(); saveEdit(); }
  };

  useEffect(() => {
    if (editingCell && editRef.current) {
      editRef.current.focus();
      editRef.current.select();
    }
  }, [editingCell]);

  // 셀 렌더링
  const renderCell = (row: any, col: DataGridColumn, rowIdx: number) => {
    const isEditing = editingCell?.rowIdx === rowIdx && editingCell?.colKey === col.key;
    const val = row[col.key];

    if (isEditing) {
      if (col.inputType === "select" && col.selectOptions) {
        return (
          <select ref={editRef as any} value={editValue} onChange={(e) => setEditValue(e.target.value)}
            onKeyDown={handleEditKeyDown} onBlur={saveEdit}
            className="h-7 w-full rounded border border-primary bg-background px-1.5 text-xs focus:ring-1">
            <option value="">선택</option>
            {col.selectOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        );
      }
      return (
        <input ref={editRef} type={col.inputType === "date" ? "date" : "text"}
          value={editValue} onChange={(e) => setEditValue(e.target.value)}
          onKeyDown={handleEditKeyDown} onBlur={saveEdit}
          className={cn("h-7 w-full rounded border border-primary bg-background px-1.5 text-xs focus:ring-1",
            col.align === "right" && "text-right")} />
      );
    }

    // 이미지 타입
    if (col.renderType === "image" && val) {
      const src = (val.startsWith("http") || val.startsWith("/")) ? val : `/api/files/preview/${val}`;
      return (
        <img src={src} alt="" className="h-10 w-10 rounded object-cover cursor-pointer hover:ring-2 hover:ring-primary transition-all"
          onClick={(e) => { e.stopPropagation(); setPreviewImage(src); }} />
      );
    }
    if (col.renderType === "image" && !val) {
      return <div className="h-10 w-10 rounded bg-muted flex items-center justify-center"><ImageIcon className="h-4 w-4 text-muted-foreground/30" /></div>;
    }

    let display = val ?? "";
    if (col.formatNumber || col.inputType === "number") display = fmtNum(val);
    const truncateClass = col.truncate !== false ? "block truncate" : "";

    return (
      <span className={cn("text-xs", truncateClass, col.align === "right" && "text-right w-full inline-block")}
        title={String(val ?? "")}>
        {display}
      </span>
    );
  };

  return (
    <div className="flex flex-col h-full flex-1 min-h-0">
      <div className="flex-1 min-h-0 overflow-auto">
      <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
        <Table noWrapper>
          <TableHeader className="sticky top-0 bg-background z-10 shadow-[0_1px_0_0_hsl(var(--border))]">
            <SortableContext items={columns.map((c) => c.key)} strategy={horizontalListSortingStrategy}>
              <TableRow>
                {showCheckbox && (
                  <TableHead className="w-[40px] text-center">
                    <Checkbox
                      checked={processedData.length > 0 && checkedIds.length === processedData.length}
                      onCheckedChange={(checked) => {
                        onCheckedChange?.(checked ? processedData.map((r) => r.id) : []);
                      }}
                    />
                  </TableHead>
                )}
                {showRowNumber && !showCheckbox && <TableHead className="w-[40px] text-center text-xs">No</TableHead>}
                {columns.map((col) => (
                  <SortableHeaderCell
                    key={col.key}
                    col={col}
                    sortKey={sortKey}
                    sortDir={sortDir}
                    onSort={handleSort}
                    headerFilterValues={headerFilters[col.key] || new Set()}
                    uniqueValues={columnUniqueValues[col.key] || []}
                    onToggleFilter={toggleHeaderFilter}
                    onClearFilter={clearHeaderFilter}
                  />
                ))}
              </TableRow>
            </SortableContext>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={columns.length + 1} className="text-center py-8 text-muted-foreground">
                  로딩 중...
                </TableCell>
              </TableRow>
            ) : paginatedData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={columns.length + 1} className="text-center py-8 text-muted-foreground">
                  {emptyMessage}
                </TableCell>
              </TableRow>
            ) : paginatedData.map((row, rowIdx) => (
              <TableRow
                key={row.id || rowIdx}
                className={cn("cursor-pointer",
                  selectedId === row.id && "bg-primary/5",
                  showCheckbox && checkedIds.includes(row.id) && "bg-primary/5",
                )}
                onClick={() => {
                  onSelect?.(row.id);
                  onRowClick?.(row, rowIdx);
                  // 체크박스 모드에서는 행 클릭으로 체크 토글
                  if (showCheckbox && onCheckedChange) {
                    const next = checkedIds.includes(row.id)
                      ? checkedIds.filter((id) => id !== row.id)
                      : [...checkedIds, row.id];
                    onCheckedChange(next);
                  }
                }}
                onDoubleClick={() => onRowDoubleClick?.(row, rowIdx)}
              >
                {showCheckbox && (
                  <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
                    <Checkbox
                      checked={checkedIds.includes(row.id)}
                      onCheckedChange={(checked) => {
                        const next = checked
                          ? [...checkedIds, row.id]
                          : checkedIds.filter((id) => id !== row.id);
                        onCheckedChange?.(next);
                      }}
                    />
                  </TableCell>
                )}
                {showRowNumber && !showCheckbox && <TableCell className="text-center text-[10px] text-muted-foreground">{pageOffset + rowIdx + 1}</TableCell>}
                {columns.map((col) => (
                  <TableCell
                    key={col.key}
                    className={cn(col.width, col.minWidth, "py-2.5", col.editable && "cursor-text")}
                    onDoubleClick={(e) => {
                      if (col.editable) {
                        e.stopPropagation();
                        startEdit(rowIdx, col.key, row[col.key]);
                      }
                    }}
                  >
                    {renderCell(row, col, rowIdx)}
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </DndContext>
      </div>

      {/* 페이지네이션 footer */}
      {showPagination && (
        <div className="flex items-center justify-between border-t px-3 py-2 text-xs text-muted-foreground shrink-0">
          {/* 좌측: 데이터 수량 + 페이지 크기 입력 */}
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-1">
              <span>전체</span>
              <span className="font-medium text-foreground">{totalItems.toLocaleString()}</span>
              <span>건</span>
            </div>
            <div className="flex items-center gap-1.5">
              <Input
                type="number"
                min={1}
                value={pageSizeInput}
                onChange={(e) => setPageSizeInput(e.target.value)}
                onBlur={applyPageSize}
                onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); applyPageSize(); } }}
                className="h-7 w-16 text-center text-xs"
              />
              <span>건씩 보기</span>
            </div>
          </div>

          {/* 중앙: 페이지 이동 버튼 */}
          <div className="flex items-center gap-0.5">
            <button onClick={() => setCurrentPage(1)} disabled={safePage === 1}
              className="h-7 w-7 flex items-center justify-center rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed" title="첫 페이지">
              <ChevronsLeft className="h-3.5 w-3.5" />
            </button>
            <button onClick={() => setCurrentPage((p) => Math.max(1, p - 1))} disabled={safePage === 1}
              className="h-7 w-7 flex items-center justify-center rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed" title="이전 페이지">
              <ChevronLeft className="h-3.5 w-3.5" />
            </button>
            {getPageNumbers().map((page, idx) =>
              page === "..." ? (
                <span key={`dot-${idx}`} className="h-7 w-7 flex items-center justify-center text-muted-foreground">...</span>
              ) : (
                <button key={page} onClick={() => setCurrentPage(page as number)}
                  className={cn("h-7 w-7 flex items-center justify-center rounded text-xs",
                    page === safePage ? "bg-primary text-primary-foreground font-medium" : "hover:bg-muted")}>
                  {page}
                </button>
              )
            )}
            <button onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))} disabled={safePage === totalPages}
              className="h-7 w-7 flex items-center justify-center rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed" title="다음 페이지">
              <ChevronRight className="h-3.5 w-3.5" />
            </button>
            <button onClick={() => setCurrentPage(totalPages)} disabled={safePage === totalPages}
              className="h-7 w-7 flex items-center justify-center rounded hover:bg-muted disabled:opacity-30 disabled:cursor-not-allowed" title="마지막 페이지">
              <ChevronsRight className="h-3.5 w-3.5" />
            </button>
          </div>

          {/* 우측: 좌측과 균형용 빈 공간 */}
          <div className="flex items-center gap-3 invisible">
            <div className="flex items-center gap-1">
              <span>전체</span>
              <span>{totalItems.toLocaleString()}</span>
              <span>건</span>
            </div>
            <div className="flex items-center gap-1.5">
              <div className="h-7 w-16" />
              <span>건씩 보기</span>
            </div>
          </div>
        </div>
      )}

      {/* 이미지 확대 모달 */}
      {previewImage && (
        <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/70"
          onClick={() => setPreviewImage(null)}>
          <div className="relative max-w-[90vw] max-h-[90vh]">
            <img src={previewImage} alt="" className="max-w-full max-h-[85vh] rounded-lg object-contain" />
            <button className="absolute -top-3 -right-3 bg-background rounded-full p-1 shadow-lg hover:bg-muted"
              onClick={() => setPreviewImage(null)}>
              <X className="h-5 w-5" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
