/* Landing app — wires up the homepage interactive prototype. */
const { useState, useEffect } = React;


function LandingApp() {
  // Subscribe lang ở root để toàn cây re-render khi đổi VI/EN.
  const [lang] = window.useLang();
  const [modal, setModal]   = useState(null); // 'login' | 'register' | null
  const [tabIdx, setTabIdx] = useState(0);
  const [toast, setToast]   = useState(null);
  const [busy, setBusy]     = useState(false);


  // Nếu đã có access token → đi thẳng dashboard.
  useEffect(() => {
    if (window.API?.isLoggedIn()) {
      window.location.replace('dashboard/');
    }
  }, []);

  const showToast = (kind, title, body, ms = 3000) => {
    setToast({ kind, title, body, ms });
    setTimeout(() => setToast((t) => (t ? { ...t, leaving: true } : t)), ms);
    setTimeout(() => setToast(null), ms + 220);
  };

  const handleLogin = async (username, password) => {
    if (busy) return;
    setBusy(true);
    try {
      const res = await window.API.post('/auth/login', { username, password });
      window.API.setTokens(res.data.accessToken, res.data.refreshToken);
      setModal(null);
      showToast('success', t('landing.login.toastSuccessTitle'), t('landing.login.toastSuccessBody', { user: res.data.user.username }), 1500);
      setTimeout(() => { window.location.href = 'dashboard/'; }, 800);
    } catch (err) {
      showToast('error', t('landing.login.toastFailTitle'), err?.message || t('common.tryAgain'));
    } finally { setBusy(false); }
  };

  const handleRegister = async (username, password) => {
    if (busy) return;
    setBusy(true);
    try {
      const res = await window.API.post('/auth/register', { username, password });
      window.API.setTokens(res.data.accessToken, res.data.refreshToken);
      setModal(null);
      showToast('success', t('landing.register.toastSuccessTitle'), t('landing.register.toastSuccessBody', { user: res.data.user.username }), 1500);
      setTimeout(() => { window.location.href = 'dashboard/'; }, 800);
    } catch (err) {
      showToast('error', t('landing.register.toastFailTitle'), err?.message || t('common.tryAgain'));
    } finally { setBusy(false); }
  };

  return (
    <div>
      <LandingHeader onLogin={() => setModal('login')} onRegister={() => setModal('register')} />

      <Hero onSearch={(q) => showToast('success', t('landing.hero.toastSearchTitle'), t('landing.hero.toastSearchBody', { q: q || t('landing.hero.searchAll') }))} />


      <footer style={{ borderTop: '1px solid var(--line)', padding: '40px 24px', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', display: 'flex', flexWrap: 'wrap', gap: 16, justifyContent: 'space-between', alignItems: 'center' }}>
          <img src="img/logo-vietmod.svg" alt="" style={{ height: 28, opacity: 0.7 }} />
          <span>{t('landing.footer.copyright')}</span>
          <div style={{ display: 'flex', gap: 16 }}>
            <a href="#">Discord</a>
            <a href="#">Telegram</a>
            <a href="#">Facebook</a>
          </div>
        </div>
      </footer>

      {modal === 'login' && (
        <LoginModal
          busy={busy}
          onClose={() => setModal(null)}
          onSwitchToRegister={() => setModal('register')}
          onSubmit={handleLogin}
        />
      )}
      {modal === 'register' && (
        <RegisterModal
          busy={busy}
          onClose={() => setModal(null)}
          onSwitchToLogin={() => setModal('login')}
          onSubmit={handleRegister}
        />
      )}

      {toast && (
        <div style={{ position: 'fixed', top: 24, right: 24, zIndex: 80 }}>
          <div key={toast.title + toast.ms} className={`toast ${toast.kind}${toast.leaving ? ' toast-out' : ''}`}>
            <div className="toast-icon">
              {toast.kind === 'success' ? <IconCheck size={18} /> : <IconAlert size={18} />}
            </div>
            <div>
              <div className="toast-title">{toast.title}</div>
              <div className="toast-body">{toast.body}</div>
            </div>
            <div className="toast-timer" style={{ '--toast-duration': `${toast.ms}ms` }} />
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<LandingApp />);
