javascript:!function(){

    if ("www.amazon.it" !== window.location.hostname)
        return void alert("Questo bookmark funziona solo su amazon.it");

    // Helper function to create elements with attributes
    const o = (e, t) => Object.assign(document.createElement(e), t);

    let n = false, i = null;

    // Function to display the results in a modal dialog
    const r = (content, noClose = false) => {
        const modal = document.getElementById("amazon-offers-results") || o("div", {
            id: "amazon-offers-results",
            style: "position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:white;padding:20px;border-radius:10px;box-shadow:0 0 10px rgba(0,0,0,0.5);z-index:10000;max-width:90%;width:350px;max-height:90vh;font-family:Arial,sans-serif;display:flex;flex-direction:column;"
        });
        modal.innerHTML = &lt;div style="flex:1;overflow-y:auto;margin-bottom:15px;"&gt;${content}&lt;/div&gt;;
        if (!noClose) {
            const btnContainer = o("div", {
                style: "display:flex;flex-wrap:wrap;justify-content:space-between;padding-top:15px;border-top:1px solid #e0e0e0;"
            });
            const createButton = (text, onClick) => o("button", {
                textContent: text,
                style: "padding:10px;background-color:#f0f0f0;border:none;border-radius:5px;cursor:pointer;font-size:16px;color:#333;flex:1 0 calc(33.33% - 10px);margin:5px;",
                onclick: onClick
            });
            btnContainer.append(
                createButton("Chiudi", () => {
                    document.body.removeChild(modal);
                    n = false;
                    if (i) {
                        window.removeEventListener("focus", i);
                        i = null;
                    }
                }),
                createButton("Cambia account", () => {
                    n = false;
                    if (i) {
                        window.removeEventListener("focus", i);
                        i = null;
                    }
                    window.location.href = https://www.amazon.it/ap/signin?openid.pape.max_auth_age=0&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.assoc_handle=anywhere_v2_it&openid.mode=checkid_setup&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.ns=http://specs.openid.net/auth/2.0&switch_account=picker&ignoreAuthState=1&_encoding=UTF8&forceReload=${Date.now()}
                }),
                createButton("Cancella dati", () => {
                    localStorage.removeItem("amazonGeneralOfferData");
                    localStorage.removeItem("amazonEmailOfferData");
                    alert("Tutti i dati memorizzati sono stati cancellati.");
                })
            );
            modal.appendChild(btnContainer);
        }
        document.body.appendChild(modal);
    };

    // Function to get the email of the logged-in user
    const l = async () => {
        try {
            const res = await fetch("https://www.amazon.it/ax/account/manage");
            if (res.url.includes("signin")) {
                return window.location.pathname.includes("/ap/signin") ? null : window.location.href = res.url, null;
            }
            const text = await res.text();
            return (new DOMParser)
                .parseFromString(text, "text/html")
                .querySelector("#a-page > div.a-container")
                .innerText.match(/ModificaE-mail\s*(.?)\sModificaNumero/)[1].trim() || "Email non trovata";
        } catch {
            return "Errore nel recupero dell'email";
        }
    };

    // Function to check eligibility for a specific offer
    const s = async (e) => {
        const page = await (async e => {
            const res = await fetch(e);
            return (new DOMParser).parseFromString(await res.text(), "text/html");
        })(https://www.amazon.it/yourpromotions/${e});
        const applyButton = page.querySelector("button#nslp-ajax-button-announce");
        const successBox = page.querySelector(".a-box.a-alert.a-alert-success");
        const header = page.querySelector('[class^="nudge_info_header"]');
        return {
            url: e,
            description: header?.innerText.trim() || "Offerta senza descrizione",
            isEligible: (applyButton && applyButton.textContent.trim() === "Applica promozione" && !applyButton.disabled) || (successBox && successBox.innerText.toLowerCase().includes("congratulazioni")),
            details: successBox ? successBox.innerText.trim() : ""
        };
    };

    // Function to check the cart offer eligibility
    const t = async () => {
        try {
            const res = await fetch("https://www.amazon.it/gp/cart/view.html");
            const text = await res.text();
            const doc = (new DOMParser).parseFromString(text, "text/html");
            const bannerText = doc.getElementById("maple-banner__text")?.innerText.trim().split("\n")?.at(1);
            return {
                isEligible: !!bannerText,
                description: bannerText || "Nessuna offerta del carrello disponibile"
            };
        } catch {
            return {
                isEligible: false,
                description: "Errore nel controllo del banner del carrello"
            };
        }
    };

    // Function to store offer data
    const c = (email, offers, cartOffer) => {
        let generalOffers = JSON.parse(localStorage.getItem("amazonGeneralOfferData") || "{}");
        let emailOffers = JSON.parse(localStorage.getItem("amazonEmailOfferData") || "{}");

        // Store general offers
        offers.forEach((offer, index) => {
            generalOffers[index + 1] = {
                url: offer.url,
                description: offer.description
            };
        });

        // Add cart offer to generalOffers
        const cartOfferIndex = offers.length + 1;
        generalOffers[cartOfferIndex] = {
            url: "https://www.amazon.it/gp/cart/view.html",
            description: cartOffer.description || "Offerta del carrello"
        };

        // Store email-specific data
        emailOffers[email] = {
            offerEligibility: [...offers.map(offer => offer.isEligible), cartOffer.isEligible],
            offerDetails: [...offers.map(offer => offer.details || ""), cartOffer.description || ""],
            timestamp: Date.now()
        };

        localStorage.setItem("amazonGeneralOfferData", JSON.stringify(generalOffers));
        localStorage.setItem("amazonEmailOfferData", JSON.stringify(emailOffers));
    };

    // Function to format the timestamp
    const d = e => {
        const now = new Date();
        const time = new Date(e);
        const days = now.getDate() - time.getDate();
        const months = now.getMonth() - time.getMonth();
        const years = now.getFullYear() - time.getFullYear();
        if (years === 0 && months === 0 && days === 0) return "Oggi";
        if (years === 0 && months === 0 && days === 1) return "Ieri";
        if (days <= 7) return "Meno di una settimana fa";
        if (days <= 30) return "Più di una settimana fa";
        return "Oltre un mese fa";
    };

    // Function to update the bullet points on the sign-in page
    const p = () => {
        document.querySelectorAll("span[data-email-processed]").forEach(e => {
            e.outerHTML = e.textContent.split(" ")[0].toLocaleLowerCase();
        });

        const emailRegex = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b/g;
        const generalOffers = JSON.parse(localStorage.getItem("amazonGeneralOfferData") || "{}");
        const emailOffers = JSON.parse(localStorage.getItem("amazonEmailOfferData") || "{}");

        const processNode = node => {
            if (node.nodeType === Node.TEXT_NODE && emailRegex.test(node.textContent)) {
                const fragment = document.createDocumentFragment();
                let lastIndex = 0;
                node.textContent.replace(emailRegex, function(match, index) {
                    fragment.appendChild(document.createTextNode(node.textContent.slice(lastIndex, index)));
                    const span = document.createElement("span");
                    span.textContent = match;
                    span.setAttribute("data-email-processed", "true");

                    const emailData = emailOffers[match];
                    if (emailData) {
                        const eligibility = emailData.offerEligibility;
                        const offerDetails = emailData.offerDetails;

                        const eligibleOffers = eligibility.map((isEligible, idx) => {
                            if (isEligible) return generalOffers[idx + 1]?.description;
                            return null;
                        }).filter(Boolean);

                        if (eligibleOffers.length > 0) {
                            span.textContent += " ✓";
                            span.style.color = "green";
                            const ul = o("ul", {
                                innerHTML: eligibleOffers.map(desc => &lt;li&gt;${desc}&lt;/li&gt;).join("") + &lt;li style="list-style-type:none;font-style:italic;margin-top:5px;"&gt;(Ultimo controllo: ${d(emailData.timestamp)})&lt;/li&gt;,
                                style: "font-size:0.9em;color:#333;margin-top:5px;list-style-type:disc;padding-left:20px;word-wrap:break-word;white-space:normal;overflow-wrap:break-word;"
                            });
                            ul.querySelectorAll("li").forEach(li => {
                                li.style.wordWrap = "break-word";
                                li.style.whiteSpace = "normal";
                                li.style.overflowWrap = "break-word";
                            });
                            span.appendChild(ul);
                        } else {
                            span.textContent += " ✗";
                            span.style.color = "red";
                            const ul = o("ul", {
                                innerHTML: &lt;li style="list-style-type:none;font-style:italic;"&gt;(Ultimo controllo: ${d(emailData.timestamp)})&lt;/li&gt;,
                                style: "font-size:0.9em;color:#666;margin-top:5px;list-style-type:disc;padding-left:20px;word-wrap:break-word;white-space:normal;overflow-wrap:break-word;"
                            });
                            span.appendChild(ul);
                        }
                    }

                    fragment.appendChild(span);
                    lastIndex = index + match.length;
                });
                fragment.appendChild(document.createTextNode(node.textContent.slice(lastIndex)));
                node.parentNode.replaceChild(fragment, node);
            } else if (node.nodeType === Node.ELEMENT_NODE) {
                Array.from(node.childNodes).forEach(processNode);
            }
        };

        processNode(document.body);
    };

    // Main execution function
    (async () => {
        try {
            // Check if on the sign-in page
            if (window.location.pathname.includes("/ap/signin")) {
                n = true;
                p();
                if (!i) {
                    i = () => {
                        if (n) p();
                    };
                    window.addEventListener("focus", i);
                }
                return;
            }

            // Get user email
            const email = await l();
            if (email === null) return;

            // Show loading spinner
            r('<div style="display:flex;justify-content:center;align-items:center;height:100px;"><div style="width:50px;height:50px;border:5px solid #f3f3f3;border-top:5px solid #3498db;border-radius:50%;animation:spin 1s linear infinite;"></div></div><style>@keyframes spin{0%{transform:rotate(0deg);}100%{transform:rotate(360deg);}}</style>', true);

            let storedEmail = localStorage.getItem("clickedEmail");
            if (storedEmail) {
                localStorage.removeItem("clickedEmail");
            } else {
                storedEmail = email;
            }

            // List of offer IDs to check
            const offerIds = [
                "c7e3cd4b-6645-4e0f-acf8-9d1e4016e959",
                "e03ab188-5219-48be-8bae-4967ee09df13",
                "d06aa3a3-d2e6-41d5-a1c2-d7c0768ba7c3",
                "cb3eab28-e1b5-46e5-9031-36c79f6a9405"
            ];

            // Check each offer
            const offerPromises = offerIds.map(s);
            const offerResults = await Promise.all(offerPromises);

            // Check cart offer
            const cartOfferResult = await t();

            // Store the offer data
            c(storedEmail, offerResults, cartOfferResult);

            // Display the results
            r(((email, offers, cartOffer) => <br/> &lt;h2 style="margin-top:0;color:#333;"&gt;Risultati Offerte Amazon&lt;/h2&gt;<br/> &lt;p style="margin-bottom:15px;word-break:break-word;"&gt;Email: ${email}&lt;/p&gt;<br/> ${offers.map(offer =&gt; 
                    <a href="https://www.amazon.it/yourpromotions/${offer.url}" target="blank" style="color:${offer.isEligible ? "green" : "red"};text-decoration:none;display:block;margin-bottom:10px;word-break:break-word;">
                        ${offer.isEligible ? "Sei idoneo" : "Non sei idoneo"} per l'offerta: ${offer.description}
                        ${offer.details ? &lt;br&gt;&lt;span style="font-size:0.9em;color:#666;"&gt;${offer.details}&lt;/span&gt; : ""}
                    </a>
                ).join("")}<br/> &lt;a href="https://www.amazon.it/gp/cart/view.html" target="_blank" style="color:${cartOffer.isEligible ? "green" : "red"};text-decoration:none;display:block;margin-bottom:10px;word-break:break-word;"&gt;<br/> ${cartOffer.isEligible ? "Sei idoneo per l'offerta del carrello" : "Non sei idoneo per l'offerta del carrello"}<br/> ${cartOffer.isEligible ? : ${cartOffer.description}: ""}<br/> &lt;/a&gt;<br/> )(storedEmail, offerResults, cartOfferResult));

        } catch (e) {
            r(&lt;h2 style="margin-top:0;color:#333;"&gt;Errore&lt;/h2&gt;&lt;p&gt;Errore generale: ${e.message}&lt;/p&gt;);
        }
    })();

    // Event listener for account switch on the sign-in page
    document.body.addEventListener("click", function(event) {
        const accountLink = event.target.closest('a[data-name="switch_account_request"]');
        if (accountLink) {
            event.preventDefault();
            event.stopPropagation();
            const csrfToken = document.querySelector('input[name="CsrfToken"]').value;
            const switchAccountRequest = accountLink.getAttribute("data-value");
            const emailMatch = accountLink.textContent.match(/\b[A-Za-z0-9.%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b/);
            const email = emailMatch ? emailMatch[0].toLowerCase() : null;
            let redirectUrl = "";
            const formData = {
                CsrfToken: csrfToken,
                switch_account_request: switchAccountRequest
            };
            fetch("https://www.amazon.it/ap/switchaccount", {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: new URLSearchParams(formData),
                credentials: "include",
                redirect: "manual"
            })
                .then(res => res.json())
                .catch(() => {})
                .then(data => {
                    if (data.redirectUrl && data.redirectUrl.includes("signin")) {
                        redirectUrl = data.redirectUrl;
                    }
                    return fetch("https://www.amazon.it/ax/account/manage");
                })
                .then(res => {
                    if (res.url.includes("signin")) {
                        window.open(redirectUrl || res.url, "_blank");
                        return null;
                    }
                    return res.text();
                })
                .then(text => {
                    if (text !== null) {
                        const currentEmail = (new DOMParser)
                            .parseFromString(text, "text/html")
                            .querySelector("#a-page > div.a-container")
                            .innerText.match(/ModificaE-mail\s*(.?)\sModificaNumero/)[1]
                            .trim()
                            .toLowerCase();
                        if (currentEmail === email) {
                            localStorage.setItem("clickedEmail", email);
                            (async () => {
                                try {
                                    const storedEmail = localStorage.getItem("clickedEmail");
                                    localStorage.removeItem("clickedEmail");
                                    const offerPromises = offerIds.map(s);
                                    const offerResults = await Promise.all(offerPromises);
                                    const cartOfferResult = await t();
                                    c(storedEmail, offerResults, cartOfferResult);
                                    p();
                                } catch (e) {
                                    console.error(e);
                                }
                            })();
                        } else if (redirectUrl) {
                            window.open(redirectUrl, "_blank");
                        }
                    }
                });
        }
    }, true);

}();