import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useState } from "react";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { getLicenseStatus, requestLicense, formatRetryTimeSimple, } from "../../../licensing/licenseService";
import { AlertCircle, ArrowLeft, ArrowRight, KeyRound, RefreshCw, } from "lucide-react";
export function LicenseEmailStep({ onNext, onBack }) {
    const [email, setEmail] = useState("");
    const [buildDate, setBuildDate] = useState("");
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [countdownSeconds, setCountdownSeconds] = useState(null);
    useEffect(() => {
        let disposed = false;
        getLicenseStatus()
            .then((status) => {
            if (!disposed) {
                setBuildDate(status.buildDate || "");
            }
        })
            .catch(() => {
            // Non-fatal. License request works without build date as well.
        });
        return () => {
            disposed = true;
        };
    }, []);
    // Countdown timer for rate limit (update frequency depends on remaining time)
    useEffect(() => {
        if (countdownSeconds === null || countdownSeconds <= 0) {
            return;
        }
        // Update every second when < 1 minute, every minute when >= 1 minute
        const updateInterval = countdownSeconds > 60 ? 60000 : 1000;
        const timer = setInterval(() => {
            setCountdownSeconds((prev) => {
                if (prev === null)
                    return null;
                const next = prev - (updateInterval === 60000 ? 60 : 1);
                return next > 0 ? next : 0;
            });
        }, updateInterval);
        return () => clearInterval(timer);
    }, [countdownSeconds]);
    const handleContinue = useCallback(async () => {
        if (!email) {
            setError("Please enter your email address.");
            return;
        }
        try {
            setLoading(true);
            setError(null);
            const response = await requestLicense({
                email,
                // Placeholder values are only used for branching trial-vs-code on this first step.
                name: "Setup",
                companyName: "Setup",
                parheliaBuildDate: buildDate,
            });
            if (response.status === "trial") {
                onNext({ email, mode: "trial_form" });
                return;
            }
            if (response.status === "code_sent") {
                onNext({ email, mode: "code_entry" });
                return;
            }
            if (response.status === "trial_expired") {
                setError(response.message ||
                    "Trial period expired for this email. Use activation code flow.");
                return;
            }
            if (response.status === "rate_limited") {
                const retrySeconds = response.retryAfterSeconds || 60;
                setCountdownSeconds(retrySeconds);
                setError(`Too many requests for sending a new code. If you already have one, use "I already have a code". Otherwise try again in ${formatRetryTimeSimple(retrySeconds)}.`);
                return;
            }
            setError(response.message || "Failed to start license activation.");
        }
        catch (e) {
            setError(e?.message || "Failed to contact license service.");
        }
        finally {
            setLoading(false);
        }
    }, [email, buildDate, onNext]);
    return (_jsxs("div", { className: "flex flex-col items-center text-center p-12", children: [_jsx("div", { className: "mb-8 rounded-2xl bg-blue-50 p-6 ring-1 ring-blue-100", children: _jsx(KeyRound, { className: "h-16 w-12 text-blue-600", strokeWidth: 1.5 }) }), _jsx("h2", { className: "text-3xl font-bold text-gray-900 mb-4 tracking-tight", children: "License Activation" }), _jsx("p", { className: "text-gray-500 mb-8 max-w-md leading-relaxed", children: "Enter your email to start license activation. We will detect whether to continue with trial registration or one-time activation code." }), _jsxs("form", { className: "w-full max-w-md", onSubmit: (e) => {
                    e.preventDefault();
                    if (loading)
                        return;
                    void handleContinue();
                }, children: [_jsx("div", { className: "space-y-4 mb-6", children: _jsx(Input, { id: "email", type: "email", "data-testid": "license-email-input", value: email, onChange: (e) => setEmail(e.target.value), placeholder: "you@company.com", className: "h-11 rounded-xl border-gray-200 bg-white focus:ring-blue-500" }) }), error && (_jsxs("div", { className: "mb-8 flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 p-4 text-left max-w-md", children: [_jsx(AlertCircle, { className: "h-5 w-5 shrink-0 text-red-600" }), _jsxs("div", { className: "flex-1", children: [_jsx("p", { className: "text-sm text-red-800", children: error }), countdownSeconds !== null && countdownSeconds > 0 && (_jsxs("p", { className: "text-xs text-red-700 mt-2 font-medium", children: ["Retry available in ", formatRetryTimeSimple(countdownSeconds)] }))] })] })), _jsxs("div", { className: "flex items-center gap-4", children: [_jsxs(Button, { type: "button", variant: "ghost", onClick: onBack, disabled: loading, className: "rounded-full h-10 px-6 text-xs font-bold uppercase tracking-widest text-gray-400", children: [_jsx(ArrowLeft, { className: "mr-2 h-4 w-4" }), "Back"] }), _jsx(Button, { type: "submit", disabled: loading || !email, className: "px-8 h-10 rounded-full shadow-lg shadow-blue-200 transition-all active:scale-95 min-w-[220px] text-xs font-black uppercase tracking-widest bg-blue-600 hover:bg-blue-700 text-white", children: loading ? (_jsxs(_Fragment, { children: [_jsx(RefreshCw, { className: "mr-2 h-4 w-4 animate-spin" }), "Checking..."] })) : (_jsxs(_Fragment, { children: ["Continue", _jsx(ArrowRight, { className: "ml-2 h-4 w-4", strokeWidth: 3 })] })) })] })] }), _jsx("button", { type: "button", onClick: () => {
                    if (!email) {
                        setError("Please enter your email address first.");
                        return;
                    }
                    onNext({ email, mode: "code_entry" });
                }, disabled: loading, className: "mt-5 text-xs font-semibold uppercase tracking-wider text-blue-600 hover:text-blue-700 disabled:opacity-50", children: "I already have a code" })] }));
}
//# sourceMappingURL=LicenseEmailStep.js.map