import { useAuth } from '../lib/auth';
import { mindSpaceLoginUrl } from '../lib/site';
import { fetchReviewQueue } from '../api/client';
import { useEffect, useState } from 'react';

export function RequireOps({ children }: { children: React.ReactNode }) {
  const { loading: authLoading, user } = useAuth();
  const [state, setState] = useState<'loading' | 'ok' | 'forbidden'>('loading');
  const [message, setMessage] = useState<string | null>(null);

  useEffect(() => {
    if (authLoading) return;
    if (!user) { setState('forbidden'); setMessage(null); return; }

    // Admins bypass ops-role check.
    if (user.role === 'admin') { setState('ok'); return; }

    void (async () => {
      try {
        await fetchReviewQueue('status=pending_review&limit=1');
        setState('ok');
      } catch (err) {
        setMessage(err instanceof Error ? err.message : '无运营权限');
        setState('forbidden');
      }
    })();
  }, [authLoading, user]);

  if (authLoading || state === 'loading') return <p>检查登录态…</p>;

  if (!user) {
    return (
      <div className="card">
        <h2>需要登录</h2>
        <p>请先在 MindSpace 登录（须与 Ops 使用同一域名，例如都用 127.0.0.1 或都用 *.localhost）。</p>
        <p style={{ color: '#68716c' }}>
          Ops 地址：<code>http://127.0.0.1:3002/ops/</code>
        </p>
        <a className="btn" href={mindSpaceLoginUrl()}>
          前往登录
        </a>
      </div>
    );
  }

  if (state === 'forbidden') {
    return (
      <div className="card">
        <h2>无运营权限</h2>
        <p>{message ?? '当前账号没有 Plaza 运营权限。'}</p>
        <p style={{ color: '#68716c' }}>
          本地开发可执行：<code>node scripts/grant-ops-role.mjs admin ops_admin</code>
        </p>
      </div>
    );
  }

  return children;
}
