import { useWorkbenchStore } from '@/features/workspace/WorkspaceStore';
import { useState } from 'react';

export function AuthGate() {
  const auth = useWorkbenchStore((s) => s.auth);
  const authChecking = useWorkbenchStore((s) => s.authChecking);
  const refreshAuth = useWorkbenchStore((s) => s.refreshAuth);
  const startLogin = useWorkbenchStore((s) => s.startLogin);
  const [loginMessage, setLoginMessage] = useState<string | null>(null);
  const [loginStarting, setLoginStarting] = useState(false);

  if (auth.authenticated) return null;

  const tone = !auth.cliInstalled ? 'warn' : auth.hasToken ? 'error' : 'info';

  return (
    <div className={`auth-gate auth-gate--${tone}`}>
      <div className="auth-gate__text">
        <strong>Sign in required</strong>
        <span>{loginMessage || (authChecking ? 'Checking session…' : auth.message)}</span>
      </div>
      <div className="auth-gate__actions">
        <button
          type="button"
          className="auth-gate__primary"
          disabled={loginStarting}
          onClick={() => {
            setLoginStarting(true);
            setLoginMessage(null);
            void startLogin()
              .then(setLoginMessage)
              .catch((err: unknown) => setLoginMessage(err instanceof Error ? err.message : String(err)))
              .finally(() => setLoginStarting(false));
          }}
        >
          {loginStarting ? 'Opening login…' : 'Login'}
        </button>
        <button type="button" className="auth-gate__refresh" onClick={() => void refreshAuth(true)}>
          Refresh status
        </button>
      </div>
    </div>
  );
}
