function loadUser() { return window.EA?.currentUser?.() || null; }
function saveUser() { }
async function signOut() { if (window.EA?.logout)
    await window.EA.logout(); }
function SignInModal({ open, onClose, onSignedIn }) {
    const designPreview = window.EA_UI_PREVIEW === true;
    const [mode, setMode] = React.useState("signin");
    const [step, setStep] = React.useState("request");
    const [name, setName] = React.useState("");
    const [email, setEmail] = React.useState("");
    const [requestedEmail, setRequestedEmail] = React.useState("");
    const [verifiedUser, setVerifiedUser] = React.useState(null);
    const [otp, setOtp] = React.useState("");
    const [error, setError] = React.useState("");
    const [notice, setNotice] = React.useState("");
    const [busy, setBusy] = React.useState(false);
    const [cooldown, setCooldown] = React.useState(0);
    const dialogRef = React.useRef(null);
    const requestVersion = React.useRef(0);
    const busyRef = React.useRef(busy);
    const closeRef = React.useRef(onClose);
    busyRef.current = busy;
    closeRef.current = onClose;
    React.useEffect(() => {
        requestVersion.current++;
        if (open) {
            setMode("signin");
            setStep("request");
            setName("");
            setEmail("");
            setRequestedEmail("");
            setVerifiedUser(null);
            setOtp("");
            setError("");
            setNotice("");
            setBusy(false);
            setCooldown(0);
        }
        else {
            setMode("signin");
            setStep("request");
            setError("");
            setNotice("");
            setBusy(false);
        }
    }, [open]);
    React.useEffect(() => {
        if (!open)
            return;
        const orig = document.body.style.overflow;
        document.body.style.overflow = "hidden";
        return () => { document.body.style.overflow = orig; };
    }, [open]);
    React.useEffect(() => {
        if (!open)
            return;
        const previous = document.activeElement;
        const focus = setTimeout(() => (dialogRef.current?.querySelector('input:not([disabled])') || dialogRef.current?.querySelector('button:not([disabled])'))?.focus(), 0);
        const onKey = event => {
            if (event.key === 'Escape' && !busyRef.current) {
                event.preventDefault();
                closeRef.current?.();
            }
            if (event.key !== 'Tab')
                return;
            const nodes = Array.from(dialogRef.current?.querySelectorAll('button:not([disabled]),input:not([disabled]),a[href]') || []).filter(node => !node.hidden);
            const first = nodes[0], last = nodes[nodes.length - 1];
            if (!first) {
                event.preventDefault();
                dialogRef.current?.focus();
                return;
            }
            if (event.shiftKey && (document.activeElement === first || !dialogRef.current?.contains(document.activeElement))) {
                event.preventDefault();
                last.focus();
            }
            else if (!event.shiftKey && (document.activeElement === last || !dialogRef.current?.contains(document.activeElement))) {
                event.preventDefault();
                first.focus();
            }
        };
        document.addEventListener('keydown', onKey);
        return () => { clearTimeout(focus); document.removeEventListener('keydown', onKey); previous?.focus?.(); };
    }, [open]);
    React.useEffect(() => {
        if (!open || cooldown <= 0)
            return;
        const timer = setTimeout(() => setCooldown(value => Math.max(0, value - 1)), 1000);
        return () => clearTimeout(timer);
    }, [open, cooldown]);
    const validateEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
    const isSignup = mode === "signup";
    const switchMode = (nextMode) => {
        if (busy)
            return;
        setMode(nextMode);
        setStep("request");
        setOtp("");
        setRequestedEmail("");
        setVerifiedUser(null);
        setError("");
        setNotice("");
    };
    const requestCode = async () => {
        if (designPreview || busy || (step === "verify" && cooldown > 0))
            return;
        const version = requestVersion.current;
        setError("");
        setNotice("");
        const cleanEmail = email.trim().toLowerCase();
        if (isSignup && name.trim().length < 2) {
            setError("Please enter your name.");
            return;
        }
        if (!validateEmail(cleanEmail)) {
            setError("Please enter a valid email address.");
            return;
        }
        if (!window.EA) {
            setError("Sign-in is unavailable. Refresh the page and try again.");
            return;
        }
        setBusy(true);
        try {
            const response = await window.EA.sendOTP({
                email: cleanEmail,
                name: isSignup ? name.trim() : undefined,
            });
            if (version !== requestVersion.current)
                return;
            setCooldown(60);
            setRequestedEmail(cleanEmail);
            setOtp("");
            setStep("verify");
            const isLocal = ['localhost', '127.0.0.1', '::1', '[::1]'].includes(window.location?.hostname);
            const localCode = isLocal && typeof response?.dev_otp === 'string' && /^\d{6}$/.test(response.dev_otp) ? response.dev_otp : null;
            setNotice(localCode ? `Local preview code: ${localCode}. Use this code to continue.` : `We sent a 6-digit code to ${cleanEmail}.`);
        }
        catch (err) {
            if (version === requestVersion.current) {
                if (err.status === 429 && step === 'verify')
                    setCooldown(Math.max(60, err.retryAfter || 0));
                setError(err.message || "Could not send the code. Please try again.");
            }
        }
        finally {
            if (version === requestVersion.current)
                setBusy(false);
        }
    };
    const verifyCode = async () => {
        if (designPreview || busy)
            return;
        const version = requestVersion.current;
        setError("");
        const cleanEmail = (requestedEmail || email).trim().toLowerCase();
        const cleanOtp = otp.replace(/\D/g, "").slice(0, 6);
        if (!validateEmail(cleanEmail)) {
            setError("Please enter a valid email address.");
            setStep("request");
            return;
        }
        if (!verifiedUser && cleanOtp.length !== 6) {
            setError("Enter the 6-digit code from your email.");
            return;
        }
        if (!window.EA) {
            setError("Sign-in is unavailable. Refresh the page and try again.");
            return;
        }
        setBusy(true);
        try {
            const verified = verifiedUser ? { user: verifiedUser } : await window.EA.verifyOTP(cleanEmail, cleanOtp);
            if (!verified?.user?.id)
                throw new Error('Your session could not be confirmed. Please try again.');
            if (version !== requestVersion.current)
                return;
            let userData = verified.user;
            setVerifiedUser(userData);
            if (isSignup && name.trim() && userData.name !== name.trim()) {
                try {
                    const profile = await window.EA.updateProfile({ name: name.trim() });
                    if (profile.user)
                        userData = profile.user;
                }
                catch (err) {
                    if (version !== requestVersion.current)
                        return;
                    if (err.status === 401) {
                        setVerifiedUser(null);
                        setStep('request');
                        setOtp('');
                    }
                    else {
                        setStep('profile');
                        setNotice('Your email is verified. You can save your name now or continue with your account.');
                    }
                    throw err;
                }
            }
            if (version !== requestVersion.current)
                return;
            saveUser(userData);
            onSignedIn && onSignedIn(userData);
        }
        catch (err) {
            if (version === requestVersion.current)
                setError(err.message || "Could not verify the code. Please try again.");
        }
        finally {
            if (version === requestVersion.current)
                setBusy(false);
        }
    };
    const submit = () => {
        if (step === "verify" || step === "profile")
            return verifyCode();
        return requestCode();
    };
    if (!open)
        return null;
    const title = designPreview ? "You’re in the design preview" : step === "profile" ? "Finish your account" : step === "verify"
        ? "Enter your code"
        : (isSignup ? "Create your account" : "Welcome back");
    const description = designPreview
        ? "Account sign-in is unavailable in this preview. You can keep exploring templates and editing your invitation, but changes are not saved to an account."
        : step === "profile"
            ? "Choose the name you want to see in your dashboard."
            : step === "verify"
                ? "Use your one-time code to continue."
                : (isSignup
                    ? "Verify your email, save designs, publish invitations, and manage RSVPs."
                    : "Save your designs, share your invitation, and keep every guest response together.");
    return (React.createElement("div", { className: "signin-overlay account-auth-overlay", onClick: (e) => { if (!busy && e.target === e.currentTarget)
            onClose && onClose(); } },
        React.createElement("div", { ref: dialogRef, className: "signin-modal account-auth-modal", role: "dialog", tabIndex: -1, "aria-modal": "true", "aria-labelledby": "signin-title", "aria-describedby": "signin-description", "aria-busy": busy },
            React.createElement("button", { type: "button", className: "signin-close", onClick: onClose, "aria-label": "Close sign-in", disabled: busy }, "\u00D7"),
            React.createElement("div", { className: "signin-logo" },
                React.createElement("span", { className: "logo-mark" }, "e"),
                React.createElement("span", null,
                    "Everafter ",
                    React.createElement("small", { style: { display: "block", fontSize: 10 } }, "by Makebiodata.shop"))),
            React.createElement("div", { className: "signin-step" },
                React.createElement("h2", { id: "signin-title", className: "serif", style: { fontSize: 30, fontWeight: 500, marginBottom: 6 } }, title),
                React.createElement("p", { id: "signin-description", className: "muted", style: { fontSize: 14, marginBottom: 24 } }, description),
                designPreview ? (React.createElement("button", { type: "button", className: "signin-btn-primary", onClick: onClose }, "Return to your preview")) : React.createElement(React.Fragment, null,
                    step === "request" && (React.createElement("div", { className: "signin-mode-switch", role: "group", "aria-label": "Account access" },
                        React.createElement("button", { type: "button", "aria-pressed": mode === "signin", disabled: busy, className: mode === "signin" ? "active" : "", onClick: () => switchMode("signin") }, "Sign in"),
                        React.createElement("button", { type: "button", "aria-pressed": mode === "signup", disabled: busy, className: mode === "signup" ? "active" : "", onClick: () => switchMode("signup") }, "Create account"))),
                    React.createElement("form", { onSubmit: (e) => { e.preventDefault(); submit(); } },
                        step === "request" || step === "profile" ? (React.createElement(React.Fragment, null,
                            isSignup && (React.createElement("label", { className: "signin-field" },
                                React.createElement("span", null, "Name"),
                                React.createElement("input", { type: "text", autoFocus: true, placeholder: "Your name", value: name, onChange: (e) => setName(e.target.value), disabled: busy, autoComplete: "name", maxLength: 100, required: true }))),
                            step === 'request' && React.createElement("label", { className: "signin-field" },
                                React.createElement("span", null, "Email"),
                                React.createElement("input", { type: "email", autoFocus: !isSignup, placeholder: "you@example.com", value: email, onChange: (e) => setEmail(e.target.value), disabled: busy, autoComplete: "email", inputMode: "email", autoCapitalize: "none", spellCheck: false, maxLength: 254, required: true })))) : (React.createElement(React.Fragment, null,
                            React.createElement("div", { className: "signin-code-target" },
                                React.createElement("span", null, requestedEmail),
                                React.createElement("button", { type: "button", className: "signin-inline-action", onClick: () => { setStep("request"); setOtp(""); setError(""); setNotice(""); }, disabled: busy }, "Change email")),
                            React.createElement("label", { className: "signin-field" },
                                React.createElement("span", null, "6-digit code"),
                                React.createElement("input", { className: "signin-otp-input", type: "text", inputMode: "numeric", pattern: "[0-9]*", maxLength: "6", autoFocus: true, placeholder: "000000", value: otp, onChange: (e) => setOtp(e.target.value.replace(/\D/g, "").slice(0, 6)), disabled: busy, autoComplete: "one-time-code" })))),
                        notice && React.createElement("div", { className: "signin-notice", role: "status" }, notice),
                        error && React.createElement("div", { className: "signin-error", role: "alert" }, error),
                        React.createElement("button", { type: "submit", className: "signin-btn-primary", disabled: busy }, busy ? (step === 'profile' ? 'Saving your name…' : step === "verify" ? "Verifying…" : "Sending code…") : (step === 'profile' ? 'Save name and continue' : step === "verify" ? "Verify and continue" : "Send email code"))),
                    step === 'profile' ? React.createElement("p", { className: "signin-fineprint" },
                        React.createElement("button", { type: "button", className: "signin-inline-action", disabled: busy, onClick: () => onSignedIn?.(verifiedUser) }, "Continue without changing your name")) : step === "verify" ? (React.createElement("p", { className: "signin-fineprint" },
                        "Did not get the code?",
                        " ",
                        React.createElement("button", { type: "button", className: "signin-inline-action", onClick: requestCode, disabled: busy || cooldown > 0 }, cooldown > 0 ? `Resend in ${cooldown}s` : "Resend code"))) : (React.createElement("p", { className: "signin-fineprint" },
                        isSignup ? "Already have an account?" : "New here?",
                        " ",
                        React.createElement("button", { type: "button", className: "signin-inline-action", disabled: busy, onClick: () => switchMode(isSignup ? "signin" : "signup") }, isSignup ? "Sign in" : "Create an account"))),
                    step === "request" && React.createElement("p", { className: "signin-security-note" }, "A one-time email code. No password to remember."))))));
}
Object.assign(window, { SignInModal, loadUser, saveUser, signOut });
