import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { clearLicenseCache, formatRetryTimeSimple, requestLicense, storeLicense, verifyActivationCode, } from "../../../licensing/licenseService";
import { setupWizardService } from "../../../setup/services/setupWizardService";
import { AlertCircle, ArrowLeft, ArrowRight, CheckCircle, KeyRound, RefreshCw, } from "lucide-react";
export function LicenseActivationStep({ email, mode, onBack, onActivated, }) {
    const [name, setName] = useState("");
    const [companyName, setCompanyName] = useState("");
    const [codeDigits, setCodeDigits] = useState(["", "", "", "", "", ""]);
    const codeInputRefs = useRef([]);
    const [loading, setLoading] = useState(false);
    const [success, setSuccess] = useState(false);
    const [error, setError] = useState(null);
    const [retryAfterSeconds, setRetryAfterSeconds] = useState(null);
    const isTrialFlow = useMemo(() => mode === "trial_form", [mode]);
    const trialFormComplete = useMemo(() => name.trim().length > 0 && companyName.trim().length > 0, [name, companyName]);
    const codeComplete = useMemo(() => codeDigits.every((d) => d.length === 1) && codeDigits.join("").length === 6, [codeDigits]);
    useEffect(() => {
        if (!isTrialFlow) {
            codeInputRefs.current[0]?.focus();
        }
    }, [isTrialFlow]);
    useEffect(() => {
        if (retryAfterSeconds === null || retryAfterSeconds <= 0) {
            return;
        }
        const updateInterval = retryAfterSeconds > 60 ? 60000 : 1000;
        const timer = setInterval(() => {
            setRetryAfterSeconds((prev) => {
                if (prev === null)
                    return null;
                const next = prev - (updateInterval === 60000 ? 60 : 1);
                return next > 0 ? next : 0;
            });
        }, updateInterval);
        return () => clearInterval(timer);
    }, [retryAfterSeconds]);
    const isRetryLocked = retryAfterSeconds !== null && retryAfterSeconds > 0;
    const handleStoreLicense = useCallback(async (license, v2OuterSignature) => {
        const settingsExist = await setupWizardService.getSettingsExists();
        if (!settingsExist) {
            await setupWizardService.createSettingsItem();
        }
        const result = await storeLicense(license, v2OuterSignature);
        if (!result.success) {
            throw new Error(result.message || "Failed to store license.");
        }
        try {
            await clearLicenseCache();
        }
        catch {
            // Non-fatal cache clear; backend will refresh eventually.
        }
    }, []);
    const completePurchasedActivation = useCallback(async (fullCode) => {
        try {
            setLoading(true);
            setError(null);
            setRetryAfterSeconds(null);
            const response = await verifyActivationCode({ email, code: fullCode });
            if (response.status === "rate_limited") {
                setRetryAfterSeconds(response.retryAfterSeconds || 60);
                throw new Error(response.message ||
                    `Too many incorrect activation code attempts. Try again in ${formatRetryTimeSimple(response.retryAfterSeconds || 60)}.`);
            }
            if (response.status !== "purchased" || !response.license) {
                setRetryAfterSeconds(null);
                throw new Error(response.message || "Activation code is invalid.");
            }
            await handleStoreLicense(response.license, response.signature);
            setRetryAfterSeconds(null);
            setSuccess(true);
            setTimeout(() => {
                onActivated();
            }, 800);
        }
        catch (e) {
            setError(e?.message || "License activation failed.");
        }
        finally {
            setLoading(false);
        }
    }, [email, handleStoreLicense, onActivated]);
    const handleActivate = useCallback(async () => {
        if (!isTrialFlow && isRetryLocked) {
            return;
        }
        if (isTrialFlow) {
            try {
                setLoading(true);
                setError(null);
                setRetryAfterSeconds(null);
                if (!name.trim() || !companyName.trim()) {
                    setError("Please provide your name and company name.");
                    return;
                }
                const response = await requestLicense({
                    email,
                    name: name.trim(),
                    companyName: companyName.trim(),
                });
                if (response.status !== "trial" || !response.license) {
                    throw new Error(response.message || "Trial activation failed.");
                }
                await handleStoreLicense(response.license, response.signature);
                setSuccess(true);
                setTimeout(() => {
                    onActivated();
                }, 800);
            }
            catch (e) {
                setError(e?.message || "License activation failed.");
            }
            finally {
                setLoading(false);
            }
            return;
        }
        const code = codeDigits.join("");
        if (code.length !== 6) {
            setError("Please enter the activation code.");
            return;
        }
        await completePurchasedActivation(code);
    }, [
        isTrialFlow,
        name,
        companyName,
        email,
        codeDigits,
        handleStoreLicense,
        onActivated,
        completePurchasedActivation,
        isRetryLocked,
    ]);
    const handleCodeDigitChange = (index, value) => {
        if (isRetryLocked)
            return;
        const digit = value.replace(/\D/g, "").slice(-1);
        setError(null);
        setCodeDigits((prev) => {
            const next = [...prev];
            next[index] = digit;
            if (digit && index < 5) {
                queueMicrotask(() => codeInputRefs.current[index + 1]?.focus());
            }
            const full = next.join("");
            if (digit && index === 5 && full.length === 6) {
                queueMicrotask(() => void completePurchasedActivation(full));
            }
            return next;
        });
    };
    const handleCodeKeyDown = (index, e) => {
        if (isRetryLocked)
            return;
        if (e.key === "Backspace" && !codeDigits[index] && index > 0) {
            codeInputRefs.current[index - 1]?.focus();
        }
    };
    const handleCodePaste = (e) => {
        if (isRetryLocked)
            return;
        e.preventDefault();
        const pasted = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 6);
        if (!pasted)
            return;
        setError(null);
        const padded = Array.from({ length: 6 }, (_, i) => pasted.charAt(i) || "");
        setCodeDigits(padded);
        const focusIdx = Math.min(pasted.length, 5);
        queueMicrotask(() => codeInputRefs.current[focusIdx]?.focus());
        if (pasted.length === 6) {
            void completePurchasedActivation(pasted);
        }
    };
    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: isTrialFlow ? "Start Trial License" : "Enter Activation Code" }), _jsx("p", { className: "text-gray-500 mb-8 max-w-md leading-relaxed", children: isTrialFlow
                    ? "Complete your trial registration. We will store the signed license in Sitecore Settings."
                    : "Enter the one-time code sent to your email. We will verify and store your purchased license." }), success ? (_jsxs("div", { className: "flex flex-col items-center gap-3 text-green-600 animate-in fade-in zoom-in duration-500", children: [_jsx("div", { className: "rounded-full bg-green-100 p-3", children: _jsx(CheckCircle, { className: "h-10 w-10", strokeWidth: 2 }) }), _jsx("span", { className: "font-semibold text-lg", children: "License Activated" })] })) : (_jsxs("form", { className: "w-full max-w-md", onSubmit: (e) => {
                    e.preventDefault();
                    if (loading)
                        return;
                    if (isTrialFlow && !trialFormComplete)
                        return;
                    if (!isTrialFlow && !codeComplete)
                        return;
                    void handleActivate();
                }, children: [_jsx("div", { className: "space-y-4 mb-6", children: isTrialFlow ? (_jsxs(_Fragment, { children: [_jsx(Input, { id: "name", value: name, onChange: (e) => setName(e.target.value), placeholder: "Your name", className: "h-11 rounded-xl border-gray-200 bg-white focus:ring-blue-500" }), _jsx(Input, { id: "company", value: companyName, onChange: (e) => setCompanyName(e.target.value), placeholder: "Company name", className: "h-11 rounded-xl border-gray-200 bg-white focus:ring-blue-500" })] })) : (_jsx("div", { className: "flex justify-center gap-2", "data-testid": "license-code-inputs", children: codeDigits.map((digit, index) => (_jsx("input", { ref: (el) => {
                                    codeInputRefs.current[index] = el;
                                }, type: "text", inputMode: "numeric", maxLength: 1, "aria-label": `Activation code digit ${index + 1}`, "data-testid": index === 0 ? "license-code-input-0" : undefined, value: digit, onChange: (e) => handleCodeDigitChange(index, e.target.value), onKeyDown: (e) => handleCodeKeyDown(index, e), onPaste: handleCodePaste, disabled: loading || isRetryLocked, className: "h-14 w-12 rounded-xl border border-gray-200 bg-white text-center text-2xl font-bold text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500/30 disabled:opacity-50" }, index))) })) }), 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 }), isRetryLocked && (_jsxs("p", { className: "mt-2 text-xs font-medium text-red-700", children: ["Retry available in ", formatRetryTimeSimple(retryAfterSeconds)] }))] })] })), _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 ||
                                    isRetryLocked ||
                                    (isTrialFlow && !trialFormComplete) ||
                                    (!isTrialFlow && !codeComplete), 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" }), "Activating..."] })) : (_jsxs(_Fragment, { children: ["Activate License", _jsx(ArrowRight, { className: "ml-2 h-4 w-4", strokeWidth: 3 })] })) })] })] }))] }));
}
//# sourceMappingURL=LicenseActivationStep.js.map