/* ============================================================
   ログイン画面 — Google アカウント認証のみ（社内 @alion.jp）
   ============================================================ */
function Login() {
  const { loginAs } = useStore();
  const [err, setErr] = React.useState('');
  const [serverErr, setServerErr] = React.useState('');   // バックエンド不達（設定取得に失敗）＝ログイン以前の問題
  const [retry, setRetry] = React.useState(0);
  const [googleReady, setGoogleReady] = React.useState(false);
  const [googleConfigured, setGoogleConfigured] = React.useState(true);
  const googleDiv = React.useRef(null);

  // Google ログイン（サーバーに GOOGLE_CLIENT_ID が設定されている場合のみ表示）
  React.useEffect(() => {
    let cancelled = false;
    API.fetchConfig().then(cfg => {
      if (cancelled) return;
      if (!cfg.googleClientId) { setGoogleConfigured(false); return; }
      const init = () => {
        if (cancelled || !googleDiv.current) return;
        window.google.accounts.id.initialize({
          client_id: cfg.googleClientId,
          callback: async (resp) => {
            try {
              const r = await API.loginGoogle(resp.credential);
              hydrateAppData(r.data);
              loginAs(r.user.id);
            } catch (e) { setErr(e.message); }
          },
        });
        const locale = (window.getLang && window.getLang() === 'zh-TW') ? 'zh_TW' : 'ja';
        window.google.accounts.id.renderButton(googleDiv.current, { theme: 'outline', size: 'large', width: 328, locale });
        setGoogleReady(true);
      };
      if (window.google && window.google.accounts) init();
      else {
        const s = document.createElement('script');
        s.src = 'https://accounts.google.com/gsi/client';
        s.onload = init;
        document.head.appendChild(s);
      }
    }).catch((e) => {
      // サーバーに繋がらない時に黙って「準備中…」のまま固まらせない。
      // 2026-08-12 の DB 停止では、利用者からは原因不明のローディングにしか見えなかった（バックエンド障害の可視化）
      if (cancelled) return;
      setServerErr((e && e.message) || t('login.serverUnreachable'));
      console.error('[login] fetchConfig:', e);
    });
    return () => { cancelled = true; };
  }, [retry]);

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', background: '#f4f5f8', padding: 24 }}>
      <div style={{ width: 388, maxWidth: '100%' }}>
        <div className="asm-login-brand">
          <img src="/assets/asm/asm-mark-dark.png" alt="ASM" />
          <div>ALION SALES MANAGEMENT</div>
        </div>

        {/* カード */}
        <div style={{ background: '#fff', border: '1px solid #ecedf0', borderRadius: 16, padding: '30px 30px 28px', boxShadow: '0 6px 24px rgba(20,22,40,.06)' }}>
          <div style={{ fontSize: 19, fontWeight: 700, color: '#1c1f26' }}>{t('login.signIn')}</div>
          <div style={{ fontSize: 13, color: '#7b828d', marginTop: 5, marginBottom: 22 }}>{t('login.desc')}</div>

          {/* Google ボタン（社内 @alion.jp アカウント） */}
          <div ref={googleDiv} style={{ display: googleReady ? 'flex' : 'none', justifyContent: 'center', marginBottom: 4 }} />
          {/* サーバー不達は「準備中…」ではなく理由と再試行を出す（原因不明の無限ローディングを作らない） */}
          {!googleReady && googleConfigured && !serverErr && (
            <div style={{ textAlign: 'center', padding: '14px 0', fontSize: 13, color: '#9aa1ab' }}>{t('login.loadingGoogle')}</div>
          )}
          {!googleReady && !!serverErr && (
            <div style={{ padding: '13px 16px', background: '#fdecec', border: '1px solid #f5c6c6', borderRadius: 10, fontSize: 12.5, color: '#b91c1c', lineHeight: 1.7 }}>
              <div style={{ fontWeight: 700, marginBottom: 4 }}>{t('login.serverDown')}</div>
              <div>{serverErr}</div>
              <button onClick={() => { setServerErr(''); setRetry(n => n + 1); }}
                style={{ marginTop: 9, border: '1px solid #f5c6c6', background: '#fff', color: '#b91c1c', borderRadius: 8, padding: '5px 12px', fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
                {t('login.retry')}
              </button>
            </div>
          )}
          {!googleConfigured && (
            <div style={{ padding: '13px 16px', background: '#fdf0db', border: '1px solid #f3dcb4', borderRadius: 10, fontSize: 12.5, color: '#b45309', lineHeight: 1.7 }}>{t('login.googleNotConfigured')}</div>
          )}
          {err && <div style={{ fontSize: 12.5, color: '#dc2626', marginTop: 12, textAlign: 'center' }}>{err}</div>}

          <div style={{ marginTop: 18, fontSize: 12, color: '#a8aeb8', textAlign: 'center', lineHeight: 1.7 }}>{t('login.googleOnlyNote')}</div>
        </div>

        <div style={{ fontSize: 12, color: '#a8aeb8', textAlign: 'center', marginTop: 22 }}>{t('login.copyright')}</div>
      </div>
    </div>
  );
}
Object.assign(window, { Login });
