import { useState, useEffect } from 'react';
import {
  FileText,
  Search,
  RefreshCw,
  Calendar,
  Edit3,
  User,
  Plus,
  MessageSquare,
  ChevronRight,
  X,
} from 'lucide-react';
import { comms } from '@/communication';
import { BoardItem } from '@/types';
import { clsx } from 'clsx';

interface BoardListProps {
  bidx: number;
  title: string;
  icon?: React.ReactNode;
  defaultCategory?: string;
  categories?: { value: string; label: string; color: string }[];
}

export function BoardList({
  bidx,
  title,
  icon = <FileText className="w-5 h-5" />,
  defaultCategory = 'PATCH',
  categories = [
    { value: 'PATCH', label: 'PATCH', color: 'red' },
    { value: 'UPDATE', label: 'UPDATE', color: 'lime' }
  ]
}: BoardListProps) {
  const [boardList, setBoardList] = useState<BoardItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchKey, setSearchKey] = useState('');
  const [selectedItem, setSelectedItem] = useState<BoardItem | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showReplyModal, setShowReplyModal] = useState(false);
  const [editFormData, setEditFormData] = useState<BoardItem | null>(null);
  const [userLevel, setUserLevel] = useState(0);
  const [userId, setUserId] = useState('');
  const [replies, setReplies] = useState<BoardItem[]>([]); // 댓글 목록 (is_comment=true)
  const [replyPosts, setReplyPosts] = useState<BoardItem[]>([]); // 답글 목록 (is_comment=false)
  const [commentText, setCommentText] = useState('');
  const [replyFormData, setReplyFormData] = useState<{ title: string; contents: string }>({ title: '', contents: '' });

  useEffect(() => {
    loadUserInfo();
    loadData();
  }, []);

  // ESC 키 처리
  useEffect(() => {
    const handleEscKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        if (showReplyModal) {
          setShowReplyModal(false);
        } else if (showEditModal) {
          setShowEditModal(false);
        } else if (showModal) {
          setShowModal(false);
        }
      }
    };

    document.addEventListener('keydown', handleEscKey);
    return () => document.removeEventListener('keydown', handleEscKey);
  }, [showModal, showEditModal, showReplyModal]);

  const loadUserInfo = async () => {
    try {
      const response = await comms.checkLoginStatus();
      if (response.Success && response.User) {
        setUserLevel(response.User.Level);
        setUserId(response.User.Id);
      }
    } catch (error) {
      console.error('사용자 정보 로드 오류:', error);
    }
  };

  const loadData = async () => {
    setLoading(true);
    try {
      console.log('게시판 조회:', { bidx, searchKey });
      const response = await comms.getBoardList(bidx, searchKey);
      console.log('게시판 응답:', response);
      if (response.Success && response.Data) {
        setBoardList(response.Data);
      } else {
        console.warn('게시판 없음:', response.Message);
        setBoardList([]);
      }
    } catch (error) {
      console.error('게시판 로드 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    loadData();
  };

  const loadReplies = async (rootIdx: number) => {
    try {
      const response = await comms.getBoardReplies(rootIdx);
      if (response.Success && response.Data) {
        setReplies(response.Data);
      } else {
        setReplies([]);
      }
    } catch (error) {
      console.error('댓글 로드 오류:', error);
      setReplies([]);
    }
  };

  const loadReplyPosts = async (rootIdx: number) => {
    try {
      // 목록에서 해당 root_idx의 답글들만 필터링
      const replyList = boardList.filter(item => item.root_idx === rootIdx && !item.is_comment);
      setReplyPosts(replyList);
    } catch (error) {
      console.error('답글 로드 오류:', error);
      setReplyPosts([]);
    }
  };

  const handleAddComment = async () => {
    if (!selectedItem || !commentText.trim()) return;

    try {
      const response = await comms.addBoardReply(selectedItem.idx, selectedItem.idx, '', commentText, true);
      if (response.Success) {
        setCommentText('');
        loadReplies(selectedItem.idx);
        // reply_count 업데이트를 위해 목록 새로고침
        loadData();
      } else {
        alert(response.Message || '댓글 등록에 실패했습니다.');
      }
    } catch (error) {
      console.error('댓글 등록 오류:', error);
      alert('댓글 등록 중 오류가 발생했습니다.');
    }
  };

  const handleAddReply = async () => {
    if (!selectedItem || !replyFormData.title.trim() || !replyFormData.contents.trim()) {
      alert('제목과 내용을 입력해주세요.');
      return;
    }

    try {
      // 답글은 is_comment=false, title 포함
      const rootIdx = selectedItem.root_idx || selectedItem.idx;
      const response = await comms.addBoardReply(rootIdx, selectedItem.idx, replyFormData.title, replyFormData.contents, false);
      if (response.Success) {
        setShowReplyModal(false);
        setReplyFormData({ title: '', contents: '' });
        await loadData(); // 목록 새로고침
        loadReplyPosts(rootIdx); // 답글 목록 새로고침
      } else {
        alert(response.Message || '답글 등록에 실패했습니다.');
      }
    } catch (error) {
      console.error('답글 등록 오류:', error);
      alert('답글 등록 중 오류가 발생했습니다.');
    }
  };

  const handleRowClick = async (item: BoardItem) => {
    try {
      const response = await comms.getBoardDetail(item.idx);
      if (response.Success && response.Data) {
        setSelectedItem(response.Data);
        const rootIdx = response.Data.root_idx || response.Data.idx;
        loadReplies(rootIdx); // 댓글 로드
        loadReplyPosts(rootIdx); // 답글 로드
        setShowModal(true); // 모두 뷰어로 보기
      }
    } catch (error) {
      console.error('상세 조회 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    }
  };

  const handleEditClick = () => {
    if (selectedItem) {
      setEditFormData(selectedItem);
      setShowModal(false);
      setShowEditModal(true);
    }
  };

  const handleEditSave = async () => {
    if (!editFormData) return;

    try {
      const isNew = editFormData.idx === 0;

      if (isNew) {
        // 신규 등록
        const response = await comms.addBoard(
          bidx,
          editFormData.header || '',
          editFormData.cate || '',
          editFormData.title || '',
          editFormData.contents || ''
        );

        if (response.Success) {
          setShowEditModal(false);
          setEditFormData(null);
          loadData();
        } else {
          alert(response.Message || '등록에 실패했습니다.');
        }
      } else {
        // 수정
        const response = await comms.editBoard(
          editFormData.idx,
          editFormData.header || '',
          editFormData.cate || '',
          editFormData.title || '',
          editFormData.contents || ''
        );

        if (response.Success) {
          setShowEditModal(false);
          setEditFormData(null);
          loadData();
        } else {
          alert(response.Message || '수정에 실패했습니다.');
        }
      }
    } catch (error) {
      console.error('저장 오류:', error);
      alert('저장 중 오류가 발생했습니다.');
    }
  };

  const handleDelete = async () => {
    if (!editFormData || editFormData.idx === 0) return;

    if (!confirm('정말 삭제하시겠습니까?')) return;

    try {
      const response = await comms.deleteBoard(editFormData.idx);

      if (response.Success) {
        setShowEditModal(false);
        setEditFormData(null);
        loadData();
      } else {
        alert(response.Message || '삭제에 실패했습니다.');
      }
    } catch (error) {
      console.error('삭제 오류:', error);
      alert('삭제 중 오류가 발생했습니다.');
    }
  };

  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '-';
    try {
      const date = new Date(dateStr);
      const yy = String(date.getFullYear()).slice(-2);
      const mm = String(date.getMonth() + 1).padStart(2, '0');
      const dd = String(date.getDate()).padStart(2, '0');
      return `${yy}.${mm}.${dd}`;
    } catch {
      return dateStr;
    }
  };

  const isNew = (dateStr: string | null) => {
    if (!dateStr) return false;
    try {
      const date = new Date(dateStr);
      const now = new Date();
      const diffTime = now.getTime() - date.getTime();
      const diffDays = diffTime / (1000 * 60 * 60 * 24);
      return diffDays <= 3;
    } catch {
      return false;
    }
  };

  const getCategoryColor = (cate: string) => {
    const category = categories.find(c => c.value.toUpperCase() === cate.toUpperCase());
    if (!category) return 'bg-gray-500/20 text-gray-400';

    switch (category.color) {
      case 'lime': return 'bg-lime-500/20 text-lime-400';
      case 'red': return 'bg-red-500/20 text-red-400';
      case 'blue': return 'bg-blue-500/20 text-blue-400';
      case 'yellow': return 'bg-yellow-500/20 text-yellow-400';
      default: return 'bg-gray-500/20 text-gray-400';
    }
  };

  return (
    <div className="space-y-6 animate-fade-in">


      {/* 게시판 목록 */}
      <div className="glass-effect rounded-3xl overflow-hidden shadow-2xl border border-white/10">
        <div className="px-6 py-4 border-b border-white/10 flex flex-col md:flex-row items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-primary-500/20 rounded-lg">
              {icon}
            </div>
            <h3 className="text-lg font-bold text-white tracking-tight">{title}</h3>
          </div>

          <div className="flex items-center gap-3">
            {/* 검색창 */}
            <div className="relative group w-48 md:w-64">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-white/40 group-focus-within:text-primary-400 transition-colors" />
              <input
                type="text"
                value={searchKey}
                onChange={(e) => setSearchKey(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                placeholder="검색..."
                className="w-full bg-white/5 border border-white/10 rounded-xl pl-9 pr-8 py-1.5 text-xs text-white placeholder-white/20 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all backdrop-blur-sm"
              />
              {searchKey && (
                <button
                  onClick={() => {
                    setSearchKey('');
                    loadData();
                  }}
                  className="absolute right-2.5 top-1/2 -translate-y-1/2 text-white/20 hover:text-white transition-colors"
                >
                  <X className="w-3.5 h-3.5" />
                </button>
              )}
            </div>

            {/* 개수 */}
            <div className="flex items-center gap-2 bg-white/5 px-3 py-1.5 rounded-xl border border-white/10 h-[38px]">
              <span className="text-primary-400 font-bold text-sm">{boardList.length}</span>
              <span className="text-white/40 text-[10px] uppercase">건</span>
            </div>

            {/* 새로고침 */}
            <button
              onClick={loadData}
              disabled={loading}
              className="p-2 bg-white/5 hover:bg-white/10 border border-white/10 rounded-xl text-white/70 hover:text-white transition-all disabled:opacity-50"
              title="새로고침"
            >
              <RefreshCw className={clsx("w-4 h-4", loading && "animate-spin")} />
            </button>

            {/* 추가 버튼 */}
            <button
              onClick={() => {
                setEditFormData({
                  idx: 0,
                  bidx: bidx,
                  gcode: '',
                  header: '',
                  cate: defaultCategory,
                  title: '',
                  contents: '',
                  file: '',
                  guid: '',
                  url: '',
                  wuid: '',
                  wuid_name: '',
                  wdate: null,
                  project: '',
                  pidx: 0,
                  close: false,
                  remark: ''
                });
                setShowEditModal(true);
              }}
              disabled={!(userLevel >= 9 || userId === '395552')}
              className="p-2 bg-success-500 hover:bg-success-600 border border-white/20 rounded-xl text-white transition-all shadow-lg shadow-success-500/20 active:scale-95 disabled:opacity-30 disabled:cursor-not-allowed"
              title="추가"
            >
              <Plus className="w-4 h-4" />
            </button>
          </div>
        </div>

        <div className="divide-y divide-white/5 max-h-[calc(100vh-280px)] overflow-y-auto custom-scrollbar">
          {loading ? (
            <div className="px-6 py-12 text-center">
              <RefreshCw className="w-10 h-10 mx-auto mb-4 animate-spin text-primary-500/50" />
              <p className="text-white/50 font-medium text-sm">데이터를 실시간으로 동기화 중...</p>
            </div>
          ) : boardList.length === 0 ? (
            <div className="px-6 py-20 text-center">
              <div className="relative inline-block mb-4">
                <FileText className="w-16 h-16 mx-auto text-white/10" />
              </div>
              <p className="text-white/30 font-medium">조회된 내역이 없습니다.</p>
            </div>
          ) : (
            boardList.map((item) => (
              <div
                key={item.idx}
                className="group px-6 py-4 hover:bg-white/[0.03] transition-all cursor-pointer relative"
                onClick={() => handleRowClick(item)}
              >
                <div className="flex items-center gap-4">
                  {/* 카테고리/상태 */}
                  <div className="flex items-center gap-2 shrink-0 min-w-[120px]">
                    {item.depth && item.depth > 0 && (
                      <div className="ml-2 mr-1">
                        <ChevronRight className="w-4 h-4 text-white/20" />
                      </div>
                    )}
                    {item.cate && (
                      <span className={clsx(
                        "px-2.5 py-1 text-xs font-bold rounded-md tracking-wider uppercase shadow-sm",
                        getCategoryColor(item.cate)
                      )}>
                        {item.cate}
                      </span>
                    )}
                    {item.header && (
                      <span className="px-2.5 py-1 bg-primary-500/10 text-primary-400 text-xs font-bold rounded-md border border-primary-500/20 whitespace-nowrap">
                        {item.header}
                      </span>
                    )}
                  </div>

                  {/* 제목 섹션 */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3">
                      <h4 className="text-sm font-bold text-white group-hover:text-primary-400 transition-colors truncate">
                        {item.title || '(댓글)'}
                      </h4>
                      <div className="flex items-center gap-2 shrink-0">
                        {isNew(item.wdate) && (
                          <span className="px-1.5 py-0.5 bg-danger-500 text-white text-[10px] font-bold rounded-sm animate-pulse">
                            NEW
                          </span>
                        )}
                        {(item.reply_count ?? 0) > 0 && (
                          <div className="flex items-center gap-1 px-2 py-0.5 bg-white/5 rounded-full border border-white/10 group-hover:border-primary-500/30 transition-colors">
                            <MessageSquare className="w-3 h-3 text-primary-400" />
                            <span className="text-xs font-bold text-primary-400">{item.reply_count}</span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* 정보 섹션 */}
                  <div className="flex items-center gap-8 shrink-0">
                    <div className="flex items-center gap-6">
                      <div className="w-24 flex items-center gap-2 justify-end">
                        <div className="w-6 h-6 rounded-full bg-white/5 flex items-center justify-center border border-white/10">
                          <User className="w-3.5 h-3.5 text-white/40" />
                        </div>
                        <span className="text-sm font-medium text-white/70 truncate max-w-[80px]">
                          {item.wuid_name || item.wuid}
                        </span>
                      </div>
                      <div className="w-28 text-right flex items-center gap-2 justify-end">
                        <Calendar className="w-3.5 h-3.5 text-white/30" />
                        <span className="text-sm text-white/50 font-mono tracking-tight">
                          {formatDate(item.wdate)}
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* 호버 시 나타나는 화살표 */}
                  <div className="absolute right-4 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-all transform translate-x-2 group-hover:translate-x-0 hidden md:block">
                    <ChevronRight className="w-5 h-5 text-primary-500/40" />
                  </div>
                </div>
              </div>
            ))
          )}
        </div>
      </div>

      {/* 상세 모달 */}
      {showModal && selectedItem && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-md animate-fade-in">
          <div className="bg-[#1a1b2e]/90 rounded-3xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden border border-white/10 flex flex-col backdrop-blur-xl">
            {/* 헤더 */}
            <div className="flex items-center justify-between px-8 py-6 border-b border-white/10 bg-white/5">
              <div className="flex items-center gap-3">
                <div className="flex items-center gap-2">
                  {selectedItem.cate && (
                    <span className={clsx(
                      "px-2.5 py-1 text-[10px] font-bold rounded-md tracking-wider uppercase",
                      getCategoryColor(selectedItem.cate)
                    )}>
                      {selectedItem.cate}
                    </span>
                  )}
                  {selectedItem.header && (
                    <span className="px-2.5 py-1 bg-primary-500/10 text-primary-400 text-[10px] font-bold rounded-md border border-primary-500/20 whitespace-nowrap">
                      {selectedItem.header}
                    </span>
                  )}
                </div>
                <h2 className="text-xl font-bold text-white ml-2 tracking-tight">{selectedItem.title}</h2>
              </div>
              <button
                onClick={() => setShowModal(false)}
                className="p-2 hover:bg-white/10 rounded-full text-white/40 hover:text-white transition-all transform hover:rotate-90"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            {/* 정보바 */}
            <div className="px-8 py-3 border-b border-white/5 bg-white/[0.02] flex items-center gap-6 text-xs text-white/50 font-medium">
              <div className="flex items-center gap-2">
                <div className="w-5 h-5 rounded-full bg-white/5 flex items-center justify-center border border-white/10">
                  <User className="w-3 h-3 text-white/40" />
                </div>
                <span className="text-white/70">{selectedItem.wuid_name || selectedItem.wuid}</span>
              </div>
              <div className="flex items-center gap-2 border-l border-white/10 pl-6">
                <Calendar className="w-3.5 h-3.5" />
                <span>{formatDate(selectedItem.wdate)}</span>
              </div>
            </div>

            {/* 본문 */}
            <div className="overflow-y-auto flex-1 p-8 space-y-8 custom-scrollbar">
              {selectedItem.contents && selectedItem.contents.trim() && (
                <div className="prose prose-invert max-w-none">
                  <div className="text-white/90 leading-relaxed whitespace-pre-wrap text-[15px] font-medium opacity-90">{selectedItem.contents}</div>
                </div>
              )}

              {/* 답글 목록 */}
              {replyPosts.length > 0 && (
                <div className="space-y-4">
                  <div className="flex items-center gap-3 mb-2">
                    <div className="w-1 h-5 bg-success-500 rounded-full shadow-[0_0_10px_rgba(34,197,94,0.5)]"></div>
                    <h3 className="text-sm font-bold text-white tracking-wide uppercase opacity-70">
                      답글 <span className="text-success-400">{replyPosts.length}</span>
                    </h3>
                  </div>

                  <div className="space-y-3">
                    {replyPosts.map((replyPost) => (
                      <div
                        key={replyPost.idx}
                        className="group bg-white/5 hover:bg-white/10 border border-white/5 hover:border-white/10 rounded-2xl p-5 cursor-pointer transition-all active:scale-[0.98]"
                        onClick={() => handleRowClick(replyPost)}
                      >
                        <div className="flex items-center justify-between mb-3">
                          <h4 className="text-sm font-bold text-white flex items-center gap-3">
                            {replyPost.depth && replyPost.depth > 0 && (
                              <ChevronRight className="w-4 h-4 text-white/20" />
                            )}
                            <span className="group-hover:text-primary-400 transition-colors">{replyPost.title}</span>
                            {isNew(replyPost.wdate) && (
                              <span className="px-1.5 py-0.5 bg-danger-500 text-white text-[9px] font-bold rounded-sm">
                                NEW
                              </span>
                            )}
                          </h4>
                          <div className="flex items-center gap-4 text-[10px] text-white/40 font-bold uppercase tracking-wider">
                            <span className="flex items-center gap-1.5">
                              <User className="w-3 h-3" />
                              {replyPost.wuid_name || replyPost.wuid}
                            </span>
                            <span className="flex items-center gap-1.5">
                              <Calendar className="w-3 h-3" />
                              {formatDate(replyPost.wdate)}
                            </span>
                          </div>
                        </div>
                        {replyPost.contents && (
                          <div className="text-white/50 text-xs line-clamp-2 leading-relaxed italic">
                            {replyPost.contents}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 댓글 섹션 */}
              <div className="space-y-6">
                <div className="flex items-center gap-3 mb-2">
                  <div className="w-1 h-5 bg-primary-500 rounded-full shadow-[0_0_10px_rgba(59,130,246,0.5)]"></div>
                  <h3 className="text-sm font-bold text-white tracking-wide uppercase opacity-70">
                    댓글 <span className="text-primary-400">{replies.length}</span>
                  </h3>
                </div>

                <div className="space-y-4">
                  {replies.map((reply) => (
                    <div key={reply.idx} className="bg-white/5 border border-white/5 rounded-2xl p-5 group hover:bg-white/[0.07] transition-all">
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-2">
                          <div className="w-7 h-7 rounded-full bg-primary-500/10 flex items-center justify-center border border-primary-500/20">
                            <User className="w-3.5 h-3.5 text-primary-400" />
                          </div>
                          <div className="flex flex-col">
                            <span className="text-[11px] font-bold text-white/80">{reply.wuid_name || reply.wuid}</span>
                            <span className="text-[9px] text-white/30 font-bold tracking-wider">{formatDate(reply.wdate)}</span>
                          </div>
                        </div>
                      </div>
                      <div className="text-white/70 text-[13px] leading-relaxed whitespace-pre-wrap pl-[36px]">{reply.contents}</div>
                    </div>
                  ))}
                </div>

                {/* 댓글 입력 */}
                <div className="bg-white/[0.03] border border-white/10 rounded-2xl p-5 focus-within:border-primary-500/50 transition-all">
                  <textarea
                    value={commentText}
                    onChange={(e) => setCommentText(e.target.value)}
                    placeholder="공유하고 싶은 의견을 입력하세요..."
                    rows={3}
                    className="w-full bg-transparent border-none text-white text-sm placeholder-white/20 focus:ring-0 resize-none font-medium"
                  />
                  <div className="flex justify-end mt-3 border-t border-white/5 pt-3">
                    <button
                      onClick={handleAddComment}
                      disabled={!commentText.trim()}
                      className="px-6 py-2 bg-primary-500 hover:bg-primary-600 disabled:opacity-30 disabled:cursor-not-allowed text-white text-xs font-bold rounded-xl transition-all shadow-lg shadow-primary-500/20 active:scale-95"
                    >
                      댓글 등록
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* 하단 버튼 바 */}
            <div className="flex items-center justify-between px-8 py-6 border-t border-white/10 bg-white/5">
              <div className="flex items-center gap-3">
                <button
                  onClick={() => setShowReplyModal(true)}
                  className="px-5 py-2.5 rounded-xl bg-success-500 hover:bg-success-600 text-white text-sm font-bold transition-all shadow-lg shadow-success-500/20 active:scale-95 flex items-center gap-2"
                >
                  <MessageSquare className="w-4 h-4" />
                  답글 달기
                </button>
              </div>
              <div className="flex items-center gap-3">
                {(userLevel >= 9 || userId === '395552') && (
                  <>
                    <button
                      onClick={handleEditClick}
                      className="px-5 py-2.5 rounded-xl bg-primary-500 hover:bg-primary-600 text-white text-sm font-bold transition-all shadow-lg shadow-primary-500/20 active:scale-95 flex items-center gap-2"
                    >
                      <Edit3 className="w-4 h-4" />
                      편집
                    </button>
                    <button
                      onClick={async () => {
                        if (!selectedItem) return;
                        if (!confirm('정말 삭제하시겠습니까?')) return;
                        try {
                          const response = await comms.deleteBoard(selectedItem.idx);
                          if (response.Success) {
                            setShowModal(false);
                            loadData();
                          } else {
                            alert(response.Message || '삭제에 실패했습니다.');
                          }
                        } catch (error) {
                          console.error('삭제 오류:', error);
                          alert('삭제 중 오류가 발생했습니다.');
                        }
                      }}
                      className="px-5 py-2.5 rounded-xl bg-danger-500/10 hover:bg-danger-500 text-danger-500 hover:text-white border border-danger-500/30 hover:border-danger-500 text-sm font-bold transition-all active:scale-95"
                    >
                      삭제
                    </button>
                  </>
                )}
                <button
                  onClick={() => setShowModal(false)}
                  className="px-5 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-white/70 hover:text-white text-sm font-bold transition-all active:scale-95"
                >
                  닫기
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 편집 모달 */}
      {showEditModal && editFormData && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-md animate-fade-in">
          <div className="bg-[#1a1b2e]/90 rounded-3xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden border border-white/10 flex flex-col backdrop-blur-xl">
            <div className="flex items-center justify-between px-8 py-6 border-b border-white/10 bg-white/5">
              <h2 className="text-xl font-bold text-white flex items-center tracking-tight">
                <div className="p-2 bg-primary-500/20 rounded-lg mr-3">
                  <Edit3 className="w-5 h-5 text-primary-400" />
                </div>
                {editFormData.idx === 0 ? `${title} 등록` : `${title} 편집`}
              </h2>
              <button
                onClick={() => setShowEditModal(false)}
                className="p-2 hover:bg-white/10 rounded-full text-white/40 hover:text-white transition-all transform hover:rotate-90"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            <div className="overflow-y-auto flex-1 p-8 space-y-6 custom-scrollbar">
              <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
                <div className="md:col-span-1">
                  <label className="block text-white/50 text-[11px] font-bold uppercase tracking-wider mb-2">카테고리</label>
                  <select
                    value={editFormData.cate || defaultCategory}
                    onChange={(e) => setEditFormData({ ...editFormData, cate: e.target.value })}
                    className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm font-medium focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all appearance-none cursor-pointer"
                  >
                    {categories.map((cat) => (
                      <option key={cat.value} value={cat.value} className="bg-[#1a1b2e] text-white">
                        {cat.label}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="md:col-span-3">
                  <label className="block text-white/50 text-[11px] font-bold uppercase tracking-wider mb-2">제목</label>
                  <input
                    type="text"
                    value={editFormData.title || ''}
                    onChange={(e) => setEditFormData({ ...editFormData, title: e.target.value })}
                    className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm font-medium placeholder-white/10 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all"
                    placeholder="내용을 요약할 제목을 입력하세요"
                  />
                </div>
              </div>

              <div>
                <label className="block text-white/50 text-[11px] font-bold uppercase tracking-wider mb-2">상세 정보</label>
                <textarea
                  value={editFormData.contents || ''}
                  onChange={(e) => setEditFormData({ ...editFormData, contents: e.target.value })}
                  rows={15}
                  className="w-full bg-white/5 border border-white/10 rounded-2xl px-5 py-4 text-white text-sm font-medium placeholder-white/10 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all resize-none leading-relaxed custom-scrollbar"
                  placeholder="패치 내역 또는 게시글의 상세 내용을 자유롭게 작성하세요..."
                />
              </div>
            </div>

            <div className="flex items-center justify-between px-8 py-6 border-t border-white/10 bg-white/5">
              <div>
                {editFormData && editFormData.idx > 0 && (
                  <button
                    onClick={handleDelete}
                    className="px-6 py-2.5 rounded-xl bg-danger-500/10 hover:bg-danger-500 text-danger-500 hover:text-white border border-danger-500/30 hover:border-danger-500 text-sm font-bold transition-all active:scale-95"
                  >
                    게시글 삭제
                  </button>
                )}
              </div>
              <div className="flex items-center gap-3">
                <button
                  onClick={() => setShowEditModal(false)}
                  className="px-6 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-white/70 hover:text-white text-sm font-bold transition-all active:scale-95"
                >
                  취소
                </button>
                <button
                  onClick={handleEditSave}
                  className="px-8 py-2.5 rounded-xl bg-primary-500 hover:bg-primary-600 text-white text-sm font-bold transition-all shadow-lg shadow-primary-500/20 active:scale-95"
                >
                  저장하기
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 답글 달기 모달 */}
      {showReplyModal && selectedItem && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-md animate-fade-in">
          <div className="bg-[#1a1b2e]/90 rounded-3xl shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden border border-white/10 flex flex-col backdrop-blur-xl">
            <div className="flex items-center justify-between px-8 py-6 border-b border-white/10 bg-white/5">
              <h2 className="text-xl font-bold text-white flex items-center tracking-tight">
                <div className="p-2 bg-success-500/20 rounded-lg mr-3">
                  <MessageSquare className="w-5 h-5 text-success-400" />
                </div>
                답글 작성
              </h2>
              <button
                onClick={() => setShowReplyModal(false)}
                className="p-2 hover:bg-white/10 rounded-full text-white/40 hover:text-white transition-all transform hover:rotate-90"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            <div className="overflow-y-auto flex-1 p-8 space-y-6 custom-scrollbar">
              <div className="bg-white/5 border border-white/5 rounded-2xl p-6">
                <div className="text-[10px] font-bold text-white/30 uppercase tracking-widest mb-1.5">원본 게시글</div>
                <div className="text-white font-semibold text-base">{selectedItem.title}</div>
              </div>

              <div>
                <label className="block text-white/50 text-[11px] font-bold uppercase tracking-wider mb-2">답글 제목</label>
                <input
                  type="text"
                  value={replyFormData.title}
                  onChange={(e) => setReplyFormData({ ...replyFormData, title: e.target.value })}
                  className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-white text-sm font-medium placeholder-white/10 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all"
                  placeholder="답글의 제목을 입력하세요"
                />
              </div>

              <div>
                <label className="block text-white/50 text-[11px] font-bold uppercase tracking-wider mb-2">답글 내용</label>
                <textarea
                  value={replyFormData.contents}
                  onChange={(e) => setReplyFormData({ ...replyFormData, contents: e.target.value })}
                  rows={12}
                  className="w-full bg-white/5 border border-white/10 rounded-2xl px-5 py-4 text-white text-sm font-medium placeholder-white/10 focus:outline-none focus:ring-1 focus:ring-primary-500/50 transition-all resize-none leading-relaxed custom-scrollbar"
                  placeholder="답글 내용을 상세히 작성하세요..."
                />
              </div>
            </div>

            <div className="flex items-center justify-end gap-3 px-8 py-6 border-t border-white/10 bg-white/5">
              <button
                onClick={() => setShowReplyModal(false)}
                className="px-6 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-white/70 hover:text-white text-sm font-bold transition-all active:scale-95"
              >
                취소
              </button>
              <button
                onClick={handleAddReply}
                className="px-8 py-2.5 rounded-xl bg-primary-500 hover:bg-primary-600 text-white text-sm font-bold transition-all shadow-lg shadow-primary-500/20 active:scale-95"
              >
                답글 등록
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
