// [nexus] Google OAuth button — 3-second risk warning gate, opens popup, captures stateId
import { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { CheckCircle } from "lucide-react";
import { puterProxyApi } from "@/api/puter-proxy";

interface GoogleOAuthButtonProps {
  onSuccess: (stateId: string) => void;
  onError: (msg: string) => void;
}

export function GoogleOAuthButton({ onSuccess, onError }: GoogleOAuthButtonProps) {
  const [loading, setLoading] = useState(false);
  const [warningTimer, setWarningTimer] = useState(false);
  const [connected, setConnected] = useState(false);

  // 3-second gate — button stays disabled until user has read the risk warning
  useEffect(() => {
    const id = setTimeout(() => setWarningTimer(true), 3000);
    return () => clearTimeout(id);
  }, []);

  async function handleClick() {
    setLoading(true);
    try {
      const { url, stateId } = await puterProxyApi.getAuthUrl();

      const popup = window.open(url, "_blank", "popup,width=600,height=700");
      if (!popup) {
        throw new Error("Popup blocked");
      }

      // Poll for popup close — when closed, assume callback stored tokens server-side
      await new Promise<void>((resolve) => {
        const interval = setInterval(() => {
          if (popup.closed) {
            clearInterval(interval);
            resolve();
          }
        }, 500);
      });

      onSuccess(stateId);
      setConnected(true);
    } catch {
      onError("Google sign-in failed. Try again or use an API key instead.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex flex-col gap-3">
      {/* Policy-risk warning — always visible when this component is rendered */}
      <div role="alert" className="text-sm text-destructive bg-destructive/10 rounded-md px-3 py-2">
        <p className="font-medium">Policy risk -- read before continuing</p>
        <p className="mt-1">
          Google has suspended accounts that used third-party apps with Gemini credentials. This may
          affect your Gmail and Workspace access. Use a Google AI Studio API key instead if you want
          to avoid this risk.
        </p>
      </div>

      <Button
        type="button"
        variant="outline"
        onClick={handleClick}
        disabled={!warningTimer || loading || connected}
        aria-busy={loading}
        className="w-full"
      >
        {loading ? (
          <span className="flex items-center gap-2">
            <svg
              className="h-4 w-4 animate-spin"
              viewBox="0 0 24 24"
              fill="none"
              aria-hidden="true"
            >
              <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 12h4z"
              />
            </svg>
            Signing in...
          </span>
        ) : connected ? (
          <span className="flex items-center gap-2">
            <CheckCircle className="h-4 w-4" />
            Google connected
          </span>
        ) : (
          "Sign in with Google"
        )}
      </Button>
    </div>
  );
}
