/* global React, Icon, Button */
// LPE Learning Center — /auth/handoff Single Sign-On Consumer for TLPE Supabase Auth

function AuthHandoffScreen({ onLoginSuccess, onCancel }) {
  const [status, setStatus] = React.useState("processing"); // 'processing' | 'success' | 'failed'
  const [errorMsg, setErrorMsg] = React.useState("");
  const onLoginSuccessRef = React.useRef(onLoginSuccess);
  onLoginSuccessRef.current = onLoginSuccess;
  const hasRunRef = React.useRef(false);

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

    async function handleHandoff() {
      // 1. Extract tokens from URL hash or query params
      const hashStr = window.location.hash ? window.location.hash.slice(1) : "";
      const hashParams = new URLSearchParams(hashStr);
      const queryParams = new URLSearchParams(window.location.search);

      let tokenHash = hashParams.get("token_hash") || queryParams.get("token_hash");
      let accessToken = hashParams.get("access_token") || queryParams.get("access_token");
      let refreshToken = hashParams.get("refresh_token") || queryParams.get("refresh_token") || "";
      let otpType = hashParams.get("type") || queryParams.get("type") || "email";

      // 2. Strip token from browser address bar immediately so it cannot leak
      try {
        window.history.replaceState(null, "", window.location.pathname);
      } catch (e) {
        console.warn("Could not rewrite history state:", e);
      }

      if (!tokenHash && !accessToken) {
        setStatus("failed");
        setErrorMsg("No authentication token was found in the handoff URL.");
        return;
      }

      // 3. Obtain Supabase browser client
      const client = (typeof window.getSupabaseClient === "function") ? window.getSupabaseClient() : null;

      try {
        // Case A: Direct session access_token provided
        if (accessToken) {
          if (client && client.auth) {
            try {
              await client.auth.setSession({
                access_token: accessToken,
                refresh_token: refreshToken
              });
            } catch (sessErr) {
              console.warn("Supabase setSession error:", sessErr);
            }
          }

          localStorage.setItem("lpe_session_token", accessToken);
          setStatus("success");
          setTimeout(() => {
            if (onLoginSuccessRef.current) {
              onLoginSuccessRef.current({ access_token: accessToken });
            }
          }, 500);
          return;
        }

        // Case B: token_hash provided for OTP verification
        if (!client) {
          setStatus("failed");
          setErrorMsg("Authentication service is currently unavailable. Please refresh or contact support.");
          return;
        }

        // 4. Verify OTP with Supabase (try primary type, fallback to magiclink/email if needed)
        let { data, error } = await client.auth.verifyOtp({
          token_hash: tokenHash,
          type: otpType
        });

        if ((error || !data || !data.session) && (otpType === "email" || otpType === "magiclink")) {
          const fallbackType = otpType === "email" ? "magiclink" : "email";
          const retryRes = await client.auth.verifyOtp({
            token_hash: tokenHash,
            type: fallbackType
          });
          if (!retryRes.error && retryRes.data && retryRes.data.session) {
            data = retryRes.data;
            error = null;
          }
        }

        if (error || !data || !data.session) {
          setStatus("failed");
          setErrorMsg(error ? error.message : "The sign-in token could not be verified.");
          return;
        }

        // 5. Store session access token
        const session = data.session;
        localStorage.setItem("lpe_session_token", session.access_token);

        setStatus("success");
        setTimeout(() => {
          if (onLoginSuccessRef.current) {
            onLoginSuccessRef.current(session);
          }
        }, 500);
      } catch (err) {
        setStatus("failed");
        setErrorMsg(err.message || "An unexpected error occurred during sign in.");
      }
    }

    handleHandoff();
  }, []);

  return (
    <div style={{
      minHeight: "80vh",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      padding: "24px",
      background: "var(--cream, #F8F8F8)",
      fontFamily: "var(--sans, system-ui, sans-serif)"
    }}>
      <div style={{
        maxWidth: 460,
        width: "100%",
        background: "#ffffff",
        border: "1px solid var(--grey-200, #E5E7EB)",
        borderRadius: "8px",
        boxShadow: "0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.01)",
        padding: "40px 32px",
        textAlign: "center"
      }}>
        <div style={{ marginBottom: 24 }}>
          <div style={{
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            width: 52,
            height: 52,
            borderRadius: "50%",
            background: status === "failed" ? "#FEE2E2" : "var(--navy-50, #EEF2F6)",
            color: status === "failed" ? "#DC2626" : "var(--navy, #1E293B)",
            margin: "0 auto"
          }}>
            {status === "processing" && <Icon name="sparkle" size={26} />}
            {status === "success" && <Icon name="check" size={26} />}
            {status === "failed" && <Icon name="lock" size={26} />}
          </div>
        </div>

        {status === "processing" && (
          <div>
            <h2 style={{ fontSize: 20, fontWeight: 700, color: "var(--navy, #1E293B)", margin: "0 0 8px" }}>
              Signing you in…
            </h2>
            <p style={{ fontSize: 14, color: "var(--grey-600, #4B5563)", margin: "0 0 20px", lineHeight: 1.5 }}>
              Connecting to your TLPE account and opening the Learning Center.
            </p>
            <div style={{
              width: 32,
              height: 32,
              border: "3px solid #E5E7EB",
              borderTopColor: "var(--navy, #1E293B)",
              borderRadius: "50%",
              margin: "0 auto",
              animation: "spin 1s linear infinite"
            }} />
          </div>
        )}

        {status === "success" && (
          <div>
            <h2 style={{ fontSize: 20, fontWeight: 700, color: "#059669", margin: "0 0 8px" }}>
              Welcome back!
            </h2>
            <p style={{ fontSize: 14, color: "var(--grey-600, #4B5563)", margin: 0 }}>
              Redirecting you to the course catalog…
            </p>
          </div>
        )}

        {status === "failed" && (
          <div>
            <h2 style={{ fontSize: 20, fontWeight: 700, color: "var(--navy, #1E293B)", margin: "0 0 8px" }}>
              Sign-in Link Expired
            </h2>
            <p style={{ fontSize: 14, color: "var(--grey-600, #4B5563)", margin: "0 0 24px", lineHeight: 1.5 }}>
              {errorMsg || "This sign-in link has expired or was already used."}
            </p>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <a
                href="https://lawpractice.exchange/resources"
                style={{
                  display: "inline-block",
                  padding: "12px 20px",
                  background: "var(--navy, #1E293B)",
                  color: "#ffffff",
                  borderRadius: "6px",
                  fontSize: 14,
                  fontWeight: 600,
                  textDecoration: "none"
                }}
              >
                Return to TLPE & Open Again
              </a>
              <button
                type="button"
                onClick={onCancel || (() => window.location.href = "/")}
                style={{
                  background: "transparent",
                  border: "none",
                  color: "var(--grey-500, #6B7280)",
                  fontSize: 13,
                  cursor: "pointer",
                  padding: "6px"
                }}
              >
                Go to Learning Center Home
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.AuthHandoffScreen = AuthHandoffScreen;
