'use client';

/**
 * SSO 登录回调中间页（v2.4 Entra ID OIDC）
 *
 * 路径：/sso/landing
 *
 * 事实源：docs/modules/organization/05-ui-interaction-spec.md
 *   §「SSO 登录（v2.4 新增 · 主路径）」「`/sso/landing` 路由规格」
 *
 * 设计动机
 * --------
 * 后端 callback 成功时 302 到 `${sso_redirect}#accessToken=<jwt>&refreshToken=<jwt>`，
 * 其中 sso_redirect 是用户登录前所在路径（默认 /overview）。本路由作为兜底中间页存在：
 *   - 当 sso_redirect 显式指向 /sso/landing 时（如登录页用户首次访问）
 *   - 用户从浏览器历史/书签直达 /sso/landing 时（无 hash 视为非法访问 -> ssoError）
 *
 * 主流程的 hash 处理实际由 AuthBootstrap（全局根注入）兜底——见
 * `frontend/src/components/common/AuthBootstrap.tsx`「SSO hash 处理」段。
 *
 * 生命周期（useEffect 一次性）：
 *   1. 读 window.location.hash，解析 #accessToken=xxx&refreshToken=yyy
 *   2. 缺失任一 token → router.replace('/login?ssoError=SSO_TOKEN_INVALID')
 *   3. 写 localStorage + zustand store
 *   4. 调 /users/me 拉权限（fire-and-forget，错误内化）
 *   5. history.replaceState 清掉 hash，防 token 通过 referrer/browser-history 泄漏
 *   6. router.replace 到 ?to=<path> 或 /overview
 */

import { useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth';
import { useTranslation } from '@/hooks/useTranslation';
import {
  applySsoTokensFromHash,
  type SsoLandingResult,
} from '@/lib/sso-landing';

export default function SsoLandingPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const handledRef = useRef(false);
  const reload = useAuth((s) => s.reload);

  useEffect(() => {
    if (handledRef.current) return;
    handledRef.current = true;

    const result: SsoLandingResult = applySsoTokensFromHash();

    if (result.kind === 'error') {
      router.replace(`/login?ssoError=${result.errorCode}`);
      return;
    }

    if (result.kind === 'noop') {
      // 无 hash 直达 /sso/landing → 视为非法访问 / 浏览器历史/书签直达，按 spec
      // §「`/sso/landing` 路由规格」step 1 失败分支处理，回登录页带错误码
      router.replace('/login?ssoError=SSO_TOKEN_INVALID');
      return;
    }

    // 异步拉 /users/me（fire-and-forget，避免阻塞跳转；reload 内部对 401 graceful 处理）
    reload().catch(() => undefined);

    router.replace(result.target);
  }, [router, reload]);

  return (
    <div
      className="min-h-screen flex flex-col items-center justify-center bg-black"
      data-testid="sso-landing"
      role="status"
      aria-live="polite"
    >
      <svg
        className="animate-spin h-12 w-12 text-white mb-6"
        fill="none"
        viewBox="0 0 24 24"
      >
        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
        <path
          className="opacity-75"
          fill="currentColor"
          d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
        />
      </svg>
      <p
        className="text-white text-sm font-light tracking-wide"
        data-testid="sso-completing"
      >
        {t.auth.sso.status.completing}
      </p>
    </div>
  );
}
