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 p-12 text-center", children: [_jsx("div", { className: "bg-feedback-blue-light ring-feedback-blue mb-8 rounded-2xl p-6 ring-1", children: _jsx(KeyRound, { className: "text-feedback-blue h-16 w-12", strokeWidth: 1.5 }) }), _jsx("h2", { className: "text-neutral-grey-100 mb-4 text-3xl font-bold tracking-tight", children: "License Activation" }), _jsx("p", { className: "text-neutral-grey-50 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: "mb-6 space-y-4", 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: "border-border-default focus:ring-feedback-blue h-11 rounded-xl bg-white" }) }), error && (_jsxs("div", { className: "border-feedback-red bg-feedback-red-light mb-8 flex max-w-md items-start gap-3 rounded-xl border p-4 text-left", children: [_jsx(AlertCircle, { className: "text-feedback-red h-5 w-5 shrink-0" }), _jsxs("div", { className: "flex-1", children: [_jsx("p", { className: "text-feedback-red text-sm", children: error }), countdownSeconds !== null && countdownSeconds > 0 && (_jsxs("p", { className: "text-feedback-red mt-2 text-xs font-medium", children: ["Retry available in ", formatRetryTimeSimple(countdownSeconds)] }))] })] })), _jsxs("div", { className: "flex items-center gap-4", children: [_jsxs(Button, { type: "button", variant: "ghost", size: "lg", onClick: onBack, disabled: loading, children: [_jsx(ArrowLeft, { className: "mr-2 h-4 w-4" }), "Back"] }), _jsx(Button, { type: "submit", size: "lg", disabled: loading || !email, className: "min-w-[220px]", 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", variant: "link", onClick: () => {
                    if (!email) {
                        setError("Please enter your email address first.");
                        return;
                    }
                    onNext({ email, mode: "code_entry" });
                }, disabled: loading, className: "mt-5", children: "I already have a code" })] }));
}
//# sourceMappingURL=LicenseEmailStep.js.map