"use client";

import React from "react";
import { TailwindSpinner } from "@/components/common/GlobalLoad";

export default function PayRedirectPage() {
    const [status, setStatus] = React.useState<string>("Waiting for secure checkout redirect...");
    const [error, setError] = React.useState<string>("");

    React.useEffect(() => {
        const handleMessage = (event: MessageEvent) => {
            try {
                if (event.origin !== window.location.origin) return;
                const data = event.data || {};
                if (data?.type === "redirect-to-payment" && typeof data?.url === "string") {
                    setStatus("Redirecting to Stripe Checkout...");
                    window.location.href = data.url as string;
                } else if (data?.type === "redirect-error") {
                    setError(typeof data?.message === "string" ? data.message : "Failed to create payment. Please close this page and try again.");
                }
            } catch {
                setError("An error occurred while processing redirect info. Please close this page and try again.");
            }
        };

        window.addEventListener("message", handleMessage);
        const timeoutId = window.setTimeout(() => {
            setStatus("");
            setError("No redirect instruction received. It may be a network issue or the page was blocked. Please go back and try again.");
        }, 15000);

        return () => {
            window.removeEventListener("message", handleMessage);
            window.clearTimeout(timeoutId);
        };
    }, []);

    return (
        <div data-alt="pay-redirect-page" className="min-h-screen w-full flex items-center justify-center bg-black text-white">
            <div data-alt="pay-redirect-card" className="max-w-md w-full p-6 rounded-xl border border-white/10 bg-white/5 backdrop-blur">
                <h1 className="text-lg font-semibold mb-2">Preparing to redirect</h1>
                {status && <p className="text-sm text-white/80 mb-2">{status}</p>}
                {!error && (
                    <div data-alt="loading-indicator" className="flex items-center justify-center my-3">
                        <TailwindSpinner diameter={40} />
                    </div>
                )}
                {error && <p className="text-sm text-red-300">{error}</p>}
                {!error && (
                    <p className="text-xs text-white/60 mt-2">If it takes too long, please return to the previous page or check your network.</p>
                )}
            </div>
        </div>
    );
}


