import { jsxs as u, jsx as t } from "@emotion/react/jsx-runtime";
import { useModuleDictionary as Me } from "@m4l/core";
import { useIsMobile as _e } from "@m4l/graphics";
import { LayoutTableFill as be, ActionsEditOutlined as ge, ActionsTrashOutlined as Se, ActionsAddSquareOutlined as we } from "@m4l/icons";
import { Tooltip as Ee, Icon as ve, Typography as ye } from "@m4l/base";
import Le from "clsx";
import * as Te from "yup";
import { useState as h, useRef as Ce, useEffect as Oe } from "react";
import { shallow as p } from "zustand/shallow";
import { getComponentSlotRoot as De } from "../../../../utils/getComponentSlotRoot.js";
import { getPropDataTestId as Pe } from "../../../../test/getNameDataTestId.js";
import { useModal as xe } from "../../../../hooks/useModal/index.js";
import { MenuDivider as Re } from "../../../extended/mui/MenuDivider/MenuDivider.js";
import { getAreasDictionary as i, AREAS_DICCTIONARY as l } from "../../dictionary.js";
import { useAreasStore as c } from "../../hooks/useAreas/index.js";
import { AREAS_ADMIN_TOOLTIP_DELAY_PROPS as Ne, AREAS_MENU_MAX_VISIBLE_ITEMS as $e, AREAS_ADMIN_KEY_COMPONENT as W, DEFAULT_HORIZONTAL_MODULE_ITEM_LIMIT as ze, DEFAULT_VERTICAL_MODULE_ITEM_LIMIT as We } from "./constants.js";
import { AreasAdminRootStyled as ke, AreasAdminContentStyled as Be, AreasTriggerButtonStyled as Fe, AreasMenuContentStyled as Ve, AreasMenuScrollAreaStyled as Ue, AreasMenuListStyled as He, AreaMenuItemActionsStyled as je, AreaMenuActionButtonStyled as k, AreasMenuFooterStyled as Ye, ButtonAddAreaStyled as qe, AreasSectionDividerStyled as Ke, EditAreaHeaderStyled as Xe } from "./slots/AreasAdminSlots.js";
import { createValidationSchema as Ze, createValidationFullObject as Ge, createValidationPartialObject as Je } from "../../../hook-form/RHFormProvider/schema.js";
import { ContainerModules as Qe } from "./subcomponents/ContainerModules/ContainerModules.js";
import { RHFormProvider as et } from "../../../hook-form/RHFormProvider/RHFormProvider.js";
import { RHFTextField as tt } from "../../../hook-form/RHFTextField/RHFTextField.js";
import { ActionsContainer as rt } from "../../../CommonActions/components/ActionsContainer/ActionsContainer.js";
import { Popover as B } from "../../../extended/mui/Popover/Popover.js";
import { MenuItem as F } from "../../../extended/mui/MenuItem/MenuItem.js";
import { ActionCancel as ot } from "../../../CommonActions/components/ActionCancel/ActionCancel.js";
import { ActionIntro as nt } from "../../../CommonActions/components/ActionIntro/ActionIntro.js";
import { AreasAdminSlots as at } from "./slots/AreasAdminEnum.js";
import { WindowConfirm as it } from "../../../WindowConfirm/WindowConfirm.js";
function lt(g, f) {
  return f !== void 0 ? Math.max(f, 1) : g === "horizontal" ? ze : We;
}
const Nt = (g) => {
  const {
    color: f = "primary",
    size: o = "medium",
    orientation: m = "vertical",
    moduleItemLimit: V,
    className: U,
    dataTestId: H,
    ...j
  } = g, Y = _e(), { getLabel: n } = Me(), { openModal: q } = xe(), [I, T] = h(null), [S, C] = h(null), [K, O] = h(null), [A, D] = h(null), [w, E] = h(null), P = Ce(null), d = c(
    (e) => e.areasIds.map((r) => ({ id: r, name: e.hashAreas[r].name })),
    p
  ), M = c((e) => e.currentAreaId, p), X = c((e) => e.ownerState?.status), { addArea: Z, deleteArea: G, editArea: J, selectArea: Q } = c((e) => e.areasActions, p), { maximizeLayout: ee } = c((e) => e.areaActions, p), te = c(
    (e) => e.currentAreaId ? e.hashAreas[e.currentAreaId]?.currentLayoutId : ""
  ), x = c(
    (e) => e.currentAreaId ? e.hashAreas[e.currentAreaId]?.maximizedId : void 0
  ), R = c(
    (e) => e.hashAreas[e.currentAreaId]?.layoutItemsIds?.filter((r) => e.hashWindows[r].emergeType === "layout")?.map((r) => {
      const a = e.hashWindows[r], s = a.moduleCount;
      return {
        iconUrl: a.iconUrl,
        id: a.windowId,
        label: `${a.title}${s ? `:${s}` : ""}`,
        title: a.title
      };
    }) ?? [],
    p
  ), _ = !!I;
  if (Oe(() => {
    if (!_ || !w)
      return;
    const e = Array.from(
      P.current?.querySelectorAll("[data-area-menu-item-id]") ?? []
    ).find((r) => r.dataset.areaMenuItemId === w);
    e && (e.scrollIntoView?.({ block: "nearest" }), E(null));
  }, [d, _, w]), X !== "loaded")
    return null;
  const v = n(i(l.label_new_area)) || "Open areas menu", re = n(i(l.area_add_new)) || "Add area", N = n(i(l.label_edit_area)) || "Edit area", oe = n(i(l.label_delete_area)) || "Delete area", ne = n(i(l.label_delete_area_confirm_title)) || "Delete work area", ae = n(i(l.label_delete_area_confirm_message)) || "This action is irreversible. Do you want to permanently delete this work area?", $ = d.find((e) => e.id === M)?.name ?? "", ie = n(i(l.label_window)) || "Window", le = n(i(l.label_windows)) || "Windows", y = !!x && R.length > 1, de = lt(m, V), se = x || te || !1, L = {
    color: f,
    hasModules: y,
    isMobile: Y,
    orientation: m,
    size: o
  };
  function ce(e) {
    e.stopPropagation(), T(e.currentTarget);
  }
  function z() {
    I?.blur(), T(null), E(null), b();
  }
  function me(e, r) {
    e.stopPropagation();
    const a = e.currentTarget.closest("li") ?? e.currentTarget, s = a.getBoundingClientRect();
    C(a), O({ left: s.right, top: s.top + s.height / 2 }), D(r);
  }
  function b() {
    C(null), O(null), D(null);
  }
  function ue(e) {
    A && (J(A, e.inputEditArea), b());
  }
  function Ae(e, r) {
    if (e.stopPropagation(), d.length > 1) {
      const a = d.find((s) => s.id === r)?.name;
      q({
        variant: "warning",
        window: /* @__PURE__ */ t(
          it,
          {
            variant: "warning",
            title: ne,
            msg: `${ae} (${a})`,
            onClickIntro: () => G(r),
            size: o
          }
        )
      });
    }
  }
  function he(e) {
    Q(e), z();
  }
  function pe() {
    const e = Z();
    e && E(e);
  }
  function fe(e) {
    ee(M, e);
  }
  const Ie = Ze(
    Ge(
      Je({
        inputEditArea: Te.string().required(
          n(i(l.validation_edit_area))
        )
      })
    )
  );
  return /* @__PURE__ */ u(
    ke,
    {
      className: Le(De(W), U),
      ownerState: L,
      role: "areas-admin-role",
      ...Pe(W, at.root, H),
      ...j,
      children: [
        /* @__PURE__ */ u(Be, { ownerState: L, children: [
          /* @__PURE__ */ t(
            Ee,
            {
              ...Ne,
              title: $ ? `${v}: ${$}` : v,
              children: /* @__PURE__ */ t(
                Fe,
                {
                  "aria-label": v,
                  color: I ? "primary" : "default",
                  icon: /* @__PURE__ */ t(be, {}),
                  onClick: ce,
                  size: o,
                  selected: _,
                  variant: "text"
                }
              )
            }
          ),
          /* @__PURE__ */ t(
            B,
            {
              anchorEl: I,
              anchorOrigin: m === "vertical" ? { horizontal: "right", vertical: "top" } : { horizontal: "right", vertical: "bottom" },
              arrowType: "right-top",
              onClose: z,
              open: _,
              slotProps: {
                paper: {
                  sx: {
                    // Pin the areas menu to a fixed, safe width so growing content
                    // (long area names) can no longer widen or shift the popover.
                    width: 230,
                    maxWidth: 230,
                    minWidth: 230,
                    ...m === "vertical" ? { ml: 1.5 } : { mt: 1 }
                  }
                }
              },
              transformOrigin: m === "vertical" ? { horizontal: "left", vertical: "top" } : { horizontal: "right", vertical: "top" },
              children: /* @__PURE__ */ u(Ve, { children: [
                /* @__PURE__ */ t(
                  Ue,
                  {
                    ref: P,
                    ownerState: { ...L, maxVisibleItems: $e },
                    children: /* @__PURE__ */ t(He, { children: d.length > 0 ? d.map((e) => /* @__PURE__ */ t(
                      F,
                      {
                        "data-area-menu-item-id": e.id,
                        endAdornment: e.id === M ? /* @__PURE__ */ u(je, { children: [
                          /* @__PURE__ */ t(
                            k,
                            {
                              "aria-label": `${N}: ${e.name}`,
                              icon: /* @__PURE__ */ t(ge, {}),
                              onClick: (r) => me(r, e.id),
                              size: o,
                              variant: "text"
                            }
                          ),
                          /* @__PURE__ */ t(
                            k,
                            {
                              "aria-label": `${oe}: ${e.name}`,
                              color: "error",
                              disabled: d.length === 1,
                              icon: /* @__PURE__ */ t(Se, {}),
                              onClick: (r) => Ae(r, e.id),
                              size: o,
                              variant: "text"
                            }
                          )
                        ] }) : void 0,
                        label: e.name,
                        onClick: () => he(e.id),
                        selected: e.id === M,
                        size: o
                      },
                      e.id
                    )) : /* @__PURE__ */ t(
                      F,
                      {
                        disabled: !0,
                        label: n(i(l.label_no_areas_available)) || "No areas available",
                        size: o
                      }
                    ) })
                  }
                ),
                /* @__PURE__ */ t(Re, { variant: "solid", size: o }),
                /* @__PURE__ */ t(Ye, { children: /* @__PURE__ */ t(
                  qe,
                  {
                    endIcon: /* @__PURE__ */ t(ve, { icon: /* @__PURE__ */ t(we, {}) }),
                    label: re,
                    onClick: pe,
                    size: o,
                    color: "default",
                    variant: "contained",
                    fullWidth: !0
                  }
                ) })
              ] })
            }
          ),
          m === "vertical" && y ? /* @__PURE__ */ t(
            Ke,
            {
              customVariant: "solid",
              "data-testid": "AreasAdminTriggerDivider",
              orientation: "horizontal",
              size: o
            }
          ) : null,
          y ? /* @__PURE__ */ t(
            Qe,
            {
              itemLimit: de,
              items: R,
              menuHeaderLabel: le,
              onSelect: fe,
              orientation: m,
              overflowLabel: `More ${ie.toLowerCase()} modules`,
              selectedItemId: se,
              size: o
            }
          ) : null
        ] }),
        A ? /* @__PURE__ */ t(
          B,
          {
            anchorEl: S,
            anchorPosition: K ?? void 0,
            anchorReference: "anchorPosition",
            arrowType: "no-arrow",
            container: S?.closest('[aria-label="Paper-popover-root"]'),
            onClose: b,
            open: !!S,
            slotProps: { paper: { sx: { ml: 4, minWidth: 220 } } },
            transformOrigin: { horizontal: "left", vertical: "center" },
            children: /* @__PURE__ */ u(
              et,
              {
                onSubmit: ue,
                validationSchema: Ie,
                values: {
                  inputEditArea: d.find((e) => e.id === A)?.name ?? ""
                },
                children: [
                  /* @__PURE__ */ t(Xe, { children: /* @__PURE__ */ t(ye, { color: "text.secondary", variant: "bodyDens", children: N }) }),
                  /* @__PURE__ */ t(tt, { name: "inputEditArea" }),
                  /* @__PURE__ */ u(rt, { children: [
                    /* @__PURE__ */ t(
                      ot,
                      {
                        onClick: b,
                        size: o,
                        variant: "contained"
                      }
                    ),
                    /* @__PURE__ */ t(nt, { size: o })
                  ] })
                ]
              },
              A
            )
          }
        ) : null
      ]
    }
  );
};
export {
  Nt as AreasAdmin
};
