import FileManagerModal from "./file-manager-modal.js";
import html from "../../services/html.js";
import { buildConfirmCancelButtons, openPluginModal, } from "./modal-controller.js";
import t from "../../i18n/index.js";
export default class MultipleSizedImagesModal {
    constructor(element, onChange, sizes, markup) {
        this.initImages = () => {
            const targets = Array.from(this.element.querySelectorAll("img, source"));
            targets.forEach((target) => {
                const isImg = target.tagName === "IMG";
                if (isImg) {
                    const src = target.getAttribute("src");
                    const metadata = target.getAttribute("data-metadata");
                    const image = this.root.querySelector('[data-key="default"] img');
                    if (src && image) {
                        image.setAttribute("src", src);
                        if (metadata) {
                            image.setAttribute("data-metadata", metadata);
                        }
                    }
                }
                else {
                    const src = target.getAttribute("srcset");
                    const metadata = target.getAttribute("data-metadata");
                    const mediaAttr = target.getAttribute("media");
                    if (mediaAttr) {
                        const key = mediaAttr.replace(/\(|\)/g, "");
                        const image = this.root.querySelector(`[data-key="${key}"] img`);
                        if (image && src) {
                            image.setAttribute("src", src);
                            if (metadata) {
                                image.setAttribute("data-metadata", metadata);
                            }
                        }
                    }
                }
            });
        };
        this.updateImages = () => {
            this.imagesElements = Array.from(this.root.querySelectorAll(".modal__size img"));
            if (!this.sizes)
                return;
            const sizes = this.sizes;
            this.results = this.imagesElements.map((element, i) => {
                const key = Object.keys(sizes)[i];
                const { src } = element;
                const width = element.getAttribute("width") || "";
                const height = element.getAttribute("height") || "";
                const metadata = element.getAttribute("data-metadata") || "";
                return { key, src, width, height, metadata };
            });
        };
        this.closeModal = () => {
            this.root.removeEventListener("click", this.onClick);
        };
        this.onClick = async (e) => {
            const target = e.target;
            const editButton = target?.closest(".modal__size-button--edit");
            const cropButton = target?.closest(".modal__size-button--crop");
            if (editButton || cropButton) {
                const button = (editButton || cropButton);
                const image = button
                    .closest(".modal__size")
                    ?.querySelector("img");
                const width = image && image.hasAttribute("width")
                    ? parseInt(image.getAttribute("width") || "", 10)
                    : undefined;
                const height = image && image.hasAttribute("height")
                    ? parseInt(image.getAttribute("height") || "", 10)
                    : undefined;
                const metadata = cropButton && image
                    ? (image.getAttribute("data-metadata") ?? undefined)
                    : undefined;
                if (image) {
                    await editImage(image, width, height, metadata, this.updateImages);
                }
            }
            const removeButton = target?.closest(".modal__size-button--remove");
            if (removeButton) {
                const imageContainer = removeButton.closest(".modal__size");
                if (imageContainer) {
                    const image = imageContainer.querySelector("img");
                    if (image && this.sizes) {
                        const index = this.imagesElements.indexOf(image);
                        const keys = Object.keys(this.sizes);
                        const { src, width, height } = this.sizes[keys[index]];
                        const html = Object.assign(document.createElement("img"), {
                            src,
                            width,
                            height,
                        }).outerHTML;
                        image.outerHTML = html;
                        this.updateImages();
                    }
                }
            }
        };
        this.onConfirm = () => {
            this.onChange(this.results);
        };
        this.element = element;
        this.markup = markup;
        this.onChange = onChange;
        const defaultImage = Object.assign(document.createElement("div"), {
            innerHTML: this.markup,
        }).querySelector("img");
        const defaultSrc = defaultImage?.getAttribute("src") || "";
        const defaultWidth = parseInt(defaultImage?.getAttribute("width") || "0", 10) || undefined;
        const defaultHeight = parseInt(defaultImage?.getAttribute("height") || "0", 10) || undefined;
        this.sizes = {
            default: { src: defaultSrc, width: defaultWidth, height: defaultHeight },
            ...sizes,
        };
    }
    init() {
        this.modal = openPluginModal({
            icon: "image",
            title: t("modals.multiple-images.title"),
            content: template(this.sizes),
            onClose: this.closeModal,
            buttons: buildConfirmCancelButtons({
                confirmLabel: t("common.confirm"),
                onConfirm: this.onConfirm,
                autofocus: true,
            }),
        });
        this.root = this.modal.shadowRoot;
        this.initImages();
        this.updateImages();
        this.root.addEventListener("click", this.onClick);
    }
}
function imageChanged(img, callback) {
    return (path, metadata) => {
        img.setAttribute("src", path);
        img.setAttribute("data-metadata", metadata);
        callback();
    };
}
async function editImage(img, width, height, metadata, callback) {
    new FileManagerModal({
        callback: imageChanged(img, callback),
        width,
        height,
        metadata,
    });
}
function getTitle(key) {
    const value = key.replace(/[^0-9]/g, "");
    switch (true) {
        case key === "default": {
            return "Image par défaut";
        }
        case key.includes("min-width"): {
            return `Écrans > ${value}px de large`;
        }
        case key.includes("max-width"): {
            return `Écrans < ${value}px de large`;
        }
        case key.includes("min-height"): {
            return `Écrans > ${value}px de haut`;
        }
        case key.includes("max-height"): {
            return `Écrans < ${value}px de haut`;
        }
        case key.includes("landscape"): {
            return "Écrans paysages";
        }
        case key.includes("portrait"): {
            return "Écrans portraits";
        }
        default: {
            return value;
        }
    }
}
function renderImages(sizes) {
    if (!sizes)
        return;
    const keys = Object.keys(sizes);
    return keys
        .map((key) => {
        const size = sizes[key];
        const { src, width, height } = size;
        const image = Object.assign(document.createElement("img"), { src });
        if (width) {
            image.setAttribute("width", width.toString());
        }
        if (height) {
            image.setAttribute("height", height.toString());
        }
        const htmlContent = image.outerHTML;
        const title = getTitle(key);
        return html `
        <div class="modal__size" data-key="${key}">
          <div class="modal__size-title">${title}</div>
          ${htmlContent}
          <div class="modal__size-buttons">
            <button
              is="eden-button"
              tooltip="${t("modals.multiple-images.replace-image")}"
              class="modal__size-button modal__size-button--edit"
            >
              <eden-icon code="pen" class="modal__size-button-icon"></eden-icon>
            </button>
            <button
              is="eden-button"
              tooltip="${t("modals.multiple-images.crop-image")}"
              class="modal__size-button modal__size-button--crop"
            >
              <eden-icon
                code="crop"
                class="modal__size-button-icon"
              ></eden-icon>
            </button>
            <button
              is="eden-button"
              tooltip="${t("modals.multiple-images.remove-image")}"
              class="modal__size-button modal__size-button--remove"
            >
              <eden-icon
                code="delete"
                class="modal__size-button-icon"
              ></eden-icon>
            </button>
          </div>
        </div>
      `;
    })
        .join("");
}
function template(sizes) {
    return html `
    <style>
      .modal__inner {
        width: 700px;
        display: flex;
        flex-direction: column;
        gap: 10px;
      }

      .modal__sizes {
        max-width: 100%;
        display: flex;
        padding: 10px 0;
        gap: 20px;
        overflow: auto;
        box-sizing: border-box;
      }

      .modal__size {
        position: relative;
        min-width: 0;
        flex: 0 0 auto;
        display: flex;
        flex-direction: column;
      }

      .modal__size-title {
        margin-bottom: 5px;
        font-size: 12px;
        color: var(--eden-grey-500);
        user-select: none;
        white-space: nowrap;
      }

      .modal__size-buttons {
        position: absolute;
        bottom: 8px;
        right: 8px;
        display: flex;
        gap: 6px;
      }

      .modal__size-button {
        width: 26px;
        height: 26px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: var(--eden-grey-000);
        border: none;
        border-radius: var(--eden-radius-100);
      }

      .modal__size-button:focus {
        outline: none;
      }

      .modal__size-button:focus-visible {
        outline: 2px solid var(--eden-secondary-color);
        outline-offset: 3px;
      }

      .modal__size-button--edit,
      .modal__size-button--crop {
        background-color: var(--eden-primary-color);
      }

      .modal__size
        img:not([data-metadata])
        + .modal__size-buttons
        .modal__size-button--crop {
        display: none;
      }

      .modal__size-button--remove {
        background-color: var(--eden-red-400);
      }

      .modal__size-button-icon {
        width: 20px;
        height: 20px;
        fill: currentcolor;
      }

      .modal__size img {
        width: auto;
        height: 240px;
        border-radius: var(--eden-radius-200);
      }

      .modal__helper {
        display: flex;
        gap: 10px;
        padding: 10px;
        background-color: var(--eden-grey-100);
        border-radius: var(--eden-radius-200);
      }

      .modal__helper-icon {
        flex: 0 0 26px;
        height: 26px;
        fill: var(--eden-grey-500);
      }

      .modal__helper-text {
        font-size: 15px;
      }
    </style>
    <div class="modal__inner">
      <div class="modal__sizes">${renderImages(sizes)}</div>
      <div class="modal__helper">
        <eden-icon code="information" class="modal__helper-icon"></eden-icon>
        <div class="modal__helper-text">
          ${t("modals.multiple-images.helper-text")}
          <br />
          <br />
          <b>${t("modals.multiple-images.helper-first-required")}</b>,
          ${t("modals.multiple-images.helper-optional")}
        </div>
      </div>
    </div>
  `;
}
