// main.jsx — App entry + router

const { useState: uS, useEffect: uE } = React;

function App() {
  const route = useRoute();
  const { user, login } = useAuth();
  const r = parseRoute(route);

  // OAuth 콜백 처리 — 백엔드에서 #/auth/complete?token=xxx 로 redirect 됨
  useEffect(() => {
    if (route.startsWith('/auth/complete')) {
      const params = new URLSearchParams(route.split('?')[1] || '');
      const token = params.get('token');
      if (token) {
        window.UJTrack.setToken(token);
        // /v1/me 호출해서 user 정보 받아오기
        const API = window.UJTrack.API_BASE;
        if (API) {
          fetch(API + '/v1/me', { headers: { Authorization: 'Bearer ' + token } })
            .then(r => r.json())
            .then(d => {
              if (d.user) {
                login({ ...d.user, method: 'sso', joinedAt: d.user.joined_at || Date.now() });
                window.UJTrack.track('login_success', { provider: d.user.provider, method: 'sso' });
                navigate(d.user.onboarded === false ? '/onboarding/1' : '/app/dashboard');
              }
            })
            .catch(() => navigate('/login'));
        }
      } else {
        navigate('/login');
      }
    }
  }, [route]);

  // Route table
  let page;
  if (route === '/' || route === '') {
    page = <LandingPage />;
  } else if (route === '/login') {
    page = <LoginPage />;
  } else if (route.startsWith('/signup')) {
    page = <SignupPage />;
  } else if (route.startsWith('/verify')) {
    page = <EmailVerifyPage />;
  } else if (route.startsWith('/auth/complete')) {
    page = <AuthShell title="로그인 중…" subtitle="잠시만 기다려주세요."><div style={{ height: 80 }} /></AuthShell>;
  } else if (r.base === '/onboarding') {
    // 온보딩은 로그인(인증완료) 상태에서만
    if (!user) page = <Redirect to="/login" />;
    else page = <OnboardingPage step={r.step || 1} />;
  } else if (route.startsWith('/app')) {
    // ── 라우트 가드: 인증 + 온보딩 완료자만 앱 접근 ──
    if (!user) {
      page = <Redirect to="/login" label="로그인이 필요합니다" />;
    } else if (user.onboarded === false) {
      page = <Redirect to="/onboarding/1" label="온보딩을 완료해주세요" />;
    } else {
      let inner;
      if (route === '/app' || route === '/app/dashboard') inner = <DashboardPage />;
      else if (r.base === '/app/detail') inner = <DetailPage id={r.id} />;
      else if (route.startsWith('/app/search')) inner = <SearchPage />;
      else if (route === '/app/portfolio') inner = <PortfolioPage />;
      else if (route === '/app/compare') inner = <ComparePage />;
      else if (route.startsWith('/app/loan')) inner = <LoanPage />;
      else if (route === '/app/profile') inner = <ProfilePage />;
      else if (route === '/app/notifications') inner = <NotificationsPage />;
      else inner = <DashboardPage />;
      page = <AppShell route={route}>{inner}</AppShell>;
    }
  } else if (route === '/admin') {
    page = <AdminPage />;
  } else if (route === '/status') {
    page = <StatusPage />;
  } else if (route === '/terms' || route === '/privacy' || route === '/disclaimer') {
    page = <LegalPage type={route.slice(1)} />;
  } else if (route === '/pricing') {
    page = <PricingPage />;
  } else if (route === '/about') {
    page = <AboutPage />;
  } else {
    page = <NotFound />;
  }

  return <>{page}<InstallPrompt /></>;
}

// 라우트 가드용 리다이렉트 — hooks 안정성을 위해 별도 컴포넌트
function Redirect({ to, label }) {
  useEffect(() => { navigate(to); }, [to]);
  return (
    <AuthShell title={label || '이동 중…'} subtitle="잠시만 기다려주세요.">
      <div style={{ height: 60 }} />
    </AuthShell>
  );
}

// PWA 설치 유도 배너 — beforeinstallprompt 가 발생하면 노출
function InstallPrompt() {
  const [show, setShow] = useState(false);
  useEffect(() => {
    if (sessionStorage.getItem('uj_install_dismissed') === '1') return;
    const h = () => setShow(true);
    window.addEventListener('urijib:installable', h);
    if (window.UJ_INSTALL) setShow(true);
    return () => window.removeEventListener('urijib:installable', h);
  }, []);
  if (!show) return null;
  return (
    <div style={{
      position: 'fixed', left: 12, right: 12, bottom: 12, zIndex: 9998,
      maxWidth: 420, margin: '0 auto',
      background: T.cardHi, border: '1px solid ' + T.lineHi, borderRadius: 8,
      padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12,
      boxShadow: '0 16px 48px rgba(0,0,0,0.55)', fontFamily: T.font,
    }}>
      <div style={{ width: 38, height: 38, borderRadius: 9, background: T.hot, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 20 }}>📲</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: T.fg }}>앱으로 설치하기</div>
        <div style={{ fontSize: 11, color: T.fgDim }}>홈 화면에서 바로 실행 · 오프라인 지원</div>
      </div>
      <button onClick={async () => { const ok = await (window.UJ_INSTALL && window.UJ_INSTALL()); if (ok !== false) setShow(false); }}
        style={{ padding: '8px 14px', borderRadius: 5, background: T.hot, color: T.bg, border: 'none', fontSize: 12, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap' }}>설치</button>
      <button onClick={() => { setShow(false); sessionStorage.setItem('uj_install_dismissed', '1'); }}
        style={{ background: 'transparent', border: 'none', color: T.fgMuted, cursor: 'pointer', fontSize: 16 }}>✕</button>
    </div>
  );
}

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