"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useRef, useEffect } from "react";
import { formatRetryTimeSimple } from "./licenseService";
export function LicenseCodeEntry({ email, onSubmit, onBack, error, retryAfterSeconds, }) {
    const [code, setCode] = useState(["", "", "", "", "", ""]);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [countdownSeconds, setCountdownSeconds] = useState(null);
    const inputRefs = useRef([]);
    const isRetryLocked = countdownSeconds !== null && countdownSeconds > 0;
    // Focus first input on mount
    useEffect(() => {
        inputRefs.current[0]?.focus();
    }, []);
    useEffect(() => {
        setCountdownSeconds(retryAfterSeconds && retryAfterSeconds > 0 ? retryAfterSeconds : null);
    }, [retryAfterSeconds]);
    useEffect(() => {
        if (countdownSeconds === null || countdownSeconds <= 0) {
            return;
        }
        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 handleChange = (index, value) => {
        if (isRetryLocked)
            return;
        // Only allow digits
        const digit = value.replace(/\D/g, "").slice(-1);
        const newCode = [...code];
        newCode[index] = digit;
        setCode(newCode);
        // Auto-focus next input
        if (digit && index < 5) {
            inputRefs.current[index + 1]?.focus();
        }
        // Auto-submit when all digits entered
        if (digit && index === 5) {
            const fullCode = newCode.join("");
            if (fullCode.length === 6) {
                handleSubmit(fullCode);
            }
        }
    };
    const handleKeyDown = (index, e) => {
        if (isRetryLocked)
            return;
        if (e.key === "Backspace" && !code[index] && index > 0) {
            // Move to previous input on backspace if current is empty
            inputRefs.current[index - 1]?.focus();
        }
    };
    const handlePaste = (e) => {
        if (isRetryLocked)
            return;
        e.preventDefault();
        const pastedData = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 6);
        if (pastedData) {
            const newCode = [...code];
            for (let i = 0; i < pastedData.length && i < 6; i++) {
                newCode[i] = pastedData.charAt(i);
            }
            setCode(newCode);
            // Focus appropriate input
            const nextEmptyIndex = Math.min(pastedData.length, 5);
            inputRefs.current[nextEmptyIndex]?.focus();
            // Auto-submit if complete
            if (pastedData.length === 6) {
                handleSubmit(pastedData);
            }
        }
    };
    const handleSubmit = async (fullCode) => {
        if (isRetryLocked)
            return;
        const codeToSubmit = fullCode || code.join("");
        if (codeToSubmit.length !== 6)
            return;
        setIsSubmitting(true);
        try {
            await onSubmit(codeToSubmit);
        }
        finally {
            setIsSubmitting(false);
        }
    };
    return (_jsxs("div", { className: "w-full max-w-md", "data-testid": "license-code-entry", children: [_jsx("h2", { className: "text-3xl font-bold text-gray-900 text-center tracking-tight", children: "Enter Activation Code" }), _jsxs("p", { className: "mt-3 text-gray-500 text-center leading-relaxed", children: ["We've sent a 6-digit code to", " ", _jsx("span", { className: "font-medium text-gray-700", children: email })] }), _jsx("div", { className: "mt-8 flex justify-center gap-2", "data-testid": "license-code-inputs", children: code.map((digit, index) => (_jsx("input", { ref: (el) => {
                        inputRefs.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) => handleChange(index, e.target.value), onKeyDown: (e) => handleKeyDown(index, e), onPaste: handlePaste, disabled: isSubmitting || 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: "mt-4 rounded-xl border border-red-100 bg-red-50 p-3 text-sm text-red-800 text-center", children: [_jsx("p", { children: error }), isRetryLocked && (_jsxs("p", { className: "mt-2 text-xs font-medium text-red-700", children: ["Retry available in ", formatRetryTimeSimple(countdownSeconds)] }))] })), _jsxs("p", { className: "mt-6 text-center text-sm text-gray-500", children: ["Didn't receive the code?", " ", _jsx("button", { onClick: onBack, disabled: isSubmitting, className: "text-blue-600 hover:underline disabled:opacity-50", children: "Try again" })] }), _jsxs("div", { className: "mt-6 flex gap-3", children: [_jsx("button", { onClick: onBack, disabled: isSubmitting, className: "flex-1 rounded-full h-10 border border-gray-200 px-6 text-xs font-bold uppercase tracking-widest text-gray-500 transition-colors hover:bg-gray-50 disabled:opacity-50", children: "Back" }), _jsx("button", { onClick: () => handleSubmit(), disabled: isSubmitting || isRetryLocked || code.join("").length !== 6, className: "flex-1 rounded-full h-10 bg-blue-600 px-8 text-xs font-black uppercase tracking-widest text-white shadow-lg shadow-blue-200 transition-all hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50", children: isSubmitting ? (_jsxs("span", { className: "flex items-center justify-center gap-2", children: [_jsxs("svg", { className: "h-5 w-5 animate-spin", viewBox: "0 0 24 24", fill: "none", children: [_jsx("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), _jsx("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })] }), "Verifying..."] })) : ("Verify") })] })] }));
}
//# sourceMappingURL=LicenseCodeEntry.js.map