const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;

/* ──────────────────────────────────────────
   i18n SETUP
────────────────────────────────────────── */
const I18nContext = createContext({ t: k => k, lang: 'ko', setLang: () => {} });
const useT = () => useContext(I18nContext);

const TRANSLATIONS = {
  ko: {
    /* Navbar */
    nav_home:     '홈',
    nav_notice:   '공지사항',
    nav_inquiry:  '문의하기',
    nav_about:    '사업소개',
    about_overview: '사업개요',
    about_greeting: '인사말',
    about_history:  '연혁',
    about_org:      '조직 및 구성',
    about_location: '위치 및 연락처',
    nav_archive:  '자료실',
    nav_lectures: '강의 영상',
    inquiry_label:       '문의하기',
    inquiry_title:       '문의하기',
    inquiry_desc:        '강의나 서비스에 관해 궁금한 점을 남겨주세요. 빠르게 답변드리겠습니다.',
    inquiry_name:        '이름',
    inquiry_email:       '이메일',
    inquiry_title_label: '제목',
    inquiry_content:     '문의 내용',
    inquiry_submit:      '문의 제출',
    inquiry_success:     '문의가 접수되었습니다. 빠른 시일 내에 답변드리겠습니다.',
    inquiry_error:       '문의 제출 중 오류가 발생했습니다.',
    inquiry_required:    '이름, 이메일, 제목, 내용을 모두 입력해 주세요.',
    nav_login:    '로그인',
    nav_logout:   '로그아웃',
    nav_join:     '회원가입',
    nav_member:   '회원',

    /* Notice Page */
    notice_label:        'NOTICE',
    notice_title:        '공지사항',
    notice_desc:         '서울대학교 한국어문학연구소의 새로운 소식과 공지를 전달합니다.',
    notice_search_ph:    '제목, 내용 검색…',
    notice_no:           '번호',
    lec_course_list:     '강좌 목록',
    lec_total_courses:   '총 {n}개 강좌',
    lec_session_list:    '단원 목록',
    lec_clip_list:       '클립 목록',
    lec_studying:        '학습하기',
    lec_enroll_btn:      '수강신청',
    lec_enrolled:        '수강 중',
    lec_preview:         '미리보기',
    lec_preview_play:    '미리보기 재생',
    lec_enroll_now:      '수강신청하기',
    lec_resume_title:    '이어보기',
    lec_resume_from:     '이전에 {t}까지 시청했습니다. 이어서 보시겠습니까?',
    lec_resume_btn:      '{t}부터 이어보기',
    lec_restart:         '처음부터 보기',
    lec_no_session:      '차시를 선택하세요',
    lec_login_required:  '로그인 후 시청하실 수 있습니다',
    lec_enroll_required: '수강신청 후 시청 가능합니다',
    lec_login_btn:       '로그인하기',
    lec_processing:      '처리 중...',
    lec_script_search_ph:'강의 스크립트에서 키워드 검색 (예: 방언, 번역, 소설)',
    lec_script_btn:      '검색',
    lec_script_none:     '해당 단어가 포함된 강의 스크립트가 없습니다',
    lec_script_results:  '검색 결과 — {n}개 강의',
    lec_script_panel:    '스크립트',
    inq_write_title:     '문의 작성',
    inq_required_note:   '* 표시된 항목은 필수 입력 항목입니다.',
    inq_my_title:        '내 문의 내역',
    inq_no_inquiry:      '아직 작성한 문의가 없습니다.',
    notice_date:         '날짜',
    notice_author:       '작성자',
    notice_close:        '닫기',
    notice_attachment:   '첨부파일',
    notice_prev:         '이전글',
    notice_next:         '다음글',

    /* Archive (자료실) */
    archive_wp_label:    '자료실',
    archive_wp_title:    '자료실',
    archive_wp_desc:     '연구소의 학술 자료, 간행물, 연구 결과물을 제공합니다.',
    archive_wp_search:   '자료 검색…',
    archive_wp_cat_all:  '전체',

    /* Hero */
    hero_since:       'Since 2009',
    hero_title:       '한국어문학\n연구소',
    hero_en_title:    'Institute of Korean Language and Literature',
    hero_subtitle:    '2003년 한국문학연구소와 2006년 한국어연구소를 통합해 2009년 출범했습니다.\n엄밀한 학술 방법론으로 한국 언어·문학의 새 지평을 열고, 그 깊이를 세계와 나눕니다.',
    hero_btn_archive: '연구 아카이브 보기',
    hero_btn_lecture: '강의 영상 보기',
    hero_stat_journals:  '발간 학술지',
    hero_stat_members:   '등록 연구원',
    hero_stat_lectures:  '강의 영상',
    hero_stat_projects:  '연구 프로젝트',

    /* 최신 활동 섹션 */
    section_latest_label: 'LATEST UPDATES',
    section_latest_title: '공지사항',
    section_view_all:     '전체 보기',

    /* 인용구 배너 */
    quote_text:   '"언어는 존재의 집이며,\n문학은 인간 정신의 기록입니다."',
    quote_credit: '— 한국어문학연구소 설립 정신',

    /* 빠른 링크 */
    quick_notice_title:  '공지사항',
    quick_notice_desc:   '연구소의 새 소식, 행사 안내, 개강 공지를 확인하세요.',
    quick_notice_btn:    '공지 보러가기',
    quick_archive_title: '자료실',
    quick_archive_desc:  '연구소의 학술 자료, 간행물, 연구 결과물을 열람하세요.',
    quick_archive_btn:   '자료실 바로가기',
    quick_lecture_title: '강의 영상',
    quick_lecture_desc:  '국내외 석학의 특별강연 및 학술발표 영상을 시청하세요.',
    quick_lecture_btn:   '강의 보러가기',
    quick_research_title:'연구 프로젝트',
    quick_research_desc: '현재 진행 중인 연구과제 및 성과를 확인하세요.',
    quick_research_btn:  '연구 보러가기',
    nav_research:        '연구 프로젝트',
    research_label:      'RESEARCH',
    research_title:      '연구 프로젝트',
    research_desc:       '한국어문학연구소에서 진행 중이거나 완료된 연구 프로젝트를 소개합니다.',
    research_status_active: '진행 중',
    research_status_done:   '완료',

    /* 학술지 아카이브 페이지 */
    archive_label:      '연구 아카이브',
    archive_title:      '연구 아카이브',
    archive_desc:       '그동안 발간된 학술지와 연구 프로젝트 성과를 체계적으로 아카이빙합니다.',
    archive_tab_journals: '학술지 목록',
    archive_tab_research: '연구 프로젝트',
    archive_search_ph:  '검색어를 입력하세요',
    archive_toc:        '목차 보기',
    archive_download:   '다운로드',
    archive_detail:     '상세 보기',
    archive_no_result:  '검색 결과가 없습니다.',
    archive_papers:     '편',
    archive_in_progress:'진행 중',
    archive_done:       '완료',

    /* 강의 영상 페이지 */
    lectures_label:     '강의 영상',
    lectures_title:     '강의 영상',
    lectures_desc:      '국내외 석학의 특별강연 및 학술발표 영상을 시청하세요.',
    lectures_members_only: '※ 회원 로그인 후 시청 가능합니다.',
    lectures_youtube:   'YouTube 채널',
    lectures_loading:   'YouTube에서 최신 영상을 불러오는 중…',
    lectures_all:       '전체',
    lectures_gate_title:'모든 강의 영상은 회원 전용 콘텐츠입니다.',
    lectures_gate_desc: '로그인하시면 모든 강의 영상을 자유롭게 시청하실 수 있습니다.',
    lectures_login_btn: '로그인하기',
    lectures_views:     '회',

    /* 로그인/회원가입 */
    auth_login:        '로그인',
    auth_join:         '회원가입',
    auth_nationality:  '국적',
    auth_nationality_ph: '국적을 선택해 주세요',
    auth_email:        '이메일',
    auth_password:     '비밀번호',
    auth_pw_confirm:   '비밀번호 확인',
    auth_name:         '이름',
    auth_name_ph:      '홍길동',
    auth_pw_ph:        '8자 이상',
    auth_pw_confirm_ph:'비밀번호 재입력',
    auth_agree:        '에 동의합니다.',
    auth_terms:        '이용약관',
    auth_privacy:      '개인정보처리방침',
    auth_no_account:   '계정이 없으신가요?',
    auth_have_account: '이미 계정이 있으신가요?',
    auth_demo:         '데모 계정',
    auth_login_btn:    '로그인',
    auth_join_btn:     '회원가입',
    auth_processing:   '처리 중...',
    auth_logging_in:   '로그인 중...',

    /* 알림창 */
    swal_login_needed_title: '로그인이 필요합니다',
    swal_login_needed_text:  '강의 영상은 로그인 후 시청하실 수 있습니다.',
    swal_login_needed_confirm:'로그인하러 가기',
    swal_login_needed_cancel:'취소',
    swal_logout_ok:    '로그아웃 되었습니다.',
    swal_login_error:  '이메일 또는 비밀번호가 올바르지 않습니다.\n(데모: demo@ikll.ac.kr / demo1234)',
    swal_pw_mismatch:  '비밀번호가 일치하지 않습니다.',
    swal_agree_required:'이용약관에 동의해주세요.',
    swal_join_success_title: '회원가입 완료!',

    /* 푸터 */
    footer_quick_links:'빠른 링크',
    footer_contact:    '연락처',
    footer_links: [['사업소개','about_overview'],['자료실','archive'],['강의 영상','lectures'],['공지사항','notice'],['위치 및 연락처','about_location']],
    footer_address:    '서울시 관악구 관악로 1 서울대학교 인문대학 (1동 414호, 7동 407호)',
    footer_copyright:  '© 2026 서울대학교 한국어문학연구소. All rights reserved.',
    footer_terms:      '이용약관',
    footer_privacy:    '개인정보처리방침',
  },
  en: {
    /* Navbar */
    nav_home:     'Home',
    nav_notice:   'Notice',
    nav_inquiry:  'Contact',
    nav_about:    'About',
    about_overview: 'Overview',
    about_greeting: 'Greetings',
    about_history:  'History',
    about_org:      'Organization',
    about_location: 'Location & Contact',
    nav_archive:  'Archive',
    nav_lectures: 'Lectures',
    inquiry_label:       'Contact',
    inquiry_title:       'Contact Us',
    inquiry_desc:        'Please leave your questions about lectures or services. We will respond promptly.',
    inquiry_name:        'Name',
    inquiry_email:       'Email',
    inquiry_title_label: 'Subject',
    inquiry_content:     'Message',
    inquiry_submit:      'Submit',
    inquiry_success:     'Your inquiry has been received. We will get back to you shortly.',
    inquiry_error:       'An error occurred while submitting your inquiry.',
    inquiry_required:    'Please fill in all required fields.',
    nav_login:    'Log In',
    nav_logout:   'Log Out',
    nav_join:     'Sign Up',
    nav_member:   'Member',

    /* Notice Page */
    notice_label:        'NOTICE',
    notice_title:        'Notice',
    notice_desc:         'Announcements, event notices, and course schedules from the Institute.',
    notice_search_ph:    'Search by title or content…',
    notice_no:           'No.',
    lec_course_list:     'Courses',
    lec_total_courses:   '{n} courses',
    lec_session_list:    'Units',
    lec_clip_list:       'Clips',
    lec_studying:        'Study',
    lec_enroll_btn:      'Enroll',
    lec_enrolled:        'Enrolled',
    lec_preview:         'Preview',
    lec_preview_play:    'Play Preview',
    lec_enroll_now:      'Enroll Now',
    lec_resume_title:    'Resume',
    lec_resume_from:     'You watched up to {t}. Continue watching?',
    lec_resume_btn:      'Resume from {t}',
    lec_restart:         'Watch from beginning',
    lec_no_session:      'Select a session',
    lec_login_required:  'Please log in to watch',
    lec_enroll_required: 'Please enroll to watch',
    lec_login_btn:       'Log in',
    lec_processing:      'Processing...',
    lec_script_search_ph:'Search keyword in lecture scripts (e.g. dialect, translation)',
    lec_script_btn:      'Search',
    lec_script_none:     'No lecture scripts found for that keyword',
    lec_script_results:  'Results — {n} lectures',
    lec_script_panel:    'Script',
    inq_write_title:     'New Inquiry',
    inq_required_note:   '* Required fields',
    inq_my_title:        'My Inquiries',
    inq_no_inquiry:      'No inquiries yet.',
    notice_date:         'Date',
    notice_author:       'Author',
    notice_close:        'Close',
    notice_attachment:   'Attachments',
    notice_prev:         'Prev',
    notice_next:         'Next',

    /* Archive */
    archive_wp_label:    'Archive',
    archive_wp_title:    'Archive',
    archive_wp_desc:     'Academic materials, publications, and research outputs from the institute.',
    archive_wp_search:   'Search archive…',
    archive_wp_cat_all:  'All',

    /* Hero */
    hero_since:       'Since 2009',
    hero_title:       'Institute of\nKorean Studies',
    hero_en_title:    'Institute of Korean Language and Literature',
    hero_subtitle:    'Launched in 2009 by uniting the Institute of Korean Literature (est. 2003) and the Institute of Korean Language (est. 2006).\nThrough rigorous scholarship, we open new horizons in Korean language and literature — and share them with the world.',
    hero_btn_archive: 'Research Archive',
    hero_btn_lecture: 'Video Lectures',
    hero_stat_journals:  'Journals',
    hero_stat_members:   'Researchers',
    hero_stat_lectures:  'Lectures',
    hero_stat_projects:  'Projects',

    /* Latest section */
    section_latest_label: 'LATEST UPDATES',
    section_latest_title: 'Notice',
    section_view_all:     'View All',

    /* Quote banner */
    quote_text:   '"Language is the house of being,\nand literature is the record of the human spirit."',
    quote_credit: '— Founding Spirit of the Institute',

    /* Quick links */
    quick_notice_title:  'Notice',
    quick_notice_desc:   'Check announcements, event notices, and course schedules.',
    quick_notice_btn:    'View Notices',
    quick_archive_title: 'Archive',
    quick_archive_desc:  'Browse academic materials, publications, and research outputs.',
    quick_archive_btn:   'Go to Archive',
    quick_lecture_title: 'Video Lectures',
    quick_lecture_desc:  'Watch special lectures and academic presentations by leading scholars.',
    quick_lecture_btn:   'Go to Lectures',
    quick_research_title:'Research',
    quick_research_desc: 'Explore ongoing research projects and their outcomes.',
    quick_research_btn:  'Go to Research',
    nav_research:        'Research',
    research_label:      'RESEARCH',
    research_title:      'Research Projects',
    research_desc:       'Ongoing and completed research projects at the Institute of Korean Language and Literature.',
    research_status_active: 'Ongoing',
    research_status_done:   'Completed',

    /* Journal Archive page */
    archive_label:      'Research Archive',
    archive_title:      'Research Archive',
    archive_desc:       'We systematically archive the academic journals and research outcomes published by the Institute.',
    archive_tab_journals: 'Journals',
    archive_tab_research: 'Research Projects',
    archive_search_ph:  'Search...',
    archive_toc:        'Table of Contents',
    archive_download:   'Download',
    archive_detail:     'View Details',
    archive_no_result:  'No results found.',
    archive_papers:     ' papers',
    archive_in_progress:'Ongoing',
    archive_done:       'Completed',

    /* Lectures page */
    lectures_label:     'Video Lectures',
    lectures_title:     'Video Lectures',
    lectures_desc:      'Watch special lectures and academic presentations by leading Korean and international scholars.',
    lectures_members_only: '※ Login required to watch lectures.',
    lectures_youtube:   'YouTube Channel',
    lectures_loading:   'Loading latest videos…',
    lectures_all:       'All',
    lectures_gate_title:'All lecture videos are member-only content.',
    lectures_gate_desc: 'Log in to freely watch all lecture videos.',
    lectures_login_btn: 'Log In',
    lectures_views:     ' views',

    /* Auth modal */
    auth_login:        'Log In',
    auth_join:         'Sign Up',
    auth_nationality:  'Nationality',
    auth_nationality_ph: 'Select your nationality',
    auth_email:        'Email',
    auth_password:     'Password',
    auth_pw_confirm:   'Confirm Password',
    auth_name:         'Full Name',
    auth_name_ph:      'Hong Gil-dong',
    auth_pw_ph:        'Min. 8 characters',
    auth_pw_confirm_ph:'Re-enter password',
    auth_agree:        ' and ',
    auth_terms:        'Terms of Service',
    auth_privacy:      'Privacy Policy',
    auth_no_account:   "Don't have an account?",
    auth_have_account: 'Already have an account?',
    auth_demo:         'Demo account',
    auth_login_btn:    'Log In',
    auth_join_btn:     'Sign Up',
    auth_processing:   'Processing...',
    auth_logging_in:   'Logging in...',

    /* Alerts */
    swal_login_needed_title: 'Login Required',
    swal_login_needed_text:  'Please log in to watch lecture videos.',
    swal_login_needed_confirm:'Go to Login',
    swal_login_needed_cancel:'Cancel',
    swal_logout_ok:    'You have been logged out.',
    swal_login_error:  'Incorrect email or password.\n(Demo: demo@ikll.ac.kr / demo1234)',
    swal_pw_mismatch:  'Passwords do not match.',
    swal_agree_required:'Please agree to the Terms of Service.',
    swal_join_success_title: 'Registration Complete!',

    /* Footer */
    footer_quick_links:'Quick Links',
    footer_contact:    'Contact',
    footer_links: [['About','about_overview'],['Archive','archive'],['Lectures','lectures'],['Notice','notice'],['Location','about_location']],
    footer_address:    'Seoul National University, College of Humanities, 1 Gwanak-ro, Gwanak-gu, Seoul (Bldg.1 Rm.414, Bldg.7 Rm.407)',
    footer_copyright:  '© 2026 Institute of Korean Language and Literature. All rights reserved.',
    footer_terms:      'Terms of Service',
    footer_privacy:    'Privacy Policy',
  },
};

function I18nProvider({ children }) {
  const [lang, setLang] = useState('ko');
  const t = (key) => {
    const dict = TRANSLATIONS[lang] || TRANSLATIONS.ko;
    return dict[key] !== undefined ? dict[key] : key;
  };
  return (
    <I18nContext.Provider value={{ t, lang, setLang }}>
      {children}
    </I18nContext.Provider>
  );
}


