/* ──────────────────────────────────────────
   COMPONENTS
────────────────────────────────────────── */

/* ── Lang Toggle Button ── */
function LangToggle() {
  const { lang, setLang } = useT();
  return (
    <button
      onClick={() => setLang(l => l === 'ko' ? 'en' : 'ko')}
      className="lang-toggle flex items-center gap-0.5 border border-white/25 hover:border-white/60 rounded px-2.5 py-1 text-xs transition-colors select-none"
      title="언어 전환 / Switch Language"
    >
      <span className={lang === 'ko' ? 'lang-active' : 'lang-inactive'}>KO</span>
      <span className="text-white/25 mx-0.5">/</span>
      <span className={lang === 'en' ? 'lang-active' : 'lang-inactive'}>EN</span>
    </button>
  );
}

/* ── Navbar ── */
function Navbar({ currentPage, setPage, isLoggedIn, setShowLoginModal, handleLogout, user }) {
  const { t } = useT();
  const [menuOpen, setMenuOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const navItems = [
    { id: 'home',     label: t('nav_home') },
    { id: 'about',    label: t('nav_about'), dropdown: [
      { id: 'about_overview', label: t('about_overview') },
      { id: 'about_greeting', label: t('about_greeting') },
      { id: 'about_history',  label: t('about_history')  },
      { id: 'about_org',      label: t('about_org')      },
      { id: 'about_location', label: t('about_location') },
    ]},
    { id: 'notice',   label: t('nav_notice') },
    { id: 'archive',  label: t('nav_archive') },
    { id: 'research', label: t('nav_research') },
    { id: 'lectures', label: t('nav_lectures') },
    { id: 'inquiry',  label: t('nav_inquiry') },
  ];

  const [dropOpen, setDropOpen] = React.useState(false);
  const dropRef = useRef(null);

  useEffect(() => {
    const close = e => { if (dropRef.current && !dropRef.current.contains(e.target)) setDropOpen(false); };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, []);

  const handleNav = (id) => {
    setPage(id);
    setMenuOpen(false);
    setDropOpen(false);
  };

  const aboutPages = ['about_overview','about_greeting','about_history','about_org','about_location'];
  const isAboutActive = aboutPages.includes(currentPage);

  return (
    <div className="fixed top-0 left-0 right-0 z-50">
      {/* ── 서울대학교 · K학술확산연구센터 병행표기 바 ── */}
      <div className="bg-white border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center h-10">
            <img
              src="materials/snu-logo.png"
              alt="서울대학교 Seoul National University"
              className="h-[22px] sm:h-6 w-auto block shrink-0"
            />
            <span className="mx-3 sm:mx-3.5 w-px h-6 bg-gray-200 shrink-0" aria-hidden="true"></span>
            <div className="leading-none whitespace-nowrap">
              <div className="font-gothic text-navy-900 text-[13.5px] sm:text-[15px] font-bold tracking-[0.005em]">
                K학술확산연구센터
              </div>
              <div className="text-gray-400 text-[8.5px] sm:text-[9.5px] font-semibold tracking-[0.22em] uppercase mt-[3px]">
                K-Academics
              </div>
            </div>
          </div>
        </div>
      </div>
    <nav className={`transition-all duration-300 ${
      scrolled ? 'bg-navy-900 shadow-2xl' : 'bg-navy-900'
    }`}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          {/* Logo */}
          <button
            onClick={() => handleNav('home')}
            className="flex items-center gap-3 group"
          >
            <div className="w-9 h-9 bg-white/10 rounded flex items-center justify-center group-hover:bg-white/20 transition-colors">
              <i className="fas fa-book-open text-white text-sm"></i>
            </div>
            <div className="text-left">
              <div className="font-gothic text-white text-base font-bold leading-tight tracking-tight">
                한국어문학연구소
              </div>
              <div className="text-white/50 text-xs tracking-widest uppercase hidden sm:block">
                Institute of Korean Language &amp; Literature
              </div>
            </div>
          </button>

          {/* Desktop Nav */}
          <div className="hidden md:flex items-center gap-6">
            {navItems.map(item => item.dropdown ? (
              <div key={item.id} className="relative flex items-center" ref={dropRef}>
                <button
                  onClick={() => setDropOpen(o => !o)}
                  className={`nav-link text-sm font-medium tracking-wide text-white/80 hover:text-white transition-colors whitespace-nowrap ${
                    isAboutActive ? 'active text-white' : ''
                  }`}
                >
                  {item.label}
                </button>
                {dropOpen && (
                  <div className="absolute top-full left-0 mt-2 w-44 bg-white rounded-lg shadow-xl border border-gray-100 overflow-hidden z-50 py-1">
                    {item.dropdown.map(sub => (
                      <button
                        key={sub.id}
                        onClick={() => handleNav(sub.id)}
                        className={`w-full text-left px-4 py-2.5 text-sm transition-colors ${
                          currentPage === sub.id
                            ? 'bg-navy-900 text-white font-semibold'
                            : 'text-gray-700 hover:bg-gray-50 hover:text-navy-900'
                        }`}
                      >
                        {sub.label}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            ) : (
              <button
                key={item.id}
                onClick={() => handleNav(item.id)}
                className={`nav-link text-sm font-medium tracking-wide text-white/80 hover:text-white transition-colors ${
                  currentPage === item.id ? 'active text-white' : ''
                }`}
              >
                {item.label}
              </button>
            ))}
          </div>

          {/* Desktop Auth + Lang */}
          <div className="hidden md:flex items-center gap-4 ml-4">
            <LangToggle />
            {isLoggedIn ? (
              <div className="flex items-center gap-3">
                <a
                  href={ADMIN_EMAILS.includes(user?.email) ? "admin.html" : "mypage.html"}
                  title={ADMIN_EMAILS.includes(user?.email) ? "관리자 페이지" : "마이페이지"}
                  className="flex items-center gap-2 cursor-pointer group"
                  style={{textDecoration:'none'}}
                >
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center transition-colors ${
                    ADMIN_EMAILS.includes(user?.email)
                      ? 'bg-amber-400/30 group-hover:bg-amber-400/50'
                      : 'bg-white/20 group-hover:bg-white/35'
                  }`}>
                    <span className="text-white text-xs font-bold">
                      {ADMIN_EMAILS.includes(user?.email)
                        ? <i className="fas fa-shield-alt" style={{fontSize:'11px'}} />
                        : (user?.name || t('nav_member')).charAt(0).toUpperCase()
                      }
                    </span>
                  </div>
                  <span className="text-white/80 group-hover:text-white text-sm transition-colors">
                    {ADMIN_EMAILS.includes(user?.email) ? '관리자' : (user?.name || t('nav_member'))}
                  </span>
                  <i className="fas fa-external-link-alt text-white/30 group-hover:text-white/60 text-[10px] transition-colors"></i>
                </a>
                <button
                  onClick={handleLogout}
                  className="text-white/60 hover:text-white text-sm transition-colors border border-white/20 hover:border-white/50 rounded px-3 py-1.5"
                >
                  {t('nav_logout')}
                </button>
              </div>
            ) : (
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setShowLoginModal('login')}
                  className="text-white/80 hover:text-white text-sm transition-colors px-3 py-1.5"
                >
                  {t('nav_login')}
                </button>
                <button
                  onClick={() => setShowLoginModal('join')}
                  className="bg-white text-navy-900 hover:bg-silver text-sm font-semibold rounded px-4 py-1.5 transition-colors"
                >
                  {t('nav_join')}
                </button>
              </div>
            )}
          </div>

          {/* Mobile: Lang + Hamburger */}
          <div className="md:hidden flex items-center gap-2">
            <LangToggle />
            <button
              onClick={() => setMenuOpen(o => !o)}
              className="w-10 h-10 flex items-center justify-center rounded text-white/80 hover:text-white hover:bg-white/10 transition-colors"
              aria-label="메뉴 열기"
            >
              <i className={`fas ${menuOpen ? 'fa-times' : 'fa-bars'} text-lg`}></i>
            </button>
          </div>
        </div>
      </div>

      {/* Mobile Menu */}
      <div className={`md:hidden overflow-hidden transition-all duration-300 ${
        menuOpen ? 'max-h-screen opacity-100' : 'max-h-0 opacity-0'
      }`}>
        <div className="bg-navy-950 border-t border-white/10 px-4 py-4 space-y-1">
          {navItems.map(item => item.dropdown ? (
            <div key={item.id}>
              <div className="px-4 py-2 text-white/40 text-xs font-semibold tracking-widest uppercase">
                {item.label}
              </div>
              {item.dropdown.map(sub => (
                <button
                  key={sub.id}
                  onClick={() => handleNav(sub.id)}
                  className={`w-full text-left pl-8 pr-4 py-2.5 rounded text-sm transition-colors ${
                    currentPage === sub.id
                      ? 'bg-white/15 text-white'
                      : 'text-white/60 hover:bg-white/10 hover:text-white'
                  }`}
                >
                  — {sub.label}
                </button>
              ))}
            </div>
          ) : (
            <button
              key={item.id}
              onClick={() => handleNav(item.id)}
              className={`w-full text-left px-4 py-3 rounded text-sm font-medium transition-colors ${
                currentPage === item.id
                  ? 'bg-white/15 text-white'
                  : 'text-white/70 hover:bg-white/10 hover:text-white'
              }`}
            >
              {item.label}
            </button>
          ))}
          <div className="border-t border-white/10 pt-3 mt-3 flex gap-2">
            {isLoggedIn ? (
              <>
                <a
                  href={ADMIN_EMAILS.includes(user?.email) ? "admin.html" : "mypage.html"}
                  className="flex-1 text-center text-white/80 border border-white/20 rounded py-2 text-sm flex items-center justify-center gap-1.5"
                  style={{textDecoration:'none'}}
                  onClick={() => setMenuOpen(false)}
                >
                  <i className={`fas ${ADMIN_EMAILS.includes(user?.email) ? 'fa-shield-alt' : 'fa-user-circle'} text-xs`}></i>
                  {ADMIN_EMAILS.includes(user?.email) ? '관리자' : (user?.name || t('nav_member'))}
                </a>
                <button
                  onClick={() => { handleLogout(); setMenuOpen(false); }}
                  className="flex-1 text-center text-white/60 border border-white/20 rounded py-2 text-sm"
                >
                  {t('nav_logout')}
                </button>
              </>
            ) : (
              <>
                <button
                  onClick={() => { setShowLoginModal('login'); setMenuOpen(false); }}
                  className="flex-1 text-center text-white/70 border border-white/20 rounded py-2 text-sm"
                >
                  {t('nav_login')}
                </button>
                <button
                  onClick={() => { setShowLoginModal('join'); setMenuOpen(false); }}
                  className="flex-1 text-center bg-white text-navy-900 rounded py-2 text-sm font-semibold"
                >
                  {t('nav_join')}
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </nav>
    </div>
  );
}

/* ── Hero Section ── */
function HeroSection({ setPage }) {
  const { t, lang } = useT();
  return (
    <section className="relative min-h-screen flex items-center justify-center overflow-hidden">
      {/* Background Image */}
      <div
        className="absolute inset-0 bg-cover bg-center bg-no-repeat"
        style={{
          backgroundImage: `url('https://images.unsplash.com/photo-1521587760476-6c12a4b040da?w=1920&q=90')`
        }}
      />
      {/* Overlay */}
      <div className="absolute inset-0 hero-overlay" />

      {/* Content */}
      <div className="relative z-10 text-center text-white px-4 max-w-4xl mx-auto">
        {/* Decorative line */}
        <div className="flex items-center justify-center gap-4 mb-8">
          <div className="h-px w-16 bg-white/40"></div>
          <span className="text-white/60 text-xs tracking-[0.3em] uppercase font-light">{t('hero_since')}</span>
          <div className="h-px w-16 bg-white/40"></div>
        </div>

        <h1 className="font-gothic text-4xl sm:text-5xl md:text-6xl lg:text-7xl font-bold leading-tight mb-6 tracking-tight whitespace-pre-line">
          {t('hero_title')}
        </h1>

        <p className="text-white/70 text-base sm:text-lg md:text-xl font-light leading-relaxed mb-4 tracking-wide">
          {t('hero_en_title')}
        </p>
        <p className="text-white/55 text-sm sm:text-base leading-relaxed mb-12 max-w-2xl mx-auto whitespace-pre-line">
          {t('hero_subtitle')}
        </p>

        <div className="flex flex-col sm:flex-row items-center justify-center gap-4">
          <button
            onClick={() => setPage('archive')}
            className="bg-white text-navy-900 hover:bg-silver font-semibold px-8 py-3.5 rounded transition-all duration-200 hover:scale-105 w-full sm:w-auto"
          >
            <i className="fas fa-archive mr-2"></i>
            {t('hero_btn_archive')}
          </button>
          <button
            onClick={() => setPage('lectures')}
            className="border border-white/50 hover:border-white text-white hover:bg-white/10 font-medium px-8 py-3.5 rounded transition-all duration-200 w-full sm:w-auto"
          >
            <i className="fas fa-play-circle mr-2"></i>
            {t('hero_btn_lecture')}
          </button>
        </div>

      </div>

      {/* Scroll indicator */}
      <div className="absolute bottom-8 left-1/2 -translate-x-1/2 text-white/40 animate-bounce">
        <i className="fas fa-chevron-down text-lg"></i>
      </div>
    </section>
  );
}

/* ── Notice Card ── */
function NoticeCard({ item, setPage }) {
  // DB 데이터: { id, title, author, created_at }
  // 로컬 데이터: { _isLocal, _tag, _tagColor, _excerpt, ... }
  const isLocal = item._isLocal;
  const tag      = isLocal ? item._tag   : 'NOTICE';
  const tagColor = isLocal ? item._tagColor : 'bg-blue-100 text-blue-800';
  const excerpt  = isLocal ? item._excerpt  : (item.author ? `작성자: ${item.author}` : '');
  const dateStr  = isLocal ? item.created_at : (item.created_at ? item.created_at.slice(0,10).replace(/-/g,'.') : '');

  return (
    <article className="bg-white rounded-lg overflow-hidden card-hover border border-gray-100 flex flex-col cursor-pointer"
             onClick={() => setPage && setPage('notice')}>
      <div className="p-6 flex flex-col flex-1">
        <div className="flex items-center justify-between mb-3">
          <span className={`badge text-xs font-semibold px-2.5 py-1 rounded ${tagColor}`}>
            {tag}
          </span>
          <span className="text-gray-400 text-xs">{dateStr}</span>
        </div>
        <h3 className="font-gothic text-gray-900 font-semibold text-base leading-snug mb-3 hover:text-navy-900 transition-colors">
          {item.title}
        </h3>
        <p className="text-gray-500 text-sm leading-relaxed flex-1 line-clamp-2">
          {excerpt}
        </p>
        <div className="mt-4 pt-4 border-t border-gray-50 flex items-center justify-between">
          <span className="text-gray-400 text-xs">{item.author || '관리자'}</span>
          <span className="text-navy-900 text-xs font-medium flex items-center gap-1">
            자세히 보기 <i className="fas fa-arrow-right text-[10px]"></i>
          </span>
        </div>
      </div>
    </article>
  );
}

/* ── Home Page ── */
function HomePage({ setPage }) {
  const { t } = useT();
  const [dbNotices, setDbNotices] = useState([]);
  const [noticesLoading, setNoticesLoading] = useState(true);

  useEffect(() => {
    window.supabaseClient
      .from('notices')
      .select('id,title,author,created_at')
      .order('created_at', { ascending: false })
      .limit(6)
      .then(({ data, error }) => {
        if (!error && data?.length) {
          setDbNotices(data);
        } else {
          // Supabase에 데이터 없으면 기존 하드코딩 데이터 사용
          setDbNotices(NOTICES.map(n => ({
            id: n.id, title: n.title,
            author: n.category,
            created_at: n.date,
            _isLocal: true, _tag: n.tag, _tagColor: n.tagColor, _excerpt: n.excerpt,
          })));
        }
        setNoticesLoading(false);
      });
  }, []);

  return (
    <div>
      <HeroSection setPage={setPage} />

      {/* Notices Section */}
      <section className="py-20 bg-silver">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-end justify-between mb-12">
            <div>
              <div className="text-navy-900/40 text-xs tracking-[0.25em] uppercase mb-2">
                {t('section_latest_label')}
              </div>
              <h2 className="font-gothic text-3xl sm:text-4xl font-bold text-navy-900">
                {t('section_latest_title')}
              </h2>
            </div>
            <button onClick={() => setPage('notice')}
              className="hidden sm:flex items-center gap-2 text-sm text-navy-900 hover:underline font-medium">
              {t('section_view_all')} <i className="fas fa-arrow-right text-xs"></i>
            </button>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {noticesLoading
              ? Array(3).fill(0).map((_, i) => (
                  <div key={i} className="bg-white rounded-lg border border-gray-100 p-6 animate-pulse">
                    <div className="h-3 bg-gray-100 rounded w-1/3 mb-4"></div>
                    <div className="h-4 bg-gray-100 rounded w-full mb-2"></div>
                    <div className="h-4 bg-gray-100 rounded w-3/4"></div>
                  </div>
                ))
              : dbNotices.map(item => <NoticeCard key={item.id} item={item} setPage={setPage} />)
            }
          </div>
        </div>
      </section>

      {/* About Banner */}
      <section className="py-24 bg-navy-900 relative overflow-hidden">
        <div className="absolute inset-0 opacity-5"
          style={{
            backgroundImage: 'repeating-linear-gradient(0deg, transparent, transparent 40px, #fff 40px, #fff 41px), repeating-linear-gradient(90deg, transparent, transparent 40px, #fff 40px, #fff 41px)'
          }}
        />
        <div className="max-w-4xl mx-auto px-4 text-center relative z-10">
          <div className="h-px w-16 bg-white/30 mx-auto mb-8"></div>
          <blockquote className="font-gothic text-white text-2xl sm:text-3xl md:text-4xl font-semibold leading-relaxed mb-8 whitespace-pre-line">
            {t('quote_text')}
          </blockquote>
          <p className="text-white/50 text-sm tracking-widest">{t('quote_credit')}</p>
          <div className="h-px w-16 bg-white/30 mx-auto mt-8"></div>
        </div>
      </section>

      {/* Quick Links */}
      <section className="py-20 bg-white">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {[
              {
                icon: 'fa-bullhorn',
                title: t('quick_notice_title') || '공지사항',
                desc:  t('quick_notice_desc')  || '연구소 새 소식과 공지를 확인하세요.',
                action: 'notice',
                label:  t('quick_notice_btn')  || '바로가기',
                color: 'text-rose-600',
                bg:    'bg-rose-50',
              },
              {
                icon: 'fa-book-open',
                title: t('quick_archive_title'),
                desc:  t('quick_archive_desc'),
                action: 'archive',
                label:  t('quick_archive_btn'),
                color: 'text-blue-600',
                bg:    'bg-blue-50',
              },
              {
                icon: 'fa-video',
                title: t('quick_lecture_title'),
                desc:  t('quick_lecture_desc'),
                action: 'lectures',
                label:  t('quick_lecture_btn'),
                color: 'text-purple-600',
                bg:    'bg-purple-50',
              },
              {
                icon: 'fa-flask',
                title: t('quick_research_title'),
                desc:  t('quick_research_desc'),
                action: 'research',
                label:  t('quick_research_btn'),
                color: 'text-emerald-600',
                bg:    'bg-emerald-50',
              },
            ].map(item => (
              <div key={item.title} className="text-center p-8 rounded-xl border border-gray-100 card-hover">
                <div className={`w-14 h-14 ${item.bg} rounded-xl flex items-center justify-center mx-auto mb-5`}>
                  <i className={`fas ${item.icon} ${item.color} text-xl`}></i>
                </div>
                <h3 className="font-gothic text-navy-900 text-xl font-bold mb-3">{item.title}</h3>
                <p className="text-gray-500 text-sm leading-relaxed mb-6">{item.desc}</p>
                <button
                  onClick={() => setPage(item.action)}
                  className="text-navy-900 text-sm font-semibold hover:underline flex items-center gap-1 mx-auto"
                >
                  {item.label} <i className="fas fa-arrow-right text-xs"></i>
                </button>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Footer */}
      <Footer setPage={setPage} />
    </div>
  );
}

/* ── Archive Page ── */
