function PostModal({ post, posts, onClose }) {
  const { t } = useT();
  const idx   = posts.findIndex(p => p.id === post.id);
  const prev  = idx > 0              ? posts[idx - 1] : null;
  const next  = idx < posts.length-1 ? posts[idx + 1] : null;

  /* body scroll lock */
  useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  /* ESC 닫기 */
  useEffect(() => {
    const h = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  const [current, setCurrent] = React.useState(post);
  const goTo = (p) => { if (p) setCurrent(p); };
  const currentIdx = posts.findIndex(p => p.id === current.id);
  const hasPrev = currentIdx > 0;
  const hasNext = currentIdx < posts.length - 1;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4"
         style={{ background: 'rgba(0,0,0,0.6)' }}
         onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl flex flex-col"
           style={{ maxHeight: '90vh' }}>
        {/* 헤더 */}
        <div className="flex items-start justify-between p-6 border-b border-gray-100">
          <div className="flex-1 pr-4">
            <div className="flex flex-wrap gap-1.5 mb-2">
              {current.categories.map(c => (
                <span key={c} className="text-[11px] px-2 py-0.5 rounded-full bg-navy-8 text-navy-900 font-medium">
                  {c}
                </span>
              ))}
            </div>
            <h2 className="font-gothic text-gray-900 font-bold text-xl leading-snug">{current.title}</h2>
            <div className="flex items-center gap-3 mt-2 text-xs text-gray-400">
              <span><i className="fas fa-calendar mr-1"/>{current.date}</span>
              {current.author && <span><i className="fas fa-user mr-1"/>{current.author}</span>}
            </div>
          </div>
          <button onClick={onClose}
            className="shrink-0 w-8 h-8 flex items-center justify-center rounded-full bg-gray-100 hover:bg-gray-200 text-gray-500 transition">
            <i className="fas fa-times text-sm"/>
          </button>
        </div>

        {/* 본문 */}
        <div className="overflow-y-auto flex-1 p-6">
          <div className="prose max-w-none text-sm text-gray-700 leading-relaxed"
               style={{ wordBreak: 'break-word' }}
               dangerouslySetInnerHTML={{ __html: current.content }} />

          {/* 첨부파일 */}
          {current.attachments && current.attachments.length > 0 && (
            <div className="mt-6 pt-5 border-t border-gray-100">
              <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">
                <i className="fas fa-paperclip mr-1"/>{t('notice_attachment')}
              </p>
              <ul className="space-y-1.5">
                {current.attachments.map((url, i) => {
                  const name = url.split('/').pop();
                  return (
                    <li key={i}>
                      <a href={url} target="_blank" rel="noreferrer"
                         className="flex items-center gap-2 text-xs text-navy-900 hover:underline">
                        <i className="fas fa-download text-navy-900/50"/>
                        {decodeURIComponent(name)}
                      </a>
                    </li>
                  );
                })}
              </ul>
            </div>
          )}
        </div>

        {/* 이전/다음 */}
        <div className="flex border-t border-gray-100">
          <button
            disabled={!hasPrev}
            onClick={() => goTo(posts[currentIdx - 1])}
            className={`flex-1 flex items-center gap-2 px-5 py-3 text-xs transition-colors ${
              hasPrev ? 'text-gray-600 hover:bg-gray-50' : 'text-gray-300 cursor-not-allowed'
            }`}>
            <i className="fas fa-chevron-up text-[10px]"/>
            <span className="font-medium mr-1">{t('notice_prev')}</span>
            <span className="truncate">{hasPrev ? posts[currentIdx-1].title : '—'}</span>
          </button>
          <div className="w-px bg-gray-100"/>
          <button
            disabled={!hasNext}
            onClick={() => goTo(posts[currentIdx + 1])}
            className={`flex-1 flex items-center gap-2 px-5 py-3 text-xs transition-colors justify-end ${
              hasNext ? 'text-gray-600 hover:bg-gray-50' : 'text-gray-300 cursor-not-allowed'
            }`}>
            <span className="truncate">{hasNext ? posts[currentIdx+1].title : '—'}</span>
            <span className="font-medium ml-1">{t('notice_next')}</span>
            <i className="fas fa-chevron-down text-[10px]"/>
          </button>
        </div>
      </div>
    </div>
  );
}

/* ──────────────────────────────────────────
   NOTICE PAGE
────────────────────────────────────────── */
const ITEMS_PER_PAGE = 15;

function NoticePage({ setPage }) {
  const { t } = useT();
  const [query,    setQuery]    = useState('');
  const [pageNum,  setPageNum]  = useState(1);
  const [selected, setSelected] = useState(null);
  const [dbNotices, setDbNotices] = useState([]);
  const [dbLoading, setDbLoading] = useState(true);

  // Supabase notices 로드
  useEffect(() => {
    window.supabaseClient
      .from('notices')
      .select('id,title,author,content,created_at')
      .order('created_at', { ascending: false })
      .then(({ data }) => {
        if (data?.length) {
          // DB 데이터를 WP_NOTICES 형식으로 변환
          const converted = data.map(n => ({
            id: `db_${n.id}`,
            title: n.title,
            date: n.created_at ? n.created_at.slice(0,10) : '',
            author: n.author || '관리자',
            categories: [],
            excerpt: n.content ? n.content.replace(/<[^>]+>/g,'').slice(0,100) : '',
            content: n.content || '',
            attachments: [],
            _fromDB: true,
          }));
          setDbNotices(converted);
        }
        setDbLoading(false);
      });
  }, []);

  // WP 공지 + DB 공지 병합 (DB가 최신 우선)
  const allNotices = [...dbNotices, ...WP_NOTICES];

  const filtered = allNotices.filter(n =>
    n.title.toLowerCase().includes(query.toLowerCase()) ||
    (n.content || '').toLowerCase().includes(query.toLowerCase())
  );
  const totalPages = Math.ceil(filtered.length / ITEMS_PER_PAGE);
  const paged = filtered.slice((pageNum-1)*ITEMS_PER_PAGE, pageNum*ITEMS_PER_PAGE);

  return (
    <div className="pt-[104px] min-h-screen bg-gray-50">
      {/* 헤더 */}
      <div className="bg-navy-900 py-16">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-white/40 text-xs tracking-[0.25em] uppercase mb-3">{t('notice_label')}</div>
          <h1 className="font-gothic text-4xl sm:text-5xl font-bold text-white mb-3">{t('notice_title')}</h1>
          <p className="text-white/60 text-sm max-w-xl">{t('notice_desc')}</p>
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        {/* 검색 */}
        <div className="flex justify-between items-center mb-6 gap-4">
          <p className="text-gray-400 text-sm shrink-0">
            총 {filtered.length}건
            {dbLoading && <span className="ml-2 text-xs text-gray-300 animate-pulse">DB 로딩 중…</span>}
          </p>
          <div className="relative w-full max-w-sm">
            <i className="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"/>
            <input
              type="text"
              placeholder={t('notice_search_ph')}
              value={query}
              onChange={e => { setQuery(e.target.value); setPageNum(1); }}
              className="w-full pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900"
            />
          </div>
        </div>

        {/* 테이블 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-gray-50 border-b border-gray-100">
                <th className="text-left px-5 py-3 font-semibold text-gray-500 text-xs w-12">{t('notice_no')}</th>
                <th className="text-left px-5 py-3 font-semibold text-gray-500 text-xs">제목</th>
                <th className="text-left px-5 py-3 font-semibold text-gray-500 text-xs hidden sm:table-cell w-28">{t('notice_date')}</th>
                <th className="text-left px-5 py-3 font-semibold text-gray-500 text-xs hidden md:table-cell w-24">{t('notice_author')}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {paged.length === 0 && (
                <tr><td colSpan={4} className="text-center py-12 text-gray-400">검색 결과가 없습니다.</td></tr>
              )}
              {paged.map((post, i) => (
                <tr key={post.id}
                    className="hover:bg-navy-3 transition-colors cursor-pointer group"
                    onClick={() => setSelected(post)}>
                  <td className="px-5 py-3.5 text-gray-400 text-xs">
                    {filtered.length - (pageNum-1)*ITEMS_PER_PAGE - i}
                  </td>
                  <td className="px-5 py-3.5">
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-gray-800 group-hover:text-navy-900 transition-colors leading-snug">
                        {post.title}
                      </span>
                      {post._fromDB && (
                        <span className="text-[9px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 font-semibold shrink-0">NEW</span>
                      )}
                      {post.attachments?.length > 0 && (
                        <i className="fas fa-paperclip text-gray-400 text-[10px] shrink-0"/>
                      )}
                      {post.categories.filter(c => c !== '분류되지 않음').map(c => (
                        <span key={c} className="hidden sm:inline text-[10px] px-1.5 py-0.5 rounded bg-navy-8 text-navy-900">
                          {c}
                        </span>
                      ))}
                    </div>
                  </td>
                  <td className="px-5 py-3.5 text-gray-400 text-xs hidden sm:table-cell whitespace-nowrap">{post.date}</td>
                  <td className="px-5 py-3.5 text-gray-500 text-xs hidden md:table-cell">{post.author}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 페이지네이션 */}
        {totalPages > 1 && (
          <div className="flex justify-center gap-1 mt-6">
            <button onClick={() => setPageNum(p => Math.max(1, p-1))}
              disabled={pageNum === 1}
              className="px-3 py-1.5 rounded text-sm text-gray-500 hover:bg-gray-100 disabled:opacity-30">
              <i className="fas fa-chevron-left text-xs"/>
            </button>
            {Array.from({length: totalPages}, (_, i) => i+1).map(n => (
              <button key={n} onClick={() => setPageNum(n)}
                className={`px-3 py-1.5 rounded text-sm transition-colors ${
                  n === pageNum ? 'bg-navy-900 text-white font-semibold' : 'text-gray-600 hover:bg-gray-100'
                }`}>
                {n}
              </button>
            ))}
            <button onClick={() => setPageNum(p => Math.min(totalPages, p+1))}
              disabled={pageNum === totalPages}
              className="px-3 py-1.5 rounded text-sm text-gray-500 hover:bg-gray-100 disabled:opacity-30">
              <i className="fas fa-chevron-right text-xs"/>
            </button>
          </div>
        )}
      </div>

      {/* 모달 */}
      {selected && (
        <PostModal post={selected} posts={filtered} onClose={() => setSelected(null)} />
      )}
      <Footer setPage={setPage} />
    </div>
  );
}

/* ──────────────────────────────────────────
   WP ARCHIVE PAGE  (자료실 — WordPress 데이터)
────────────────────────────────────────── */
/* ── Research Page ── */
/* ──────────────────────────────────────────
   INQUIRY PAGE (문의하기)
────────────────────────────────────────── */
function InquiryPage({ isLoggedIn, user, setPage }) {
  const { t }  = useT();
  const sb     = window.supabaseClient;

  const [activeTab,   setActiveTab]   = React.useState('write');
  const [myInquiries, setMyInquiries] = React.useState([]);
  const [listLoading, setListLoading] = React.useState(false);
  const [form, setForm] = React.useState({
    name:    user?.name  || '',
    email:   user?.email || '',
    title:   '',
    content: '',
  });
  const [loading,   setLoading]   = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);

  React.useEffect(() => {
    if (user) setForm(f => ({ ...f, name: user.name || '', email: user.email || '' }));
  }, [user]);

  const loadMyInquiries = React.useCallback(async () => {
    const email = user?.email || form.email;
    if (!email) return;
    setListLoading(true);
    const { data } = await sb.from('inquiries')
      .select('id,title,status,created_at,admin_reply')
      .eq('email', email.trim())
      .order('created_at', { ascending: false });
    setMyInquiries(data || []);
    setListLoading(false);
  }, [user?.email, form.email]);

  React.useEffect(() => {
    if (activeTab === 'list') loadMyInquiries();
  }, [activeTab]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email || !form.title || !form.content) {
      Swal.fire({ icon:'warning', title:'입력 오류', text: t('inquiry_required'), confirmButtonColor:'#0f172a' });
      return;
    }
    setLoading(true);
    const { error } = await sb.from('inquiries').insert({
      name:    form.name.trim(),
      email:   form.email.trim(),
      title:   form.title.trim(),
      content: form.content.trim(),
      status:  'pending',
    });
    setLoading(false);
    if (error) {
      Swal.fire({ icon:'error', title:'오류', text: t('inquiry_error'), confirmButtonColor:'#0f172a' });
      return;
    }
    setSubmitted(true);
    loadMyInquiries();
    Swal.fire({ icon:'success', title:'접수 완료', text: t('inquiry_success'),
      confirmButtonColor:'#0f172a', timer: 3000, showConfirmButton: false });
  };

  const STATUS_LABEL = { pending:'답변 대기', answered:'답변 완료', closed:'종료' };
  const STATUS_CLS   = {
    pending:  'text-amber-700 bg-amber-50 border-amber-200',
    answered: 'text-green-700 bg-green-50 border-green-200',
    closed:   'text-gray-400 bg-gray-50 border-gray-200',
  };

  return (
    <div className="pt-[104px] min-h-screen bg-gray-50">
      {/* 헤더 */}
      <div className="bg-navy-900 py-16">
        <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-white/40 text-xs tracking-[0.25em] uppercase mb-3">{t('inquiry_label')}</div>
          <h1 className="font-gothic text-4xl sm:text-5xl font-bold text-white mb-3">{t('inquiry_title')}</h1>
          <p className="text-white/60 text-sm max-w-xl">{t('inquiry_desc')}</p>
        </div>
      </div>

      <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {submitted ? (
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-12 text-center">
            <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-5">
              <i className="fas fa-check text-green-600 text-2xl" />
            </div>
            <h2 className="font-gothic text-gray-900 font-bold text-xl mb-3">문의가 접수되었습니다</h2>
            <p className="text-gray-500 text-sm mb-6">{t('inquiry_success')}</p>
            <button
              onClick={() => { setSubmitted(false); setForm(f => ({...f, title:'', content:''})); setActiveTab('list'); }}
              className="px-6 py-2.5 bg-navy-900 text-white font-semibold text-sm rounded-lg hover:bg-navy-800 transition"
            >
              <i className="fas fa-list mr-2" />{t('inq_my_title')}
            </button>
          </div>
        ) : (
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            {/* 탭 */}
            <div className="flex border-b border-gray-100">
              {[
                { id:'write', label: t('inq_write_title'), icon:'fa-pen' },
                { id:'list',  label: t('inq_my_title'),    icon:'fa-list-ul' },
              ].map(tab => (
                <button key={tab.id} onClick={() => setActiveTab(tab.id)}
                  className={`flex-1 py-4 text-sm font-medium transition-colors flex items-center justify-center gap-2 ${
                    activeTab === tab.id
                      ? 'text-navy-900 border-b-2 border-navy-900'
                      : 'text-gray-400 hover:text-gray-600'
                  }`}>
                  <i className={`fas ${tab.icon} text-xs`} />{tab.label}
                  {tab.id === 'list' && myInquiries.length > 0 && (
                    <span className="ml-1 bg-navy-900 text-white text-[9px] font-bold w-4 h-4 rounded-full flex items-center justify-center">
                      {myInquiries.length}
                    </span>
                  )}
                </button>
              ))}
            </div>

            {/* 내 문의 목록 */}
            {activeTab === 'list' && (
              <div className="p-6">
                {listLoading ? (
                  <div className="text-center py-10 text-gray-400 text-sm">
                    <i className="fas fa-spinner fa-spin text-xl mb-3 block" />로딩 중...
                  </div>
                ) : myInquiries.length === 0 ? (
                  <div className="text-center py-10">
                    <i className="fas fa-comment-slash text-3xl text-gray-200 mb-3 block" />
                    <p className="text-gray-400 text-sm">{t('inq_no_inquiry')}</p>
                    <button onClick={() => setActiveTab('write')}
                      className="mt-4 px-5 py-2 bg-navy-900 text-white text-sm rounded-lg hover:bg-navy-800 transition">
                      {t('inq_write_title')}
                    </button>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {myInquiries.map(inq => (
                      <div key={inq.id} className="border border-gray-100 rounded-xl p-4 hover:border-gray-200 transition">
                        <div className="flex items-start justify-between gap-3 mb-1">
                          <p className="text-sm font-semibold text-gray-800 flex-1">{inq.title}</p>
                          <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full border shrink-0 ${STATUS_CLS[inq.status] || STATUS_CLS.closed}`}>
                            {STATUS_LABEL[inq.status] || inq.status}
                          </span>
                        </div>
                        <p className="text-[11px] text-gray-400 mb-2">{inq.created_at?.slice(0,10)}</p>
                        {inq.admin_reply && (
                          <div className="mt-2 pt-3 border-t border-gray-100 bg-blue-50 rounded-lg px-3 py-2">
                            <p className="text-[10px] font-bold text-blue-700 mb-1">
                              <i className="fas fa-reply mr-1" />관리자 답변
                            </p>
                            <p className="text-xs text-blue-900 leading-relaxed whitespace-pre-wrap">{inq.admin_reply}</p>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* 문의 작성 폼 */}
            {activeTab === 'write' && (
              <form onSubmit={handleSubmit} className="px-8 py-6 space-y-5">
                <p className="text-gray-400 text-xs">{t('inq_required_note')}</p>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1.5 uppercase tracking-wide">{t('inquiry_name')} *</label>
                    <input type="text" required value={form.name}
                      onChange={e => setForm(f => ({...f, name: e.target.value}))}
                      placeholder="홍길동"
                      className="w-full border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition" />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1.5 uppercase tracking-wide">{t('inquiry_email')} *</label>
                    <input type="email" required value={form.email}
                      onChange={e => setForm(f => ({...f, email: e.target.value}))}
                      placeholder="your@email.com"
                      className="w-full border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition" />
                  </div>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1.5 uppercase tracking-wide">{t('inquiry_title_label')} *</label>
                  <input type="text" required value={form.title}
                    onChange={e => setForm(f => ({...f, title: e.target.value}))}
                    placeholder="문의 제목을 입력해 주세요"
                    className="w-full border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition" />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1.5 uppercase tracking-wide">{t('inquiry_content')} *</label>
                  <textarea required rows={7} value={form.content}
                    onChange={e => setForm(f => ({...f, content: e.target.value}))}
                    placeholder="문의 내용을 자세히 입력해 주세요"
                    className="w-full border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition resize-none" />
                </div>
                <div className="flex justify-end pt-2">
                  <button type="submit" disabled={loading}
                    className="px-8 py-3 bg-navy-900 hover:bg-navy-800 disabled:bg-gray-300 text-white font-semibold text-sm rounded-lg transition flex items-center gap-2">
                    {loading
                      ? <><i className="fas fa-spinner fa-spin" />{t('lec_processing')}</>
                      : <><i className="fas fa-paper-plane" />{t('inquiry_submit')}</>}
                  </button>
                </div>
              </form>
            )}
          </div>
        )}
      </div>
      <Footer setPage={setPage} />
    </div>
  );
}


function ResearchPage({ setPage }) {
  const { t } = useT();
  const [items, setItems]   = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    window.supabaseClient
      .from('research')
      .select('*')
      .order('created_at', { ascending: false })
      .then(({ data, error }) => {
        if (!error && data?.length) {
          setItems(data);
        } else {
          setItems(RESEARCH);
        }
        setLoading(false);
      });
  }, []);

  const active = items.filter(r => ['진행 중','Ongoing','active'].includes(r.status));
  const done   = items.filter(r => ['완료','Completed','done'].includes(r.status));

  return (
    <div className="pt-[104px] min-h-screen bg-gray-50">
      <div className="bg-navy-900 py-16">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-white/40 text-xs tracking-[0.25em] uppercase mb-3">{t('research_label')}</div>
          <h1 className="font-gothic text-4xl sm:text-5xl font-bold text-white mb-3">{t('research_title')}</h1>
          <p className="text-white/60 text-sm max-w-xl">{t('research_desc')}</p>
        </div>
      </div>
      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        {loading ? (
          <div className="text-center py-16 text-gray-400">
            <i className="fas fa-spinner fa-spin text-2xl mb-3 block" />
            <p className="text-sm">불러오는 중...</p>
          </div>
        ) : (
          <>
            {active.length > 0 && (
              <div className="mb-10">
                <h2 className="font-gothic text-xl font-bold text-navy-900 mb-4 flex items-center gap-2">
                  <span className="w-2 h-2 bg-green-500 rounded-full inline-block"></span>
                  {t('research_status_active')}
                </h2>
                <div className="space-y-3">
                  {active.map(r => <ResearchCard key={r.id} item={r} t={t} />)}
                </div>
              </div>
            )}
            {done.length > 0 && (
              <div>
                <h2 className="font-gothic text-xl font-bold text-navy-900 mb-4 flex items-center gap-2">
                  <span className="w-2 h-2 bg-gray-400 rounded-full inline-block"></span>
                  {t('research_status_done')}
                </h2>
                <div className="space-y-3">
                  {done.map(r => <ResearchCard key={r.id} item={r} t={t} />)}
                </div>
              </div>
            )}
            {items.length === 0 && (
              <div className="text-center py-16 text-gray-400">
                <i className="fas fa-flask text-4xl mb-4 block opacity-30" />
                <p className="text-sm">등록된 연구 프로젝트가 없습니다.</p>
              </div>
            )}
          </>
        )}
      </div>
      <Footer setPage={setPage} />
    </div>
  );
}

function ResearchCard({ item, t }) {
  const isActive = ['진행 중','Ongoing','active'].includes(item.status);
  return (
    <div className="bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-md transition-shadow">
      <div className="flex items-start gap-4">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-2">
            <span className={"text-xs font-semibold px-2.5 py-1 rounded-full " + (isActive ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-500")}>
              {item.status}
            </span>
            {item.period && <span className="text-xs text-gray-400">{item.period}</span>}
          </div>
          <h3 className="font-gothic text-gray-900 font-semibold text-base leading-snug mb-2">{item.title}</h3>
          {item.description && <p className="text-gray-500 text-sm leading-relaxed mb-2">{item.description}</p>}
          <div className="flex flex-wrap gap-3 text-xs text-gray-400">
            {item.pi && <span><i className="fas fa-user mr-1" />{item.pi}</span>}
            {item.funding && <span><i className="fas fa-building mr-1" />{item.funding}</span>}
          </div>
        </div>
      </div>
    </div>
  );
}


function WpArchivePage({ setPage }) {
  const { t } = useT();
  const sb = window.supabaseClient;
  const [query,    setQuery]    = useState('');
  const [selCat,   setSelCat]   = useState('all');
  const [selected, setSelected] = useState(null);
  const [dbArchives, setDbArchives] = useState([]);

  useEffect(() => {
    sb.from('archives').select('*').order('created_at', { ascending: false })
      .then(({ data }) => {
        if (data?.length) setDbArchives(data.map(a => ({
          id: `db_${a.id}`, title: a.title, date: a.created_at?.slice(0,10) || '',
          author: a.author || '관리자', categories: a.categories || [],
          excerpt: a.excerpt || '', content: a.content || '',
          // 한글 파일명 URL을 NFC로 정규화 — 맥(NFD)↔리눅스(NFC) 미스매치 404 방지
          attachments: (a.attachments || []).map(u => typeof u === 'string' ? u.normalize('NFC') : u),
        })));
      });
  }, []);

  const allArchiveItems = [...dbArchives, ...WP_ARCHIVES];

  const allCats = [...new Set(allArchiveItems.flatMap(a => a.categories))]
    .filter(c => c !== '분류되지 않음').sort();

  const filtered = allArchiveItems.filter(a => {
    const matchCat = selCat === 'all' || a.categories.includes(selCat);
    const matchQ   = a.title.toLowerCase().includes(query.toLowerCase()) ||
                     a.content.toLowerCase().includes(query.toLowerCase());
    return matchCat && matchQ;
  });

  return (
    <div className="pt-[104px] min-h-screen bg-gray-50">
      {/* 헤더 */}
      <div className="bg-navy-900 py-16">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-white/40 text-xs tracking-[0.25em] uppercase mb-3">{t('archive_wp_label')}</div>
          <h1 className="font-gothic text-4xl sm:text-5xl font-bold text-white mb-3">{t('archive_wp_title')}</h1>
          <p className="text-white/60 text-sm max-w-xl">{t('archive_wp_desc')}</p>
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        {/* 필터 + 검색 */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
          <div className="flex flex-wrap gap-2">
            {[{id:'all', label: t('archive_wp_cat_all')}, ...allCats.map(c => ({id:c, label:c}))].map(cat => (
              <button key={cat.id} onClick={() => setSelCat(cat.id)}
                className={`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${
                  selCat === cat.id
                    ? 'bg-navy-900 text-white'
                    : 'bg-white border border-gray-200 text-gray-600 hover:border-navy-900 hover:text-navy-900'
                }`}>
                {cat.label}
              </button>
            ))}
          </div>
          <div className="relative w-full sm:w-64 shrink-0">
            <i className="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"/>
            <input type="text" placeholder={t('archive_wp_search')}
              value={query} onChange={e => setQuery(e.target.value)}
              className="w-full pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900"
            />
          </div>
        </div>

        {/* 카드 그리드 */}
        {filtered.length === 0 ? (
          <div className="text-center py-16 text-gray-400">검색 결과가 없습니다.</div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
            {filtered.map(item => {
              /* 썸네일: 본문 첫 img src 추출 */
              const imgMatch = item.content.match(/src="([^"]+\.(png|jpg|jpeg|gif|webp))"/i);
              const thumb = imgMatch ? imgMatch[1] : null;
              const cats  = item.categories.filter(c => c !== '분류되지 않음');
              return (
                <article key={item.id}
                  className="bg-white rounded-xl border border-gray-100 overflow-hidden card-hover cursor-pointer"
                  onClick={() => setSelected(item)}>
                  {thumb ? (
                    <div className="h-40 overflow-hidden bg-gray-100">
                      <img src={thumb} alt={item.title}
                        className="w-full h-full object-cover hover:scale-105 transition-transform duration-300"
                        onError={e => { e.target.parentElement.style.display='none'; }}
                      />
                    </div>
                  ) : (
                    <div className="h-2 bg-navy-900"/>
                  )}
                  <div className="p-5">
                    {cats.length > 0 && (
                      <div className="flex flex-wrap gap-1 mb-2">
                        {cats.map(c => (
                          <span key={c} className="text-[10px] px-2 py-0.5 rounded-full bg-navy-8 text-navy-900 font-medium">{c}</span>
                        ))}
                      </div>
                    )}
                    <h3 className="font-gothic text-gray-900 font-semibold text-sm leading-snug mb-2 line-clamp-2 hover:text-navy-900 transition-colors">
                      {item.title}
                    </h3>
                    <div className="flex items-center justify-between text-xs text-gray-400 mt-3">
                      <span><i className="fas fa-calendar mr-1"/>{item.date}</span>
                      {item.attachments.length > 0 && (
                        <span><i className="fas fa-paperclip mr-1"/>{item.attachments.length}개</span>
                      )}
                    </div>
                  </div>
                </article>
              );
            })}
          </div>
        )}
      </div>

      {selected && (
        <PostModal post={selected} posts={filtered} onClose={() => setSelected(null)} />
      )}
      <Footer setPage={setPage} />
    </div>
  );
}

function ArchivePage({ setPage }) {
  const { t } = useT();
  const [activeTab, setActiveTab] = useState('journals');
  const [searchQuery, setSearchQuery] = useState('');

  const filteredArchives = ARCHIVES.filter(a =>
    a.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    a.subtitle.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const filteredResearch = RESEARCH.filter(r =>
    r.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    r.pi.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="pt-[104px]">
      {/* Archive Header */}
      <div className="bg-navy-900 py-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-white/40 text-xs tracking-[0.25em] uppercase mb-3">{t('archive_label')}</div>
          <h1 className="font-gothic text-4xl sm:text-5xl font-bold text-white mb-4">{t('archive_title')}</h1>
          <p className="text-white/60 text-base max-w-xl leading-relaxed">
            {t('archive_desc')}
          </p>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Search + Tabs */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-8">
          <div className="flex border-b border-gray-200 w-full sm:w-auto">
            {[
              { id: 'journals', label: t('archive_tab_journals') },
              { id: 'research', label: t('archive_tab_research') },
            ].map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-5 py-3 text-sm transition-colors ${
                  activeTab === tab.id ? 'tab-active' : 'tab-inactive'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>
          <div className="relative w-full sm:w-72">
            <i className="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
            <input
              type="text"
              placeholder={t('archive_search_ph')}
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              className="w-full pl-9 pr-4 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900"
            />
          </div>
        </div>

        {/* Journals Tab */}
        {activeTab === 'journals' && (
          <div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredArchives.map(item => (
                <div key={item.id} className="bg-white rounded-lg border border-gray-100 overflow-hidden card-hover">
                  <div className="bg-navy-900 h-2" />
                  <div className="p-6">
                    <div className="flex items-start justify-between mb-3">
                      <div>
                        <div className="font-gothic text-navy-900 font-bold text-lg">{item.volume}</div>
                        <div className="text-gray-400 text-xs mt-0.5">{item.year} · ISSN {item.issn}</div>
                      </div>
                      <span className={`text-xs font-semibold px-2.5 py-1 rounded badge ${item.statusColor}`}>
                        {item.status}
                      </span>
                    </div>
                    <h3 className="font-gothic text-gray-800 font-semibold text-base mb-1">{item.title}</h3>
                    <p className="text-gray-500 text-sm mb-4">{item.subtitle}</p>
                    <div className="flex items-center gap-4 text-xs text-gray-400 mb-4">
                      <span><i className="fas fa-file-alt mr-1"></i>{item.papers}{t('archive_papers')}</span>
                      <span><i className="fas fa-book mr-1"></i>{item.pages}p</span>
                    </div>
                    <div className="flex gap-2">
                      <button className="flex-1 border border-navy-900 text-navy-900 hover:bg-navy-900 hover:text-white text-xs font-medium py-2 rounded transition-colors">
                        <i className="fas fa-eye mr-1"></i> {t('archive_toc')}
                      </button>
                      <button className="flex-1 border border-gray-200 text-gray-600 hover:bg-gray-50 text-xs font-medium py-2 rounded transition-colors">
                        <i className="fas fa-download mr-1"></i> {t('archive_download')}
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            {filteredArchives.length === 0 && (
              <div className="text-center py-20 text-gray-400">
                <i className="fas fa-search text-4xl mb-4 block"></i>
                {t('archive_no_result')}
              </div>
            )}
          </div>
        )}

        {/* Research Tab */}
        {activeTab === 'research' && (
          <div className="space-y-4">
            {filteredResearch.map(item => (
              <div key={item.id} className="bg-white rounded-lg border border-gray-100 p-6 card-hover">
                <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <span className={`text-xs font-semibold px-2.5 py-1 rounded badge ${
                        item.status === '진행 중'
                          ? 'bg-emerald-100 text-emerald-700'
                          : 'bg-gray-100 text-gray-600'
                      }`}>
                        {item.status === '진행 중' ? t('archive_in_progress') : t('archive_done')}
                      </span>
                      <span className="text-gray-400 text-xs">{item.period}</span>
                    </div>
                    <h3 className="font-gothic text-navy-900 font-bold text-lg mb-1">{item.title}</h3>
                    <div className="flex flex-wrap gap-4 text-sm text-gray-500">
                      <span><i className="fas fa-user mr-1.5 text-gray-400"></i>{item.pi}</span>
                      <span><i className="fas fa-building mr-1.5 text-gray-400"></i>{item.funding}</span>
                    </div>
                  </div>
                  <button className="shrink-0 border border-navy-900 text-navy-900 hover:bg-navy-900 hover:text-white text-sm font-medium px-5 py-2.5 rounded transition-colors">
                    {t('archive_detail')}
                  </button>
                </div>
              </div>
            ))}
            {filteredResearch.length === 0 && (
              <div className="text-center py-20 text-gray-400">
                <i className="fas fa-search text-4xl mb-4 block"></i>
                {t('archive_no_result')}
              </div>
            )}
          </div>
        )}
      </div>
      <Footer setPage={setPage} />
    </div>
  );
}

/* ──────────────────────────────────────────
   CUSTOM VIDEO PLAYER MODAL  (NAS HTML5)
   - crossOrigin="anonymous"  (크로스 도메인 NAS)
   - preload="metadata"
   - playsInline
   - URL: nasUrl(folder, file)
────────────────────────────────────────── */

