---
import * as QR from "qrcode";

interface Props {
    data: string;
    size?: number;
    alt?: string;
}

const { data, size = 200, alt = "QR Code" } = Astro.props;

// Generate QR code for dark mode
let darkModeQR = "";
try {
    darkModeQR = await QR.toDataURL(data, {
        width: size,
        margin: 2,
        color: {
            dark: "#FFBF00",
            light: "#17181C",
        },
    });
} catch (err) {
    console.error("Failed to generate dark mode QR code:", err);
}

// Generate QR code for light mode
let lightModeQR = "";
try {
    lightModeQR = await QR.toDataURL(data, {
        width: size,
        margin: 2,
        color: {
            dark: "#F24B3C",
            light: "#FFFFFF",
        },
    });
} catch (err) {
    console.error("Failed to generate light mode QR code:", err);
}

const uniqueId = `qr-${Math.random().toString(36).substr(2, 9)}`;
---

{
    (darkModeQR || lightModeQR) && (
        <img
            id={uniqueId}
            alt={alt}
            width={size}
            height={size}
            data-light-src={lightModeQR}
            data-dark-src={darkModeQR}
            style="margin: auto;"
        />
    )
}

<script is:inline define:vars={{ uniqueId, lightModeQR, darkModeQR }}>
    (function () {
        const img = document.getElementById(uniqueId);
        if (!img) return;

        const theme = document.documentElement.getAttribute("data-theme");
        if (theme === "dark" && darkModeQR) {
            img.setAttribute("src", darkModeQR);
        } else if (lightModeQR) {
            img.setAttribute("src", lightModeQR);
        }
    })();
</script>

<script>
    function updateQRCodes() {
        const theme = document.documentElement.getAttribute("data-theme");
        const qrImages = document.querySelectorAll(
            "img[data-light-src][data-dark-src]",
        );

        qrImages.forEach((img) => {
            const lightSrc = img.getAttribute("data-light-src");
            const darkSrc = img.getAttribute("data-dark-src");

            if (theme === "dark" && darkSrc) {
                img.setAttribute("src", darkSrc);
            } else if (lightSrc) {
                img.setAttribute("src", lightSrc);
            }
        });
    }

    // Set initial theme on page load
    updateQRCodes();

    // Watch for theme changes
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            if (
                mutation.type === "attributes" &&
                mutation.attributeName === "data-theme"
            ) {
                updateQRCodes();
            }
        });
    });

    observer.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ["data-theme"],
    });
</script>
