import { defineComponent as Z, ref as v, computed as $, resolveComponent as G, createElementBlock as c, openBlock as r, createElementVNode as s, createVNode as I, unref as h, createCommentVNode as T, normalizeClass as E, toDisplayString as U, createStaticVNode as B, Fragment as P, renderList as O, createBlock as oe, withCtx as R } from "vue";
import { J as A, F as ne } from "./jszip.min-JM2t-R2Y.js";
import { G as le, u as ie, J as D, a2 as re, N as ce, O as de, P as me } from "./index.vue_vue_type_script_setup_true_lang-BMVa5UfU.js";
import { useI18n as ue } from "@feedmepos/mf-common";
import { FmButtonVariant as z, useSnackbar as V, useDialog as ge, FmButtonColorThemeVariant as M } from "@feedmepos/ui-library";
import { _ as pe } from "./PageLayout.vue_vue_type_script_setup_true_lang-2f0QfweQ.js";
import { u as fe, a as he } from "./menu-DNLXOwiM.js";
import { a as ye } from "./Product.vue_vue_type_script_setup_true_lang-C8rOVEcT.js";
import { t as be, v as ve, w as _e } from "./item-BZS28ZS_.js";
const we = { class: "h-full flex flex-col" }, xe = { class: "flex items-center justify-between p-16 border-b border-gray-200" }, Ie = { class: "flex gap-8" }, ke = { class: "border-b border-gray-200" }, Ce = { class: "flex" }, Ue = { class: "flex-1 overflow-hidden" }, je = {
  key: 0,
  class: "h-full flex flex-col"
}, Fe = {
  key: 0,
  class: "flex-1 flex items-center justify-center"
}, Se = {
  key: 1,
  class: "flex-1 overflow-y-auto p-16"
}, Me = { class: "space-y-12" }, $e = { class: "fm-typo-en-body-sm font-medium" }, ze = { class: "flex" }, Pe = { class: "w-64 h-64 bg-gray-100 rounded-8 overflow-hidden flex items-center justify-center" }, Le = ["src", "alt"], Ne = {
  key: 1,
  class: "text-gray-400 text-xs"
}, Te = { class: "flex" }, Ee = { class: "w-64 h-64 bg-gray-100 rounded-8 overflow-hidden" }, Be = ["src", "alt"], Oe = {
  key: 1,
  class: "h-full flex flex-col"
}, Re = {
  key: 0,
  class: "flex-1 flex items-center justify-center"
}, Ae = {
  key: 1,
  class: "flex-1 overflow-y-auto p-16"
}, De = { class: "space-y-12" }, Ve = { class: "fm-typo-en-body-sm font-medium break-all" }, Ze = { class: "flex" }, Ge = { class: "w-64 h-64 bg-gray-100 rounded-8 overflow-hidden" }, Je = ["src", "alt"], We = /* @__PURE__ */ Z({
  __name: "ImageUpdatePreview",
  props: {
    matchedImages: {},
    unmatchedImages: {}
  },
  emits: ["cancel", "update"],
  setup(L, { emit: j }) {
    const u = L, F = j, y = v("matched"), b = $(() => u.matchedImages.length), k = $(() => u.unmatchedImages.length);
    function _() {
      F("cancel");
    }
    function S() {
      F("update", u.matchedImages);
    }
    return (w, l) => {
      const x = G("fm-button");
      return r(), c("div", we, [
        s("div", xe, [
          l[2] || (l[2] = s("h2", { class: "fm-typo-en-headline-sm font-semibold" }, "Update Product Images", -1)),
          s("div", Ie, [
            I(x, {
              variant: h(z).Secondary,
              label: "Cancel",
              onClick: _
            }, null, 8, ["variant"]),
            I(x, {
              variant: h(z).Primary,
              label: "Update",
              disabled: b.value === 0,
              onClick: S
            }, null, 8, ["variant", "disabled"])
          ])
        ]),
        s("div", ke, [
          s("div", Ce, [
            s("button", {
              class: E([
                "px-16 py-12 font-medium text-sm border-b-2 transition-colors",
                y.value === "matched" ? "border-blue-500 text-blue-600 bg-blue-50" : "border-transparent text-gray-500 hover:text-gray-700"
              ]),
              onClick: l[0] || (l[0] = (m) => y.value = "matched")
            }, " Matched Images (" + U(b.value) + ") ", 3),
            k.value > 0 ? (r(), c("button", {
              key: 0,
              class: E([
                "px-16 py-12 font-medium text-sm border-b-2 transition-colors",
                y.value === "unmatched" ? "border-blue-500 text-blue-600 bg-blue-50" : "border-transparent text-gray-500 hover:text-gray-700"
              ]),
              onClick: l[1] || (l[1] = (m) => y.value = "unmatched")
            }, " Unmatched Images (" + U(k.value) + ") ", 3)) : T("", !0)
          ])
        ]),
        s("div", Ue, [
          y.value === "matched" ? (r(), c("div", je, [
            b.value === 0 ? (r(), c("div", Fe, l[3] || (l[3] = [
              B('<div class="text-center text-gray-500"><svg class="mx-auto h-48 w-48 text-gray-400 mb-16" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg><p class="fm-typo-en-body-lg text-gray-500">No matched images found</p><p class="fm-typo-en-body-sm text-gray-400 mt-4"> Make sure your image filenames match product names </p></div>', 1)
            ]))) : (r(), c("div", Se, [
              l[4] || (l[4] = s("div", { class: "grid grid-cols-3 gap-16 pb-12 border-b border-gray-200 mb-16" }, [
                s("div", { class: "fm-typo-en-body-sm-600 font-semibold text-gray-700" }, "Product Name"),
                s("div", { class: "fm-typo-en-body-sm-600 font-semibold text-gray-700" }, "Current Image"),
                s("div", { class: "fm-typo-en-body-sm-600 font-semibold text-gray-700" }, "New Image")
              ], -1)),
              s("div", Me, [
                (r(!0), c(P, null, O(u.matchedImages, (m, C) => (r(), c("div", {
                  key: C,
                  class: "grid grid-cols-3 gap-16 py-12 border-b border-gray-100 items-center"
                }, [
                  s("div", $e, U(m.productName), 1),
                  s("div", ze, [
                    s("div", Pe, [
                      m.originalThumbnail ? (r(), c("img", {
                        key: 0,
                        src: m.originalThumbnail,
                        alt: m.productName,
                        class: "w-full h-full object-cover"
                      }, null, 8, Le)) : (r(), c("span", Ne, "No image"))
                    ])
                  ]),
                  s("div", Te, [
                    s("div", Ee, [
                      s("img", {
                        src: m.newImageUrl,
                        alt: m.newImage.name,
                        class: "w-full h-full object-cover"
                      }, null, 8, Be)
                    ])
                  ])
                ]))), 128))
              ])
            ]))
          ])) : y.value === "unmatched" ? (r(), c("div", Oe, [
            k.value === 0 ? (r(), c("div", Re, l[5] || (l[5] = [
              B('<div class="text-center text-gray-500"><svg class="mx-auto h-48 w-48 text-gray-400 mb-16" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg><p class="fm-typo-en-body-lg text-gray-500">All images matched!</p><p class="fm-typo-en-body-sm text-gray-400 mt-4">No unmatched images found</p></div>', 1)
            ]))) : (r(), c("div", Ae, [
              l[6] || (l[6] = s("div", { class: "grid grid-cols-2 gap-16 pb-12 border-b border-gray-200 mb-16" }, [
                s("div", { class: "fm-typo-en-body-sm-600 font-semibold text-gray-700" }, "Filename"),
                s("div", { class: "fm-typo-en-body-sm-600 font-semibold text-gray-700" }, "Image")
              ], -1)),
              s("div", De, [
                (r(!0), c(P, null, O(u.unmatchedImages, (m, C) => (r(), c("div", {
                  key: C,
                  class: "grid grid-cols-2 gap-16 py-12 border-b border-gray-100 items-center"
                }, [
                  s("div", Ve, U(m.filename), 1),
                  s("div", Ze, [
                    s("div", Ge, [
                      s("img", {
                        src: m.imageUrl,
                        alt: m.filename,
                        class: "w-full h-full object-cover"
                      }, null, 8, Je)
                    ])
                  ])
                ]))), 128))
              ])
            ]))
          ])) : T("", !0)
        ])
      ]);
    };
  }
});
var qe = { firebase: { storageBucket: "image.feedme.cc" } };
const He = {
  key: 0,
  class: "h-screen"
}, Xe = { class: "flex-1 flex justify-between gap-8 pl-8" }, Ke = { class: "flex items-center" }, Qe = { class: "bg-fm-color-neutral-gray-100 rounded-md px-8 py-4" }, Ye = { class: "fm-typo-en-body-md-600 font-semibold" }, et = { class: "flex gap-8" }, dt = /* @__PURE__ */ Z({
  __name: "ProductInternalTools",
  setup(L) {
    const { t: j } = ue(), u = le(V()), F = V(), y = ge(), b = ie(), { selectedCategories: k } = fe(), _ = v(!1), S = v(), w = v([]), l = v([]), x = $(() => {
      const e = D.flatten(k.value.map((a) => a.items));
      return D.uniqBy(e, (a) => a._id);
    }), m = $(() => x.value.length);
    async function C(e, a) {
      return await _e(e, {
        withTimestamp: !0,
        filename: a
      });
    }
    async function J(e, a = "images.zip") {
      const o = new A();
      e.forEach(({ blob: d, filename: n }) => {
        d && o.file(n, d);
      });
      const g = await o.generateAsync({ type: "blob" });
      ne.saveAs(g, a);
    }
    async function W() {
      const e = x.value.filter((a) => a.thumbnail);
      if (e.length === 0) {
        F.open({ type: "error", title: "No downloadable images found" });
        return;
      }
      y.open({
        title: "Download Images",
        message: `Found ${e.length} images, download as ZIP file?`,
        primaryActions: {
          text: "Download",
          close: !0
        },
        secondaryActions: {
          text: j("common.cancel"),
          close: !0
        }
      }).onPrimary(async () => {
        const a = v("Preparing download...");
        await u.minor(
          async () => {
            const o = e.filter((n) => n.thumbnail).map((n, p) => {
              let t = n.name || `image_${Date.now()}_${p}`;
              return t += ".jpg", {
                url: n.thumbnail,
                filename: t,
                index: p + 1
              };
            });
            a.value = `Starting download of ${o.length} images...`;
            const d = (await be(o, C, {
              batchSize: 5,
              // Download 5 images at a time
              batchDelay: 200,
              // 200ms delay between batches
              progressMessage: a
            })).filter((n) => n !== null);
            if (a.value = "Creating ZIP file...", d.length > 0) {
              const n = `images_${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.zip`;
              await J(d, n);
            } else
              throw new Error("Failed to fetch any images");
          },
          {
            message: a,
            successMessage: `Successfully downloaded ${e.length} images`,
            customId: "download-images"
          }
        );
      });
    }
    async function q(e) {
      const o = await new A().loadAsync(e), g = [];
      for (const [d, n] of Object.entries(o.files)) {
        if (n.dir || d.includes("__MACOSX/") || !N(d))
          continue;
        const p = await n.async("blob"), t = d.split("/").pop() || d, i = new File([p], t, { type: H(t) });
        g.push(i);
      }
      return g;
    }
    function N(e) {
      const a = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"], o = e.toLowerCase().substring(e.lastIndexOf("."));
      return a.includes(o);
    }
    function H(e) {
      const a = e.toLowerCase().substring(e.lastIndexOf("."));
      return {
        ".jpg": "image/jpeg",
        ".jpeg": "image/jpeg",
        ".png": "image/png",
        ".gif": "image/gif",
        ".webp": "image/webp",
        ".bmp": "image/bmp"
      }[a] || "image/jpeg";
    }
    function X(e) {
      return (e.substring(0, e.lastIndexOf(".")) || e).toLowerCase().trim().replace(/[_\-\s]+/g, " ");
    }
    function K(e) {
      return e.toLowerCase().trim().replace(/[_\-\s]+/g, " ");
    }
    async function Q(e) {
      const a = [];
      for (const t of e)
        if (t.type === "application/zip" || t.name.toLowerCase().endsWith(".zip")) {
          const i = await q(t);
          a.push(...i);
        } else N(t.name) && a.push(t);
      const o = /* @__PURE__ */ new Map();
      a.forEach((t) => {
        const i = t.name.toLowerCase();
        o.has(i) || o.set(i, t);
      });
      const g = Array.from(o.values()), d = [], n = [], p = /* @__PURE__ */ new Map();
      x.value.forEach((t) => {
        const i = K(t.name);
        p.set(i, t);
      });
      for (const t of g) {
        const i = X(t.name), f = p.get(i);
        f ? d.push({
          productId: f._id,
          productName: f.name,
          originalThumbnail: f.thumbnail,
          newImage: t,
          newImageUrl: URL.createObjectURL(t)
        }) : n.push({
          filename: t.name,
          file: t,
          imageUrl: URL.createObjectURL(t)
        });
      }
      return { matched: d, unmatched: n };
    }
    async function Y(e) {
      await u.minor(
        async () => {
          const { matched: a, unmatched: o } = await Q(e);
          w.value = a, l.value = o, _.value = !0;
        },
        {
          message: "Processing uploaded images...",
          customId: "process-images"
        }
      );
    }
    async function ee(e) {
      const a = v("Preparing image updates...");
      await u.minor(
        async () => {
          const o = async (t) => {
            const i = ce(t.productId);
            let f = "";
            return t.newImage && (await de.update(i, t.newImage, qe.firebase.storageBucket), f = me(i)), { productId: t.productId, newImageUrl: f };
          };
          a.value = `Starting upload of ${e.length} product images...`;
          const g = await ve({
            items: e,
            processor: o,
            batchSize: 5,
            // Upload 5 images at a time
            batchDelay: 200,
            // 200ms delay between batches
            onProgress: ({ batchStart: t, batchEnd: i, total: f }) => {
              a.value = `Uploading images ${t}-${i}/${f}...`;
            }
          });
          a.value = "Updating product data...";
          const d = b.state.menu, n = re(d), p = new Map(g.map((t) => [t == null ? void 0 : t.productId, t]));
          n.modules.item = n.modules.item.map((t) => {
            const i = p.get(t._id);
            return i && i.newImageUrl ? { ...t, thumbnail: i.newImageUrl } : t;
          }), await b.updateMenuSetting(n), await b.importMenu(n);
        },
        {
          message: a,
          successMessage: `Successfully updated ${e.length} product images`,
          customId: "update-product-images"
        }
      ), _.value = !1, w.value = [], l.value = [];
    }
    function te() {
      w.value.forEach((e) => URL.revokeObjectURL(e.newImageUrl)), l.value.forEach((e) => URL.revokeObjectURL(e.imageUrl)), _.value = !1, w.value = [], l.value = [];
    }
    function ae() {
      var e;
      (e = S.value) == null || e.click();
    }
    function se(e) {
      const a = e.target;
      if (a.files && a.files.length > 0) {
        const o = Array.from(a.files);
        Y(o);
      }
      a.value = "";
    }
    return he().resetOnMount(), (e, a) => {
      const o = G("fm-button");
      return r(), c(P, null, [
        _.value ? (r(), c("div", He, [
          I(We, {
            "matched-images": w.value,
            "unmatched-images": l.value,
            onCancel: te,
            onUpdate: ee
          }, null, 8, ["matched-images", "unmatched-images"])
        ])) : (r(), oe(pe, {
          key: 1,
          heading: h(j)("menu.productInternalTools.title")
        }, {
          default: R(() => [
            I(ye)
          ]),
          "append-heading": R(() => [
            s("div", Xe, [
              s("div", Ke, [
                s("div", Qe, [
                  s("p", Ye, U(m.value), 1)
                ])
              ]),
              s("div", et, [
                I(o, {
                  "bg-color": h(M).NeutralGray100,
                  "text-color": h(M).TypoSecondary,
                  variant: h(z).Primary,
                  label: "Download Images",
                  onClick: W
                }, null, 8, ["bg-color", "text-color", "variant"]),
                I(o, {
                  "bg-color": h(M).NeutralGray100,
                  "text-color": h(M).TypoSecondary,
                  variant: h(z).Primary,
                  label: "Update Images",
                  onClick: ae
                }, null, 8, ["bg-color", "text-color", "variant"])
              ])
            ])
          ]),
          _: 1
        }, 8, ["heading"])),
        s("input", {
          ref_key: "fileInput",
          ref: S,
          type: "file",
          multiple: "",
          accept: "image/*,.zip",
          style: { display: "none" },
          onChange: se
        }, null, 544)
      ], 64);
    };
  }
});
export {
  dt as default
};
