/* Visible during session restoration and Google credential verification. */
function StartupStatus({phase='restore',state={status:'loading',attempt:1,error:''},onRetry}) {
  const [slow,setSlow]=React.useState(false);
  React.useEffect(()=>{setSlow(false);const timer=setTimeout(()=>setSlow(true),8000);return()=>clearTimeout(timer);},[state.attempt,phase]);
  const failed=state.status==='error';
  return <main className="asm-startup" aria-busy={!failed} data-startup-state={state.status}>
    <section className="asm-startup-card">
      <img className="asm-startup-logo" src="/assets/asm/asm-mark-dark.png" alt="ASM" width="106" height="40"/>
      <h1>{t(failed?'startup.failed':phase==='restore'?'startup.restore':'startup.signingIn')}</h1>
      <p>{t(failed?'startup.retryHint':'startup.dataHint')}</p>
      {!failed&&<div className="asm-startup-progress" aria-hidden="true"/>}
      <div className="asm-startup-stage" role="status" aria-live="polite" hidden={failed}>{t(failed?'startup.retryHint':state.status==='retrying'?'startup.retrying':phase==='restore'?'startup.restoreStage':'startup.signingStage',{n:state.attempt})}</div>
      {(slow||failed)&&<p className="asm-startup-note" role={failed?'alert':'status'}>{failed?localizeMessage(state.error):t('startup.slow')}</p>}
      {onRetry&&(slow||failed)&&<button type="button" onClick={onRetry}>{t('login.retry')}</button>}
    </section>
  </main>;
}

/* ============================================================
   ログイン画面 — Google アカウント認証のみ（社内 @alion.jp）
   ============================================================ */
function Login() {
  const { loginAs } = useStore();
  const [busy,setBusy]=React.useState(false);
  const signing=React.useRef(false);
  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,scriptTimer,script;
    const ctrl=new AbortController();
    setGoogleReady(false);setGoogleConfigured(true);
    API.fetchConfig({signal:ctrl.signal}).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) => {
            if(cancelled||signing.current)return;
            signing.current=true;setBusy(true);setErr('');
            try {
              const r = await API.loginGoogle(resp.credential);
              if(cancelled)return;
              if(!r?.data||!Array.isArray(r.data.users))throw new Error(t('startup.invalidData'));
              hydrateAppData(r.data);
              loginAs(r.user.id);
            } catch (e) { if(!cancelled)setErr(e.message); } finally { signing.current=false;if(!cancelled)setBusy(false); }
          },
        });
        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 });
        clearTimeout(scriptTimer);setGoogleReady(true);
      };
      if (window.google && window.google.accounts) init();
      else {
        const s = script = document.createElement('script');
        scriptTimer=setTimeout(()=>{if(!cancelled){s.remove();setServerErr(t('startup.googleFailed'));}},15000);
        s.onerror=()=>{clearTimeout(scriptTimer);if(!cancelled)setServerErr(t('startup.googleFailed'));};
        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;ctrl.abort();clearTimeout(scriptTimer);if(script&&!window.google?.accounts)script.remove(); };
  }, [retry]);

  return (
    <>{busy&&<StartupStatus phase="signIn"/>}<div aria-hidden={busy} style={{ display:busy?'none':'flex', minHeight: '100vh', 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 role="status" aria-live="polite" style={{textAlign:'center',fontSize:13,color:'#7b828d'}}><div className="asm-startup-progress" aria-hidden="true"/>{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, StartupStatus });
