/* ── Auth Modal ── */
function AuthModal({ mode, onClose, onLogin }) {
  const { t } = useT();
  const [tab, setTab] = useState(mode);
  const [loginForm, setLoginForm] = useState({ email: '', password: '' });
  const [joinForm, setJoinForm] = useState({ name: '', email: '', password: '', confirm: '', agree: false, nationality: '' });
  const [loginError, setLoginError] = useState('');
  const [joinError, setJoinError] = useState('');
  const [loading, setLoading] = useState(false);

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

  // Supabase 클라이언트 참조
  const sb = window.supabaseClient;
  // 데모 계정 (Supabase 미가입 시 로컬 폴백용)
  const DEMO = { email: 'demo@ikll.ac.kr', password: 'demo1234', name: '홍길동' };

  const handleLogin = async (e) => {
    e.preventDefault();
    setLoginError('');
    setLoading(true);

    const { data, error } = await sb.auth.signInWithPassword({
      email:    loginForm.email.trim(),
      password: loginForm.password,
    });

    setLoading(false);

    if (error) {
      // 데모 계정 폴백: Supabase 미가입 시 로컬 데모 허용
      if (loginForm.email === DEMO.email && loginForm.password === DEMO.password) {
        onLogin({ name: DEMO.name, email: DEMO.email });
        onClose();
        Swal.fire({ icon:'success', title:`환영합니다, ${DEMO.name}님!`,
          timer:2000, showConfirmButton:false, confirmButtonColor:'#0f172a' });
        return;
      }
      setLoginError(error.message === 'Invalid login credentials'
        ? t('swal_login_error')
        : error.message);
      return;
    }

    const name = data.user.user_metadata?.name || data.user.email.split('@')[0];
    onLogin({ name, email: data.user.email, id: data.user.id });
    onClose();
    Swal.fire({ icon:'success', title:`환영합니다, ${name}님!`,
      text:'로그인에 성공했습니다.', timer:2000,
      showConfirmButton:false, confirmButtonColor:'#0f172a' });
  };

  const handleJoin = async (e) => {
    e.preventDefault();
    setJoinError('');

    // ── 이름 유효성 ──
    const nameVal = joinForm.name.trim();
    if (nameVal.length < 2) {
      setJoinError('이름은 2자 이상 입력해 주세요.'); return;
    }
    if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?`~]/.test(nameVal)) {
      setJoinError('이름에 특수문자를 사용할 수 없습니다.'); return;
    }

    // ── 비밀번호 유효성 ──
    const pw = joinForm.password;
    if (pw.length < 8) {
      setJoinError('비밀번호는 8자 이상이어야 합니다.'); return;
    }
    // 반복 패턴 검사 (예: 123123, abcabc)
    const half = pw.slice(0, Math.floor(pw.length / 2));
    if (half.length >= 3 && pw === half.repeat(Math.round(pw.length / half.length)).slice(0, pw.length)) {
      setJoinError('너무 단순한 비밀번호입니다. 다른 비밀번호를 사용해 주세요.'); return;
    }
    // 동일 문자 반복 (예: 11111111)
    if (/^(.)\1+$/.test(pw)) {
      setJoinError('동일한 문자만 반복된 비밀번호는 사용할 수 없습니다.'); return;
    }

    if (joinForm.password !== joinForm.confirm) {
      setJoinError(t('swal_pw_mismatch')); return;
    }
    if (!joinForm.agree) {
      setJoinError(t('swal_agree_required')); return;
    }
    setLoading(true);

    const { data, error } = await sb.auth.signUp({
      email:    joinForm.email.trim(),
      password: joinForm.password,
      options:  { data: { name: joinForm.name, nationality: joinForm.nationality } },
    });

    setLoading(false);

    if (error) {
      setJoinError(error.message === 'User already registered'
        ? '이미 가입된 이메일입니다.'
        : error.message);
      return;
    }

    // Supabase 이메일 확인 필요 여부에 따라 분기
    if (data.session) {
      // 이메일 확인 불필요(즉시 로그인)
      onLogin({ name: joinForm.name, email: joinForm.email, id: data.user.id });
      onClose();
    } else {
      // 이메일 확인 메일 발송됨
      onClose();
    }
    Swal.fire({
      icon:'success',
      title: t('swal_join_success_title'),
      text: data.session
        ? `${joinForm.name}님, 한국어문학연구소에 오신 것을 환영합니다.`
        : '가입 확인 이메일을 발송했습니다. 이메일을 확인해 주세요.',
      confirmButtonColor:'#0f172a',
    });
  };

  return (
    <div
      className="fixed inset-0 z-50 modal-backdrop flex items-center justify-center p-4"
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl overflow-hidden">
        {/* Modal Header */}
        <div className="bg-navy-900 px-8 pt-8 pb-0">
          <div className="flex items-center justify-between mb-6">
            <div>
              <div className="font-gothic text-white text-xl font-bold">한국어문학연구소</div>
              <div className="text-white/50 text-xs mt-0.5">Institute of Korean Language &amp; Literature</div>
            </div>
            <button
              onClick={onClose}
              className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-white/70 hover:text-white transition-colors"
            >
              <i className="fas fa-times text-sm"></i>
            </button>
          </div>
          {/* Tabs */}
          <div className="flex">
            {[{ id: 'login', label: t('auth_login') }, { id: 'join', label: t('auth_join') }].map(t2 => (
              <button
                key={t2.id}
                onClick={() => { setTab(t2.id); setLoginError(''); setJoinError(''); }}
                className={`flex-1 py-3 text-sm font-medium transition-colors border-b-2 ${
                  tab === t2.id
                    ? 'text-white border-white'
                    : 'text-white/40 border-transparent hover:text-white/70'
                }`}
              >
                {t2.label}
              </button>
            ))}
          </div>
        </div>

        {/* Login Form */}
        {tab === 'login' && (
          <form onSubmit={handleLogin} className="px-8 py-7 space-y-4">
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5 tracking-wide uppercase">{t('auth_email')}</label>
              <input
                type="email"
                required
                placeholder="demo@ikll.ac.kr"
                value={loginForm.email}
                onChange={e => setLoginForm(p => ({...p, email: e.target.value}))}
                className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition-colors"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5 tracking-wide uppercase">{t('auth_password')}</label>
              <input
                type="password"
                required
                placeholder="••••••••"
                value={loginForm.password}
                onChange={e => setLoginForm(p => ({...p, password: e.target.value}))}
                className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition-colors"
              />
            </div>
            {loginError && (
              <div className="bg-red-50 border border-red-200 rounded-lg px-4 py-3 text-red-600 text-xs whitespace-pre-line">
                <i className="fas fa-exclamation-circle mr-1.5"></i>{loginError}
              </div>
            )}
            <div className="bg-blue-50 border border-blue-200 rounded-lg px-4 py-3 text-blue-700 text-xs">
              <i className="fas fa-info-circle mr-1.5"></i>
              <strong>{t('auth_demo')}:</strong> demo@ikll.ac.kr / demo1234
            </div>
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-navy-900 hover:bg-navy-800 disabled:bg-gray-300 text-white font-semibold py-3.5 rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              {loading ? (
                <><i className="fas fa-spinner fa-spin"></i> {t('auth_logging_in')}</>
              ) : (
                <><i className="fas fa-sign-in-alt"></i> {t('auth_login_btn')}</>
              )}
            </button>
            <p className="text-center text-xs text-gray-400">
              {t('auth_no_account')}{' '}
              <button type="button" onClick={() => setTab('join')} className="text-navy-900 font-semibold hover:underline">
                {t('auth_join')}
              </button>
            </p>
            <p className="text-center text-xs text-gray-400 mt-1">
              비밀번호를 잊으셨나요?{' '}
              <button type="button"
                onClick={() => {
                  const email = loginForm.email.trim();
                  if (!email) { setLoginError('이메일을 먼저 입력해 주세요.'); return; }
                  window.supabaseClient.auth.resetPasswordForEmail(email, {
                    redirectTo: window.location.origin + '/index.html'
                  }).then(({ error }) => {
                    if (error) setLoginError(error.message);
                    else Swal.fire({ icon:'success', title:'이메일 발송됨',
                      text:'비밀번호 재설정 링크를 이메일로 발송했습니다.',
                      confirmButtonColor:'#0f172a' });
                  });
                }}
                className="text-navy-900 font-semibold hover:underline">
                비밀번호 재설정
              </button>
            </p>
          </form>
        )}

        {/* Join Form */}
        {tab === 'join' && (
          <form onSubmit={handleJoin} className="px-8 py-7 space-y-4">
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5 tracking-wide uppercase">{t('auth_name')}</label>
              <input
                type="text"
                required
                placeholder={t('auth_name_ph')}
                minLength={2}
                value={joinForm.name}
                onChange={e => setJoinForm(p => ({...p, name: e.target.value}))}
                className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition-colors"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5 tracking-wide uppercase">{t('auth_nationality')}</label>
              <select
                required
                value={joinForm.nationality}
                onChange={e => setJoinForm(p => ({...p, nationality: e.target.value}))}
                className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition-colors bg-white"
              >
                <option value="">{t('auth_nationality_ph')}</option>
                <option value="KR">한국 (Korea)</option>
                <option value="CN">중국 (China)</option>
                <option value="JP">일본 (Japan)</option>
                <option value="TW">대만 (Taiwan)</option>
                <option value="HK">홍콩 (Hong Kong)</option>
                <option value="MO">마카오 (Macao)</option>
                <option value="VN">베트남 (Vietnam)</option>
                <option value="TH">태국 (Thailand)</option>
                <option value="ID">인도네시아 (Indonesia)</option>
                <option value="MY">말레이시아 (Malaysia)</option>
                <option value="SG">싱가포르 (Singapore)</option>
                <option value="PH">필리핀 (Philippines)</option>
                <option value="MN">몽골 (Mongolia)</option>
                <option value="US">미국 (USA)</option>
                <option value="GB">영국 (UK)</option>
                <option value="FR">프랑스 (France)</option>
                <option value="DE">독일 (Germany)</option>
                <option value="CA">캐나다 (Canada)</option>
                <option value="AU">호주 (Australia)</option>
                <option value="RU">러시아 (Russia)</option>
                <option value="OTHER">기타 (Other)</option>
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5 tracking-wide uppercase">{t('auth_email')}</label>
              <input
                type="email"
                required
                placeholder="your@email.com"
                value={joinForm.email}
                onChange={e => { setJoinForm(p => ({...p, email: e.target.value})); if (joinError === '올바른 이메일 형식이 아닙니다.') setJoinError(''); }}
                onBlur={e => {
                  const v = e.target.value.trim();
                  if (!v) return;
                  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) setJoinError('올바른 이메일 형식이 아닙니다.');
                  else if (joinError === '올바른 이메일 형식이 아닙니다.') setJoinError('');
                }}
                className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition-colors"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5 tracking-wide uppercase">{t('auth_password')}</label>
              <input
                type="password"
                required
                placeholder={t('auth_pw_ph')}
                minLength="8"
                value={joinForm.password}
                onChange={e => setJoinForm(p => ({...p, password: e.target.value}))}
                className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition-colors"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1.5 tracking-wide uppercase">{t('auth_pw_confirm')}</label>
              <input
                type="password"
                required
                placeholder={t('auth_pw_confirm_ph')}
                value={joinForm.confirm}
                onChange={e => setJoinForm(p => ({...p, confirm: e.target.value}))}
                className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-navy-900/20 focus:border-navy-900 transition-colors"
              />
            </div>
            <label className="flex items-start gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={joinForm.agree}
                onChange={e => setJoinForm(p => ({...p, agree: e.target.checked}))}
                className="mt-0.5 w-4 h-4 accent-navy-900"
              />
              <span className="text-xs text-gray-500 leading-relaxed">
                <span className="text-navy-900 font-semibold underline cursor-pointer">{t('auth_terms')}</span>
                {' '}{t('auth_agree')}{' '}
                <span className="text-navy-900 font-semibold underline cursor-pointer">{t('auth_privacy')}</span>
              </span>
            </label>
            {joinError && (
              <div className="bg-red-50 border border-red-200 rounded-lg px-4 py-3 text-red-600 text-xs">
                <i className="fas fa-exclamation-circle mr-1.5"></i>{joinError}
              </div>
            )}
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-navy-900 hover:bg-navy-800 disabled:bg-gray-300 text-white font-semibold py-3.5 rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              {loading ? (
                <><i className="fas fa-spinner fa-spin"></i> {t('auth_processing')}</>
              ) : (
                <><i className="fas fa-user-plus"></i> {t('auth_join_btn')}</>
              )}
            </button>
            <p className="text-center text-xs text-gray-400">
              {t('auth_have_account')}{' '}
              <button type="button" onClick={() => setTab('login')} className="text-navy-900 font-semibold hover:underline">
                {t('auth_login')}
              </button>
            </p>
          </form>
        )}
      </div>
    </div>
  );
}

/* ── Footer ── */
function Footer({ setPage }) {
  const { t } = useT();
  const links = t('footer_links');
  return (
    <footer className="bg-navy-900 text-white/60 py-12 mt-0">
      <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-8 mb-10">
          <div className="lg:col-span-2">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-9 h-9 bg-white/10 rounded flex items-center justify-center">
                <i className="fas fa-book-open text-white text-sm"></i>
              </div>
              <div>
                <div className="font-gothic text-white font-bold text-base">한국어문학연구소</div>
                <div className="text-white/40 text-xs">Institute of Korean Language &amp; Literature</div>
              </div>
            </div>
            <p className="text-sm leading-relaxed text-white/50 max-w-xs">
              2009년 출범 이래 한국어와 한국문학의 학술 연구와 세계적 확산에 힘써 왔습니다.
            </p>
          </div>
          <div>
            <h4 className="text-white text-sm font-semibold mb-3">{t('footer_quick_links')}</h4>
            <ul className="space-y-2 text-sm">
              {(Array.isArray(links) ? links : []).map(([label, pageId]) => (
                <li key={pageId}>
                  <button onClick={() => setPage && (setPage(pageId), window.scrollTo({top:0, behavior:'smooth'}))}
                    className="hover:text-white transition-colors text-left">{label}</button>
                </li>
              ))}
            </ul>
          </div>
          <div>
            <h4 className="text-white text-sm font-semibold mb-3">{t('footer_contact')}</h4>
            <ul className="space-y-2 text-sm">
              <li className="flex items-start gap-2"><i className="fas fa-map-marker-alt mt-0.5 w-4 shrink-0 mt-1"></i><span style={{lineHeight:"1.6"}}>서울시 관악구 관악로 1<br/>서울대학교 인문대학<br/>(1동 414호, 7동 407호)</span></li>
              <li><i className="fas fa-phone mr-2 w-4"></i>02-880-6284</li>
              <li><i className="fas fa-envelope mr-2 w-4"></i>eomunhak@snu.ac.kr</li>
            </ul>
          </div>
        </div>
        <div className="border-t border-white/10 pt-6 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-white/30">
          <span>{t('footer_copyright')}</span>
          <div className="flex gap-4">
            <a href="#" className="hover:text-white/60 transition-colors">{t('footer_terms')}</a>
            <a href="#" className="hover:text-white/60 transition-colors">{t('footer_privacy')}</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

