

import { neo__ } from "./_global--translation.js";
import { observeOnce } from "./_global--observer.js";
import { Dialog } from "./neo-draw--editor-react-dialog.js";
import { addQueryParams } from "./_global--url-helper.js";
import { hashString } from "./_global--hash.js";
import { pluginUrl } from "./_global-plugin-and-uploads-url.js";
import { jsVar } from "./_global--enqueue-loader.js";


const img = new Image(); img.src = pluginUrl() + "/img/neo-draw--editor-dialog-save-warn-icon.svg";
img.style.display = "none"; (await observeOnce("body")).appendChild(img);



export const SaveMultiUsageDialog = ({ onAnswer, imgUrl, dbEntries, countInCurrentPost }) => {

    const [hideUntilChanged, setHideUntilChanged] = React.useState(false);
    const currentPostUrlsHash = hashString(JSON.stringify(dbEntries.map(entry => entry.postUrl)));
    let hiddenPostUrlHashes = JSON.parse(localStorage.getItem("neo-draw--hidden-post-urls-hashes") || "{}");
    const hideDialogNextTimeIfChecked = React.useCallback(() => {
        if (hideUntilChanged) {
            hiddenPostUrlHashes = JSON.parse(localStorage.getItem("neo-draw--hidden-post-urls-hashes") || "{}");
            hiddenPostUrlHashes[imgUrl] = currentPostUrlsHash;
            localStorage.setItem("neo-draw--hidden-post-urls-hashes", JSON.stringify(hiddenPostUrlHashes));
        }
    }, [currentPostUrlsHash, hideUntilChanged, imgUrl]);
    const answerWithDefaultButton = React.useCallback(() => { hideDialogNextTimeIfChecked(); onAnswer("changeAll"); }, [hideDialogNextTimeIfChecked, onAnswer]);
    React.useEffect(() => {
        document.activeElement?.blur();
        const answerOnDialogKey = (event) => {
            if (event.key === "Enter") { event.preventDefault(); event.stopImmediatePropagation(); answerWithDefaultButton(); }
            if (event.key === "Escape") { event.preventDefault(); event.stopImmediatePropagation(); onAnswer("cancel"); }
        };
        window.addEventListener("keydown", answerOnDialogKey, true);
        return () => window.removeEventListener("keydown", answerOnDialogKey, true);
    }, [answerWithDefaultButton, onAnswer]);
    const skipDialogBecauseHidden = hiddenPostUrlHashes[imgUrl] === currentPostUrlsHash;
    React.useEffect(() => {
        if (skipDialogBecauseHidden) { onAnswer("changeAll"); return; }
        delete hiddenPostUrlHashes[imgUrl];
        localStorage.setItem("neo-draw--hidden-post-urls-hashes", JSON.stringify(hiddenPostUrlHashes));
    }, [currentPostUrlsHash, imgUrl, onAnswer, skipDialogBecauseHidden]);
    if (skipDialogBecauseHidden) { return null; }

    return React.createElement(
        Dialog,
        { onClose: () => onAnswer("cancel") },
        React.createElement(
            "img",
            {
                className: "neo-draw--dialog-icon",
                src: pluginUrl() + "/img/neo-draw--editor-dialog-save-warn-icon.svg",
                alt: "",
            }
        ),
        React.createElement(
            "div",
            null,
            neo__("The image is used multiple times on the site.", "Das Bild wird auf der Seite mehrmals verwendet."),
            " ",
            React.createElement("a", {
                href: addQueryParams(jsVar("neoDrawEditorDbEntriesUsageUrl"), { "img-url": imgUrl, "db-entries": dbEntries, "count-in-current-post": countInCurrentPost }),
                target: "_blank",
                style: { color: "#444" }
            }, neo__("Show where it is used (in new tab)", "Alle Verwendungen anzeigen (in neuem Tab)"))
        ),
        React.createElement(
            "div",
            { className: "excalidraw neo-draw--dialog-button-container" },
            React.createElement(
                "input",
                {
                    type: "checkbox",
                    id: "hideUntilChanged",
                    checked: hideUntilChanged,
                    onChange: (e) => setHideUntilChanged(e.target.checked),
                    tabIndex: 0
                }
            ),
            React.createElement(
                "label",
                {
                    htmlFor: "hideUntilChanged",
                    style: { marginLeft: "0.5em" }
                },
                neo__("Hide message for this image", "Meldung für dieses Bild nicht mehr anzeigen")
            )
        ),
        React.createElement(
            "div",
            { className: "excalidraw neo-draw--dialog-button-container" },
            React.createElement(
                "button",
                {
                    className: "excalidraw-button neo-draw--dialog-button",
                    onClick: () => onAnswer("createNew"),
                    tabIndex: 0
                },
                neo__("Keep others & save as copy", "Andere behalten & als Kopie speichern")
            ),
            React.createElement(
                "button",
                {
                    className: "excalidraw-button neo-draw--dialog-button neo-draw--dialog-primary-button",
                    onClick: answerWithDefaultButton,
                    tabIndex: 0
                },
                neo__("Change all", "Alle ändern")
            ),
        )
    );
};
